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/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 #define DEBUG_TYPE "x86-isel"
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64 SelectionDAG &DAG, SDLoc dl,
65 unsigned vectorWidth) {
66 assert((vectorWidth == 128 || vectorWidth == 256) &&
67 "Unsupported vector width");
68 EVT VT = Vec.getValueType();
69 EVT ElVT = VT.getVectorElementType();
70 unsigned Factor = VT.getSizeInBits()/vectorWidth;
71 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72 VT.getVectorNumElements()/Factor);
74 // Extract from UNDEF is UNDEF.
75 if (Vec.getOpcode() == ISD::UNDEF)
76 return DAG.getUNDEF(ResultVT);
78 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
79 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
81 // This is the index of the first element of the vectorWidth-bit chunk
83 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
86 // If the input is a buildvector just emit a smaller one.
87 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
92 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106 SelectionDAG &DAG, SDLoc dl) {
107 assert((Vec.getValueType().is256BitVector() ||
108 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114 SelectionDAG &DAG, SDLoc dl) {
115 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120 unsigned IdxVal, SelectionDAG &DAG,
121 SDLoc dl, unsigned vectorWidth) {
122 assert((vectorWidth == 128 || vectorWidth == 256) &&
123 "Unsupported vector width");
124 // Inserting UNDEF is Result
125 if (Vec.getOpcode() == ISD::UNDEF)
127 EVT VT = Vec.getValueType();
128 EVT ElVT = VT.getVectorElementType();
129 EVT ResultVT = Result.getValueType();
131 // Insert the relevant vectorWidth bits.
132 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
134 // This is the index of the first element of the vectorWidth-bit chunk
136 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
139 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
143 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference. Idx is an index in the 128 bits
147 /// we want. It need not be aligned to a 128-bit bounday. That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150 unsigned IdxVal, SelectionDAG &DAG,
152 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157 unsigned IdxVal, SelectionDAG &DAG,
159 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168 unsigned NumElems, SelectionDAG &DAG,
170 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175 unsigned NumElems, SelectionDAG &DAG,
177 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
181 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
182 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
183 bool is64Bit = Subtarget->is64Bit();
185 if (Subtarget->isTargetMacho()) {
187 return new X86_64MachoTargetObjectFile();
188 return new TargetLoweringObjectFileMachO();
191 if (Subtarget->isTargetLinux())
192 return new X86LinuxTargetObjectFile();
193 if (Subtarget->isTargetELF())
194 return new TargetLoweringObjectFileELF();
195 if (Subtarget->isTargetKnownWindowsMSVC())
196 return new X86WindowsTargetObjectFile();
197 if (Subtarget->isTargetCOFF())
198 return new TargetLoweringObjectFileCOFF();
199 llvm_unreachable("unknown subtarget type");
202 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
203 : TargetLowering(TM, createTLOF(TM)) {
204 Subtarget = &TM.getSubtarget<X86Subtarget>();
205 X86ScalarSSEf64 = Subtarget->hasSSE2();
206 X86ScalarSSEf32 = Subtarget->hasSSE1();
207 TD = getDataLayout();
209 resetOperationActions();
212 void X86TargetLowering::resetOperationActions() {
213 const TargetMachine &TM = getTargetMachine();
214 static bool FirstTimeThrough = true;
216 // If none of the target options have changed, then we don't need to reset the
217 // operation actions.
218 if (!FirstTimeThrough && TO == TM.Options) return;
220 if (!FirstTimeThrough) {
221 // Reinitialize the actions.
223 FirstTimeThrough = false;
228 // Set up the TargetLowering object.
229 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
231 // X86 is weird, it always uses i8 for shift amounts and setcc results.
232 setBooleanContents(ZeroOrOneBooleanContent);
233 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
234 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
236 // For 64-bit since we have so many registers use the ILP scheduler, for
237 // 32-bit code use the register pressure specific scheduling.
238 // For Atom, always use ILP scheduling.
239 if (Subtarget->isAtom())
240 setSchedulingPreference(Sched::ILP);
241 else if (Subtarget->is64Bit())
242 setSchedulingPreference(Sched::ILP);
244 setSchedulingPreference(Sched::RegPressure);
245 const X86RegisterInfo *RegInfo =
246 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
247 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
249 // Bypass expensive divides on Atom when compiling with O2
250 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
251 addBypassSlowDiv(32, 8);
252 if (Subtarget->is64Bit())
253 addBypassSlowDiv(64, 16);
256 if (Subtarget->isTargetKnownWindowsMSVC()) {
257 // Setup Windows compiler runtime calls.
258 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
259 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
260 setLibcallName(RTLIB::SREM_I64, "_allrem");
261 setLibcallName(RTLIB::UREM_I64, "_aullrem");
262 setLibcallName(RTLIB::MUL_I64, "_allmul");
263 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
266 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
267 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
269 // The _ftol2 runtime function has an unusual calling conv, which
270 // is modeled by a special pseudo-instruction.
271 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
273 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
274 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
277 if (Subtarget->isTargetDarwin()) {
278 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
279 setUseUnderscoreSetJmp(false);
280 setUseUnderscoreLongJmp(false);
281 } else if (Subtarget->isTargetWindowsGNU()) {
282 // MS runtime is weird: it exports _setjmp, but longjmp!
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(false);
286 setUseUnderscoreSetJmp(true);
287 setUseUnderscoreLongJmp(true);
290 // Set up the register classes.
291 addRegisterClass(MVT::i8, &X86::GR8RegClass);
292 addRegisterClass(MVT::i16, &X86::GR16RegClass);
293 addRegisterClass(MVT::i32, &X86::GR32RegClass);
294 if (Subtarget->is64Bit())
295 addRegisterClass(MVT::i64, &X86::GR64RegClass);
297 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
299 // We don't accept any truncstore of integer registers.
300 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
301 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
304 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
305 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
307 // SETOEQ and SETUNE require checking two conditions.
308 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
315 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
317 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
319 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
323 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
324 } else if (!TM.Options.UseSoftFloat) {
325 // We have an algorithm for SSE2->double, and we turn this into a
326 // 64-bit FILD followed by conditional FADD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
328 // We have an algorithm for SSE2, and we turn this into a 64-bit
329 // FILD for other targets.
330 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
333 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
335 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
336 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
338 if (!TM.Options.UseSoftFloat) {
339 // SSE has no i16 to fp conversion, only i32
340 if (X86ScalarSSEf32) {
341 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
342 // f32 and f64 cases are Legal, f80 case is not
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
350 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
353 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
354 // are Legal, f80 is custom lowered.
355 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
356 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
358 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
360 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
361 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
363 if (X86ScalarSSEf32) {
364 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
365 // f32 and f64 cases are Legal, f80 case is not
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
369 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
372 // Handle FP_TO_UINT by promoting the destination to a larger signed
374 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
376 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
378 if (Subtarget->is64Bit()) {
379 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
380 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
381 } else if (!TM.Options.UseSoftFloat) {
382 // Since AVX is a superset of SSE3, only check for SSE here.
383 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384 // Expand FP_TO_UINT into a select.
385 // FIXME: We would like to use a Custom expander here eventually to do
386 // the optimal thing for SSE vs. the default expansion in the legalizer.
387 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
389 // With SSE3 we can use fisttpll to convert to a signed i64; without
390 // SSE, we're stuck with a fistpll.
391 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
394 if (isTargetFTOL()) {
395 // Use the _ftol2 runtime function, which has a pseudo-instruction
396 // to handle its weird calling convention.
397 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
400 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401 if (!X86ScalarSSEf64) {
402 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
403 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
404 if (Subtarget->is64Bit()) {
405 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
406 // Without SSE, i64->f64 goes through memory.
407 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
411 // Scalar integer divide and remainder are lowered to use operations that
412 // produce two results, to match the available instructions. This exposes
413 // the two-result form to trivial CSE, which is able to combine x/y and x%y
414 // into a single instruction.
416 // Scalar integer multiply-high is also lowered to use two-result
417 // operations, to match the available instructions. However, plain multiply
418 // (low) operations are left as Legal, as there are single-result
419 // instructions for this in x86. Using the two-result multiply instructions
420 // when both high and low results are needed must be arranged by dagcombine.
421 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
423 setOperationAction(ISD::MULHS, VT, Expand);
424 setOperationAction(ISD::MULHU, VT, Expand);
425 setOperationAction(ISD::SDIV, VT, Expand);
426 setOperationAction(ISD::UDIV, VT, Expand);
427 setOperationAction(ISD::SREM, VT, Expand);
428 setOperationAction(ISD::UREM, VT, Expand);
430 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431 setOperationAction(ISD::ADDC, VT, Custom);
432 setOperationAction(ISD::ADDE, VT, Custom);
433 setOperationAction(ISD::SUBC, VT, Custom);
434 setOperationAction(ISD::SUBE, VT, Custom);
437 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
438 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
439 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
441 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
445 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
447 if (Subtarget->is64Bit())
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
450 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
451 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
452 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
453 setOperationAction(ISD::FREM , MVT::f32 , Expand);
454 setOperationAction(ISD::FREM , MVT::f64 , Expand);
455 setOperationAction(ISD::FREM , MVT::f80 , Expand);
456 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
458 // Promote the i8 variants and force them on up to i32 which has a shorter
460 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
463 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
464 if (Subtarget->hasBMI()) {
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
467 if (Subtarget->is64Bit())
468 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
470 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
471 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
472 if (Subtarget->is64Bit())
473 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
476 if (Subtarget->hasLZCNT()) {
477 // When promoting the i8 variants, force them to i32 for a shorter
479 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
482 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
492 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
494 if (Subtarget->is64Bit()) {
495 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
500 if (Subtarget->hasPOPCNT()) {
501 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
503 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
504 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
505 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
506 if (Subtarget->is64Bit())
507 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
510 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
512 if (!Subtarget->hasMOVBE())
513 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
515 // These should be promoted to a larger select which is supported.
516 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
517 // X86 wants to expand cmov itself.
518 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
519 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
520 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
522 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
523 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
526 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
528 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
530 if (Subtarget->is64Bit()) {
531 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
532 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
534 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
535 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537 // support continuation, user-level threading, and etc.. As a result, no
538 // other SjLj exception interfaces are implemented and please don't build
539 // your own exception handling based on them.
540 // LLVM/Clang supports zero-cost DWARF exception handling.
541 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
545 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
546 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
547 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
548 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
549 if (Subtarget->is64Bit())
550 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
551 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
552 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
553 if (Subtarget->is64Bit()) {
554 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
555 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
556 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
557 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
558 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
560 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
561 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
562 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
563 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
566 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
567 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
570 if (Subtarget->hasSSE1())
571 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
573 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
575 // Expand certain atomics
576 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
578 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
579 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
580 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
583 if (!Subtarget->is64Bit()) {
584 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
595 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
598 if (Subtarget->hasCmpxchg16b()) {
599 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
602 // FIXME - use subtarget debug flags
603 if (!Subtarget->isTargetDarwin() &&
604 !Subtarget->isTargetELF() &&
605 !Subtarget->isTargetCygMing()) {
606 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
609 if (Subtarget->is64Bit()) {
610 setExceptionPointerRegister(X86::RAX);
611 setExceptionSelectorRegister(X86::RDX);
613 setExceptionPointerRegister(X86::EAX);
614 setExceptionSelectorRegister(X86::EDX);
616 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
617 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
619 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
620 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
622 setOperationAction(ISD::TRAP, MVT::Other, Legal);
623 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
625 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
626 setOperationAction(ISD::VASTART , MVT::Other, Custom);
627 setOperationAction(ISD::VAEND , MVT::Other, Expand);
628 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
629 // TargetInfo::X86_64ABIBuiltinVaList
630 setOperationAction(ISD::VAARG , MVT::Other, Custom);
631 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
633 // TargetInfo::CharPtrBuiltinVaList
634 setOperationAction(ISD::VAARG , MVT::Other, Expand);
635 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
638 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
639 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
641 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642 MVT::i64 : MVT::i32, Custom);
644 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645 // f32 and f64 use SSE.
646 // Set up the FP register classes.
647 addRegisterClass(MVT::f32, &X86::FR32RegClass);
648 addRegisterClass(MVT::f64, &X86::FR64RegClass);
650 // Use ANDPD to simulate FABS.
651 setOperationAction(ISD::FABS , MVT::f64, Custom);
652 setOperationAction(ISD::FABS , MVT::f32, Custom);
654 // Use XORP to simulate FNEG.
655 setOperationAction(ISD::FNEG , MVT::f64, Custom);
656 setOperationAction(ISD::FNEG , MVT::f32, Custom);
658 // Use ANDPD and ORPD to simulate FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
662 // Lower this to FGETSIGNx86 plus an AND.
663 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
666 // We don't support sin/cos/fmod
667 setOperationAction(ISD::FSIN , MVT::f64, Expand);
668 setOperationAction(ISD::FCOS , MVT::f64, Expand);
669 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670 setOperationAction(ISD::FSIN , MVT::f32, Expand);
671 setOperationAction(ISD::FCOS , MVT::f32, Expand);
672 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
674 // Expand FP immediates into loads from the stack, except for the special
676 addLegalFPImmediate(APFloat(+0.0)); // xorpd
677 addLegalFPImmediate(APFloat(+0.0f)); // xorps
678 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679 // Use SSE for f32, x87 for f64.
680 // Set up the FP register classes.
681 addRegisterClass(MVT::f32, &X86::FR32RegClass);
682 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
684 // Use ANDPS to simulate FABS.
685 setOperationAction(ISD::FABS , MVT::f32, Custom);
687 // Use XORP to simulate FNEG.
688 setOperationAction(ISD::FNEG , MVT::f32, Custom);
690 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
692 // Use ANDPS and ORPS to simulate FCOPYSIGN.
693 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
696 // We don't support sin/cos/fmod
697 setOperationAction(ISD::FSIN , MVT::f32, Expand);
698 setOperationAction(ISD::FCOS , MVT::f32, Expand);
699 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
701 // Special cases we handle for FP constants.
702 addLegalFPImmediate(APFloat(+0.0f)); // xorps
703 addLegalFPImmediate(APFloat(+0.0)); // FLD0
704 addLegalFPImmediate(APFloat(+1.0)); // FLD1
705 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
708 if (!TM.Options.UnsafeFPMath) {
709 setOperationAction(ISD::FSIN , MVT::f64, Expand);
710 setOperationAction(ISD::FCOS , MVT::f64, Expand);
711 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
713 } else if (!TM.Options.UseSoftFloat) {
714 // f32 and f64 in x87.
715 // Set up the FP register classes.
716 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
719 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
720 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
721 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
724 if (!TM.Options.UnsafeFPMath) {
725 setOperationAction(ISD::FSIN , MVT::f64, Expand);
726 setOperationAction(ISD::FSIN , MVT::f32, Expand);
727 setOperationAction(ISD::FCOS , MVT::f64, Expand);
728 setOperationAction(ISD::FCOS , MVT::f32, Expand);
729 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
732 addLegalFPImmediate(APFloat(+0.0)); // FLD0
733 addLegalFPImmediate(APFloat(+1.0)); // FLD1
734 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
742 // We don't support FMA.
743 setOperationAction(ISD::FMA, MVT::f64, Expand);
744 setOperationAction(ISD::FMA, MVT::f32, Expand);
746 // Long double always uses X87.
747 if (!TM.Options.UseSoftFloat) {
748 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
750 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
752 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753 addLegalFPImmediate(TmpFlt); // FLD0
755 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
758 APFloat TmpFlt2(+1.0);
759 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
761 addLegalFPImmediate(TmpFlt2); // FLD1
762 TmpFlt2.changeSign();
763 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
766 if (!TM.Options.UnsafeFPMath) {
767 setOperationAction(ISD::FSIN , MVT::f80, Expand);
768 setOperationAction(ISD::FCOS , MVT::f80, Expand);
769 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
772 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
774 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775 setOperationAction(ISD::FRINT, MVT::f80, Expand);
776 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777 setOperationAction(ISD::FMA, MVT::f80, Expand);
780 // Always use a library call for pow.
781 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
782 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
783 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
785 setOperationAction(ISD::FLOG, MVT::f80, Expand);
786 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788 setOperationAction(ISD::FEXP, MVT::f80, Expand);
789 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
791 // First set operation action for all vector types to either promote
792 // (for widening) or expand (for scalarization). Then we will selectively
793 // turn on ones that can be effectively codegen'd.
794 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796 MVT VT = (MVT::SimpleValueType)i;
797 setOperationAction(ISD::ADD , VT, Expand);
798 setOperationAction(ISD::SUB , VT, Expand);
799 setOperationAction(ISD::FADD, VT, Expand);
800 setOperationAction(ISD::FNEG, VT, Expand);
801 setOperationAction(ISD::FSUB, VT, Expand);
802 setOperationAction(ISD::MUL , VT, Expand);
803 setOperationAction(ISD::FMUL, VT, Expand);
804 setOperationAction(ISD::SDIV, VT, Expand);
805 setOperationAction(ISD::UDIV, VT, Expand);
806 setOperationAction(ISD::FDIV, VT, Expand);
807 setOperationAction(ISD::SREM, VT, Expand);
808 setOperationAction(ISD::UREM, VT, Expand);
809 setOperationAction(ISD::LOAD, VT, Expand);
810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815 setOperationAction(ISD::FABS, VT, Expand);
816 setOperationAction(ISD::FSIN, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FCOS, VT, Expand);
819 setOperationAction(ISD::FSINCOS, VT, Expand);
820 setOperationAction(ISD::FREM, VT, Expand);
821 setOperationAction(ISD::FMA, VT, Expand);
822 setOperationAction(ISD::FPOWI, VT, Expand);
823 setOperationAction(ISD::FSQRT, VT, Expand);
824 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825 setOperationAction(ISD::FFLOOR, VT, Expand);
826 setOperationAction(ISD::FCEIL, VT, Expand);
827 setOperationAction(ISD::FTRUNC, VT, Expand);
828 setOperationAction(ISD::FRINT, VT, Expand);
829 setOperationAction(ISD::FNEARBYINT, VT, Expand);
830 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831 setOperationAction(ISD::MULHS, VT, Expand);
832 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833 setOperationAction(ISD::MULHU, VT, Expand);
834 setOperationAction(ISD::SDIVREM, VT, Expand);
835 setOperationAction(ISD::UDIVREM, VT, Expand);
836 setOperationAction(ISD::FPOW, VT, Expand);
837 setOperationAction(ISD::CTPOP, VT, Expand);
838 setOperationAction(ISD::CTTZ, VT, Expand);
839 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::CTLZ, VT, Expand);
841 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842 setOperationAction(ISD::SHL, VT, Expand);
843 setOperationAction(ISD::SRA, VT, Expand);
844 setOperationAction(ISD::SRL, VT, Expand);
845 setOperationAction(ISD::ROTL, VT, Expand);
846 setOperationAction(ISD::ROTR, VT, Expand);
847 setOperationAction(ISD::BSWAP, VT, Expand);
848 setOperationAction(ISD::SETCC, VT, Expand);
849 setOperationAction(ISD::FLOG, VT, Expand);
850 setOperationAction(ISD::FLOG2, VT, Expand);
851 setOperationAction(ISD::FLOG10, VT, Expand);
852 setOperationAction(ISD::FEXP, VT, Expand);
853 setOperationAction(ISD::FEXP2, VT, Expand);
854 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859 setOperationAction(ISD::TRUNCATE, VT, Expand);
860 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863 setOperationAction(ISD::VSELECT, VT, Expand);
864 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866 setTruncStoreAction(VT,
867 (MVT::SimpleValueType)InnerVT, Expand);
868 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
873 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874 // with -msoft-float, disable use of MMX as well.
875 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877 // No operations on x86mmx supported, everything uses intrinsics.
880 // MMX-sized vectors (other than x86mmx) are expected to be expanded
881 // into smaller operations.
882 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
883 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
884 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
885 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
886 setOperationAction(ISD::AND, MVT::v8i8, Expand);
887 setOperationAction(ISD::AND, MVT::v4i16, Expand);
888 setOperationAction(ISD::AND, MVT::v2i32, Expand);
889 setOperationAction(ISD::AND, MVT::v1i64, Expand);
890 setOperationAction(ISD::OR, MVT::v8i8, Expand);
891 setOperationAction(ISD::OR, MVT::v4i16, Expand);
892 setOperationAction(ISD::OR, MVT::v2i32, Expand);
893 setOperationAction(ISD::OR, MVT::v1i64, Expand);
894 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
895 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
896 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
897 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
902 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
903 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
904 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
905 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
906 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
910 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
912 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
915 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
916 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
917 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
918 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
919 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
920 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
921 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
922 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
923 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
924 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
925 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
929 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
932 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933 // registers cannot be used even for integer operations.
934 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
939 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
940 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
941 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
942 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
943 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
944 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
945 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
946 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
947 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
948 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
949 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
950 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
951 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
952 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
953 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
954 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
956 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
957 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
958 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
959 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
960 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
962 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
963 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
964 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
965 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
967 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
968 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
970 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
971 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
973 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
974 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
975 MVT VT = (MVT::SimpleValueType)i;
976 // Do not attempt to custom lower non-power-of-2 vectors
977 if (!isPowerOf2_32(VT.getVectorNumElements()))
979 // Do not attempt to custom lower non-128-bit vectors
980 if (!VT.is128BitVector())
982 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
983 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
984 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
987 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
988 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
990 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
994 if (Subtarget->is64Bit()) {
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
999 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1000 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to promote non-128-bit vectors
1004 if (!VT.is128BitVector())
1007 setOperationAction(ISD::AND, VT, Promote);
1008 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1009 setOperationAction(ISD::OR, VT, Promote);
1010 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1011 setOperationAction(ISD::XOR, VT, Promote);
1012 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1013 setOperationAction(ISD::LOAD, VT, Promote);
1014 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1015 setOperationAction(ISD::SELECT, VT, Promote);
1016 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1019 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1021 // Custom lower v2i64 and v2f64 selects.
1022 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1023 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1024 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1025 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1027 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1028 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1031 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1032 // As there is no 64-bit GPR available, we need build a special custom
1033 // sequence to convert from v2i32 to v2f32.
1034 if (!Subtarget->is64Bit())
1035 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1037 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1038 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1040 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1042 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1045 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1046 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1047 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1048 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1049 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1050 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1051 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1052 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1053 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1054 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1055 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1060 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1062 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1063 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1064 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1065 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1066 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1068 // FIXME: Do we need to handle scalar-to-vector here?
1069 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1072 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1073 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1074 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1075 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1076 // There is no BLENDI for byte vectors. We don't need to custom lower
1077 // some vselects for now.
1078 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1080 // i8 and i16 vectors are custom , because the source register and source
1081 // source memory operand types are not the same width. f32 vectors are
1082 // custom since the immediate controlling the insert encodes additional
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1085 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1086 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1087 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1089 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1090 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1092 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1094 // FIXME: these should be Legal but thats only for the case where
1095 // the index is constant. For now custom expand to deal with that.
1096 if (Subtarget->is64Bit()) {
1097 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1098 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1102 if (Subtarget->hasSSE2()) {
1103 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1104 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1106 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1107 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1109 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1110 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1112 // In the customized shift lowering, the legal cases in AVX2 will be
1114 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1115 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1117 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1118 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1120 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1123 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1124 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1126 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1127 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1128 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1129 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1131 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1132 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1133 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1135 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1146 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1148 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1159 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1161 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1162 // even though v8i16 is a legal type.
1163 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1164 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1165 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1167 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1168 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1169 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1171 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1172 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1174 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1176 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1177 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1179 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1182 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1183 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1186 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1187 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1188 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1190 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1191 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1192 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1194 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1195 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1196 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1197 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1199 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1200 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1201 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1202 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1203 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1204 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1205 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1206 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1207 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1208 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1209 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1210 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1212 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1213 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1214 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1215 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1216 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1217 setOperationAction(ISD::FMA, MVT::f32, Legal);
1218 setOperationAction(ISD::FMA, MVT::f64, Legal);
1221 if (Subtarget->hasInt256()) {
1222 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1223 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1224 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1225 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1227 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1228 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1229 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1230 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1232 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1233 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1234 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1235 // Don't lower v32i8 because there is no 128-bit byte mul
1237 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1238 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1239 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1240 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1242 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1243 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1245 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1246 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1247 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1248 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1250 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1251 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1252 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1253 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1255 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1256 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1257 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1258 // Don't lower v32i8 because there is no 128-bit byte mul
1261 // In the customized shift lowering, the legal cases in AVX2 will be
1263 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1264 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1266 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1267 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1269 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1271 // Custom lower several nodes for 256-bit types.
1272 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1273 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1274 MVT VT = (MVT::SimpleValueType)i;
1276 // Extract subvector is special because the value type
1277 // (result) is 128-bit but the source is 256-bit wide.
1278 if (VT.is128BitVector())
1279 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1281 // Do not attempt to custom lower other non-256-bit vectors
1282 if (!VT.is256BitVector())
1285 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1286 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1287 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1288 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1289 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1290 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1291 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1294 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1295 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1296 MVT VT = (MVT::SimpleValueType)i;
1298 // Do not attempt to promote non-256-bit vectors
1299 if (!VT.is256BitVector())
1302 setOperationAction(ISD::AND, VT, Promote);
1303 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1304 setOperationAction(ISD::OR, VT, Promote);
1305 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1306 setOperationAction(ISD::XOR, VT, Promote);
1307 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1308 setOperationAction(ISD::LOAD, VT, Promote);
1309 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1310 setOperationAction(ISD::SELECT, VT, Promote);
1311 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1315 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1316 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1317 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1318 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1319 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1321 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1322 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1323 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1325 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1326 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1327 setOperationAction(ISD::XOR, MVT::i1, Legal);
1328 setOperationAction(ISD::OR, MVT::i1, Legal);
1329 setOperationAction(ISD::AND, MVT::i1, Legal);
1330 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1331 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1332 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1333 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1334 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1335 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1337 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1338 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1339 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1340 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1341 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1342 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1344 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1346 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1347 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1348 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1349 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1350 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1351 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1354 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1355 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1356 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1357 if (Subtarget->is64Bit()) {
1358 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1359 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1360 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1361 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1363 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1364 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1365 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1366 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1367 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1368 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1370 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1371 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1372 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1374 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1375 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1376 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1377 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1378 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1379 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1380 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1381 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1382 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1383 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1384 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1385 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1386 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1388 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1389 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1390 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1391 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1392 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1393 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1395 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1396 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1398 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1401 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1403 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1404 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1405 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1406 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1407 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1408 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1410 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1411 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1413 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1414 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1416 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1418 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1419 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1421 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1422 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1424 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1425 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1427 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1428 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1429 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1430 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1431 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1432 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1434 // Custom lower several nodes.
1435 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1436 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1437 MVT VT = (MVT::SimpleValueType)i;
1439 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1440 // Extract subvector is special because the value type
1441 // (result) is 256/128-bit but the source is 512-bit wide.
1442 if (VT.is128BitVector() || VT.is256BitVector())
1443 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1445 if (VT.getVectorElementType() == MVT::i1)
1446 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1448 // Do not attempt to custom lower other non-512-bit vectors
1449 if (!VT.is512BitVector())
1452 if ( EltSize >= 32) {
1453 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1454 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1455 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1456 setOperationAction(ISD::VSELECT, VT, Legal);
1457 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1458 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1459 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1462 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1463 MVT VT = (MVT::SimpleValueType)i;
1465 // Do not attempt to promote non-256-bit vectors
1466 if (!VT.is512BitVector())
1469 setOperationAction(ISD::SELECT, VT, Promote);
1470 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1474 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1475 // of this type with custom code.
1476 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1477 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1478 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1482 // We want to custom lower some of our intrinsics.
1483 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1484 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1485 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1486 if (!Subtarget->is64Bit())
1487 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1489 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1490 // handle type legalization for these operations here.
1492 // FIXME: We really should do custom legalization for addition and
1493 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1494 // than generic legalization for 64-bit multiplication-with-overflow, though.
1495 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1496 // Add/Sub/Mul with overflow operations are custom lowered.
1498 setOperationAction(ISD::SADDO, VT, Custom);
1499 setOperationAction(ISD::UADDO, VT, Custom);
1500 setOperationAction(ISD::SSUBO, VT, Custom);
1501 setOperationAction(ISD::USUBO, VT, Custom);
1502 setOperationAction(ISD::SMULO, VT, Custom);
1503 setOperationAction(ISD::UMULO, VT, Custom);
1506 // There are no 8-bit 3-address imul/mul instructions
1507 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1508 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1510 if (!Subtarget->is64Bit()) {
1511 // These libcalls are not available in 32-bit.
1512 setLibcallName(RTLIB::SHL_I128, nullptr);
1513 setLibcallName(RTLIB::SRL_I128, nullptr);
1514 setLibcallName(RTLIB::SRA_I128, nullptr);
1517 // Combine sin / cos into one node or libcall if possible.
1518 if (Subtarget->hasSinCos()) {
1519 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1520 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1521 if (Subtarget->isTargetDarwin()) {
1522 // For MacOSX, we don't want to the normal expansion of a libcall to
1523 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1525 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1526 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1530 if (Subtarget->isTargetWin64()) {
1531 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1532 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1533 setOperationAction(ISD::SREM, MVT::i128, Custom);
1534 setOperationAction(ISD::UREM, MVT::i128, Custom);
1535 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1536 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1539 // We have target-specific dag combine patterns for the following nodes:
1540 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1541 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1542 setTargetDAGCombine(ISD::VSELECT);
1543 setTargetDAGCombine(ISD::SELECT);
1544 setTargetDAGCombine(ISD::SHL);
1545 setTargetDAGCombine(ISD::SRA);
1546 setTargetDAGCombine(ISD::SRL);
1547 setTargetDAGCombine(ISD::OR);
1548 setTargetDAGCombine(ISD::AND);
1549 setTargetDAGCombine(ISD::ADD);
1550 setTargetDAGCombine(ISD::FADD);
1551 setTargetDAGCombine(ISD::FSUB);
1552 setTargetDAGCombine(ISD::FMA);
1553 setTargetDAGCombine(ISD::SUB);
1554 setTargetDAGCombine(ISD::LOAD);
1555 setTargetDAGCombine(ISD::STORE);
1556 setTargetDAGCombine(ISD::ZERO_EXTEND);
1557 setTargetDAGCombine(ISD::ANY_EXTEND);
1558 setTargetDAGCombine(ISD::SIGN_EXTEND);
1559 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1560 setTargetDAGCombine(ISD::TRUNCATE);
1561 setTargetDAGCombine(ISD::SINT_TO_FP);
1562 setTargetDAGCombine(ISD::SETCC);
1563 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1564 if (Subtarget->is64Bit())
1565 setTargetDAGCombine(ISD::MUL);
1566 setTargetDAGCombine(ISD::XOR);
1568 computeRegisterProperties();
1570 // On Darwin, -Os means optimize for size without hurting performance,
1571 // do not reduce the limit.
1572 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1573 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1574 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1575 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1576 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1577 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1578 setPrefLoopAlignment(4); // 2^4 bytes.
1580 // Predictable cmov don't hurt on atom because it's in-order.
1581 PredictableSelectIsExpensive = !Subtarget->isAtom();
1583 setPrefFunctionAlignment(4); // 2^4 bytes.
1586 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1588 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1590 if (Subtarget->hasAVX512())
1591 switch(VT.getVectorNumElements()) {
1592 case 8: return MVT::v8i1;
1593 case 16: return MVT::v16i1;
1596 return VT.changeVectorElementTypeToInteger();
1599 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1600 /// the desired ByVal argument alignment.
1601 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1604 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1605 if (VTy->getBitWidth() == 128)
1607 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1608 unsigned EltAlign = 0;
1609 getMaxByValAlign(ATy->getElementType(), EltAlign);
1610 if (EltAlign > MaxAlign)
1611 MaxAlign = EltAlign;
1612 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1613 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1614 unsigned EltAlign = 0;
1615 getMaxByValAlign(STy->getElementType(i), EltAlign);
1616 if (EltAlign > MaxAlign)
1617 MaxAlign = EltAlign;
1624 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1625 /// function arguments in the caller parameter area. For X86, aggregates
1626 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1627 /// are at 4-byte boundaries.
1628 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1629 if (Subtarget->is64Bit()) {
1630 // Max of 8 and alignment of type.
1631 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1638 if (Subtarget->hasSSE1())
1639 getMaxByValAlign(Ty, Align);
1643 /// getOptimalMemOpType - Returns the target specific optimal type for load
1644 /// and store operations as a result of memset, memcpy, and memmove
1645 /// lowering. If DstAlign is zero that means it's safe to destination
1646 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1647 /// means there isn't a need to check it against alignment requirement,
1648 /// probably because the source does not need to be loaded. If 'IsMemset' is
1649 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1650 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1651 /// source is constant so it does not need to be loaded.
1652 /// It returns EVT::Other if the type should be determined using generic
1653 /// target-independent logic.
1655 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1656 unsigned DstAlign, unsigned SrcAlign,
1657 bool IsMemset, bool ZeroMemset,
1659 MachineFunction &MF) const {
1660 const Function *F = MF.getFunction();
1661 if ((!IsMemset || ZeroMemset) &&
1662 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1663 Attribute::NoImplicitFloat)) {
1665 (Subtarget->isUnalignedMemAccessFast() ||
1666 ((DstAlign == 0 || DstAlign >= 16) &&
1667 (SrcAlign == 0 || SrcAlign >= 16)))) {
1669 if (Subtarget->hasInt256())
1671 if (Subtarget->hasFp256())
1674 if (Subtarget->hasSSE2())
1676 if (Subtarget->hasSSE1())
1678 } else if (!MemcpyStrSrc && Size >= 8 &&
1679 !Subtarget->is64Bit() &&
1680 Subtarget->hasSSE2()) {
1681 // Do not use f64 to lower memcpy if source is string constant. It's
1682 // better to use i32 to avoid the loads.
1686 if (Subtarget->is64Bit() && Size >= 8)
1691 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1693 return X86ScalarSSEf32;
1694 else if (VT == MVT::f64)
1695 return X86ScalarSSEf64;
1700 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1704 *Fast = Subtarget->isUnalignedMemAccessFast();
1708 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1709 /// current function. The returned value is a member of the
1710 /// MachineJumpTableInfo::JTEntryKind enum.
1711 unsigned X86TargetLowering::getJumpTableEncoding() const {
1712 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1714 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1715 Subtarget->isPICStyleGOT())
1716 return MachineJumpTableInfo::EK_Custom32;
1718 // Otherwise, use the normal jump table encoding heuristics.
1719 return TargetLowering::getJumpTableEncoding();
1723 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1724 const MachineBasicBlock *MBB,
1725 unsigned uid,MCContext &Ctx) const{
1726 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1727 Subtarget->isPICStyleGOT());
1728 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1730 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1731 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1734 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1736 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1737 SelectionDAG &DAG) const {
1738 if (!Subtarget->is64Bit())
1739 // This doesn't have SDLoc associated with it, but is not really the
1740 // same as a Register.
1741 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1745 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1746 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1748 const MCExpr *X86TargetLowering::
1749 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1750 MCContext &Ctx) const {
1751 // X86-64 uses RIP relative addressing based on the jump table label.
1752 if (Subtarget->isPICStyleRIPRel())
1753 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1755 // Otherwise, the reference is relative to the PIC base.
1756 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1759 // FIXME: Why this routine is here? Move to RegInfo!
1760 std::pair<const TargetRegisterClass*, uint8_t>
1761 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1762 const TargetRegisterClass *RRC = nullptr;
1764 switch (VT.SimpleTy) {
1766 return TargetLowering::findRepresentativeClass(VT);
1767 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1768 RRC = Subtarget->is64Bit() ?
1769 (const TargetRegisterClass*)&X86::GR64RegClass :
1770 (const TargetRegisterClass*)&X86::GR32RegClass;
1773 RRC = &X86::VR64RegClass;
1775 case MVT::f32: case MVT::f64:
1776 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1777 case MVT::v4f32: case MVT::v2f64:
1778 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1780 RRC = &X86::VR128RegClass;
1783 return std::make_pair(RRC, Cost);
1786 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1787 unsigned &Offset) const {
1788 if (!Subtarget->isTargetLinux())
1791 if (Subtarget->is64Bit()) {
1792 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1794 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1806 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1807 unsigned DestAS) const {
1808 assert(SrcAS != DestAS && "Expected different address spaces!");
1810 return SrcAS < 256 && DestAS < 256;
1813 //===----------------------------------------------------------------------===//
1814 // Return Value Calling Convention Implementation
1815 //===----------------------------------------------------------------------===//
1817 #include "X86GenCallingConv.inc"
1820 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1821 MachineFunction &MF, bool isVarArg,
1822 const SmallVectorImpl<ISD::OutputArg> &Outs,
1823 LLVMContext &Context) const {
1824 SmallVector<CCValAssign, 16> RVLocs;
1825 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1827 return CCInfo.CheckReturn(Outs, RetCC_X86);
1830 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1831 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1836 X86TargetLowering::LowerReturn(SDValue Chain,
1837 CallingConv::ID CallConv, bool isVarArg,
1838 const SmallVectorImpl<ISD::OutputArg> &Outs,
1839 const SmallVectorImpl<SDValue> &OutVals,
1840 SDLoc dl, SelectionDAG &DAG) const {
1841 MachineFunction &MF = DAG.getMachineFunction();
1842 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1844 SmallVector<CCValAssign, 16> RVLocs;
1845 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1846 RVLocs, *DAG.getContext());
1847 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1850 SmallVector<SDValue, 6> RetOps;
1851 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1852 // Operand #1 = Bytes To Pop
1853 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1856 // Copy the result values into the output registers.
1857 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1858 CCValAssign &VA = RVLocs[i];
1859 assert(VA.isRegLoc() && "Can only return in registers!");
1860 SDValue ValToCopy = OutVals[i];
1861 EVT ValVT = ValToCopy.getValueType();
1863 // Promote values to the appropriate types
1864 if (VA.getLocInfo() == CCValAssign::SExt)
1865 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1866 else if (VA.getLocInfo() == CCValAssign::ZExt)
1867 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1868 else if (VA.getLocInfo() == CCValAssign::AExt)
1869 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1870 else if (VA.getLocInfo() == CCValAssign::BCvt)
1871 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1873 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1874 "Unexpected FP-extend for return value.");
1876 // If this is x86-64, and we disabled SSE, we can't return FP values,
1877 // or SSE or MMX vectors.
1878 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1879 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1880 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1881 report_fatal_error("SSE register return with SSE disabled");
1883 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1884 // llvm-gcc has never done it right and no one has noticed, so this
1885 // should be OK for now.
1886 if (ValVT == MVT::f64 &&
1887 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1888 report_fatal_error("SSE2 register return with SSE2 disabled");
1890 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1891 // the RET instruction and handled by the FP Stackifier.
1892 if (VA.getLocReg() == X86::ST0 ||
1893 VA.getLocReg() == X86::ST1) {
1894 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1895 // change the value to the FP stack register class.
1896 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1897 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1898 RetOps.push_back(ValToCopy);
1899 // Don't emit a copytoreg.
1903 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1904 // which is returned in RAX / RDX.
1905 if (Subtarget->is64Bit()) {
1906 if (ValVT == MVT::x86mmx) {
1907 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1908 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1909 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1911 // If we don't have SSE2 available, convert to v4f32 so the generated
1912 // register is legal.
1913 if (!Subtarget->hasSSE2())
1914 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1919 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1920 Flag = Chain.getValue(1);
1921 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1924 // The x86-64 ABIs require that for returning structs by value we copy
1925 // the sret argument into %rax/%eax (depending on ABI) for the return.
1926 // Win32 requires us to put the sret argument to %eax as well.
1927 // We saved the argument into a virtual register in the entry block,
1928 // so now we copy the value out and into %rax/%eax.
1929 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1930 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1931 MachineFunction &MF = DAG.getMachineFunction();
1932 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1933 unsigned Reg = FuncInfo->getSRetReturnReg();
1935 "SRetReturnReg should have been set in LowerFormalArguments().");
1936 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1939 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1940 X86::RAX : X86::EAX;
1941 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1942 Flag = Chain.getValue(1);
1944 // RAX/EAX now acts like a return value.
1945 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1948 RetOps[0] = Chain; // Update chain.
1950 // Add the flag if we have it.
1952 RetOps.push_back(Flag);
1954 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1957 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1958 if (N->getNumValues() != 1)
1960 if (!N->hasNUsesOfValue(1, 0))
1963 SDValue TCChain = Chain;
1964 SDNode *Copy = *N->use_begin();
1965 if (Copy->getOpcode() == ISD::CopyToReg) {
1966 // If the copy has a glue operand, we conservatively assume it isn't safe to
1967 // perform a tail call.
1968 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1970 TCChain = Copy->getOperand(0);
1971 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1974 bool HasRet = false;
1975 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1977 if (UI->getOpcode() != X86ISD::RET_FLAG)
1990 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1991 ISD::NodeType ExtendKind) const {
1993 // TODO: Is this also valid on 32-bit?
1994 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1995 ReturnMVT = MVT::i8;
1997 ReturnMVT = MVT::i32;
1999 MVT MinVT = getRegisterType(ReturnMVT);
2000 return VT.bitsLT(MinVT) ? MinVT : VT;
2003 /// LowerCallResult - Lower the result values of a call into the
2004 /// appropriate copies out of appropriate physical registers.
2007 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2008 CallingConv::ID CallConv, bool isVarArg,
2009 const SmallVectorImpl<ISD::InputArg> &Ins,
2010 SDLoc dl, SelectionDAG &DAG,
2011 SmallVectorImpl<SDValue> &InVals) const {
2013 // Assign locations to each value returned by this call.
2014 SmallVector<CCValAssign, 16> RVLocs;
2015 bool Is64Bit = Subtarget->is64Bit();
2016 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2017 getTargetMachine(), RVLocs, *DAG.getContext());
2018 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2020 // Copy all of the result registers out of their specified physreg.
2021 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2022 CCValAssign &VA = RVLocs[i];
2023 EVT CopyVT = VA.getValVT();
2025 // If this is x86-64, and we disabled SSE, we can't return FP values
2026 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2027 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2028 report_fatal_error("SSE register return with SSE disabled");
2033 // If this is a call to a function that returns an fp value on the floating
2034 // point stack, we must guarantee the value is popped from the stack, so
2035 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2036 // if the return value is not used. We use the FpPOP_RETVAL instruction
2038 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2039 // If we prefer to use the value in xmm registers, copy it out as f80 and
2040 // use a truncate to move it from fp stack reg to xmm reg.
2041 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2042 SDValue Ops[] = { Chain, InFlag };
2043 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2044 MVT::Other, MVT::Glue, Ops), 1);
2045 Val = Chain.getValue(0);
2047 // Round the f80 to the right size, which also moves it to the appropriate
2049 if (CopyVT != VA.getValVT())
2050 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2051 // This truncation won't change the value.
2052 DAG.getIntPtrConstant(1));
2054 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2055 CopyVT, InFlag).getValue(1);
2056 Val = Chain.getValue(0);
2058 InFlag = Chain.getValue(2);
2059 InVals.push_back(Val);
2065 //===----------------------------------------------------------------------===//
2066 // C & StdCall & Fast Calling Convention implementation
2067 //===----------------------------------------------------------------------===//
2068 // StdCall calling convention seems to be standard for many Windows' API
2069 // routines and around. It differs from C calling convention just a little:
2070 // callee should clean up the stack, not caller. Symbols should be also
2071 // decorated in some fancy way :) It doesn't support any vector arguments.
2072 // For info on fast calling convention see Fast Calling Convention (tail call)
2073 // implementation LowerX86_32FastCCCallTo.
2075 /// CallIsStructReturn - Determines whether a call uses struct return
2077 enum StructReturnType {
2082 static StructReturnType
2083 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2085 return NotStructReturn;
2087 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2088 if (!Flags.isSRet())
2089 return NotStructReturn;
2090 if (Flags.isInReg())
2091 return RegStructReturn;
2092 return StackStructReturn;
2095 /// ArgsAreStructReturn - Determines whether a function uses struct
2096 /// return semantics.
2097 static StructReturnType
2098 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2100 return NotStructReturn;
2102 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2103 if (!Flags.isSRet())
2104 return NotStructReturn;
2105 if (Flags.isInReg())
2106 return RegStructReturn;
2107 return StackStructReturn;
2110 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2111 /// by "Src" to address "Dst" with size and alignment information specified by
2112 /// the specific parameter attribute. The copy will be passed as a byval
2113 /// function parameter.
2115 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2116 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2118 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2120 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2121 /*isVolatile*/false, /*AlwaysInline=*/true,
2122 MachinePointerInfo(), MachinePointerInfo());
2125 /// IsTailCallConvention - Return true if the calling convention is one that
2126 /// supports tail call optimization.
2127 static bool IsTailCallConvention(CallingConv::ID CC) {
2128 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2129 CC == CallingConv::HiPE);
2132 /// \brief Return true if the calling convention is a C calling convention.
2133 static bool IsCCallConvention(CallingConv::ID CC) {
2134 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2135 CC == CallingConv::X86_64_SysV);
2138 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2139 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2143 CallingConv::ID CalleeCC = CS.getCallingConv();
2144 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2150 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2151 /// a tailcall target by changing its ABI.
2152 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2153 bool GuaranteedTailCallOpt) {
2154 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2158 X86TargetLowering::LowerMemArgument(SDValue Chain,
2159 CallingConv::ID CallConv,
2160 const SmallVectorImpl<ISD::InputArg> &Ins,
2161 SDLoc dl, SelectionDAG &DAG,
2162 const CCValAssign &VA,
2163 MachineFrameInfo *MFI,
2165 // Create the nodes corresponding to a load from this parameter slot.
2166 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2167 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2168 getTargetMachine().Options.GuaranteedTailCallOpt);
2169 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2172 // If value is passed by pointer we have address passed instead of the value
2174 if (VA.getLocInfo() == CCValAssign::Indirect)
2175 ValVT = VA.getLocVT();
2177 ValVT = VA.getValVT();
2179 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2180 // changed with more analysis.
2181 // In case of tail call optimization mark all arguments mutable. Since they
2182 // could be overwritten by lowering of arguments in case of a tail call.
2183 if (Flags.isByVal()) {
2184 unsigned Bytes = Flags.getByValSize();
2185 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2186 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2187 return DAG.getFrameIndex(FI, getPointerTy());
2189 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2190 VA.getLocMemOffset(), isImmutable);
2191 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2192 return DAG.getLoad(ValVT, dl, Chain, FIN,
2193 MachinePointerInfo::getFixedStack(FI),
2194 false, false, false, 0);
2199 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2200 CallingConv::ID CallConv,
2202 const SmallVectorImpl<ISD::InputArg> &Ins,
2205 SmallVectorImpl<SDValue> &InVals)
2207 MachineFunction &MF = DAG.getMachineFunction();
2208 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2210 const Function* Fn = MF.getFunction();
2211 if (Fn->hasExternalLinkage() &&
2212 Subtarget->isTargetCygMing() &&
2213 Fn->getName() == "main")
2214 FuncInfo->setForceFramePointer(true);
2216 MachineFrameInfo *MFI = MF.getFrameInfo();
2217 bool Is64Bit = Subtarget->is64Bit();
2218 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2220 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2221 "Var args not supported with calling convention fastcc, ghc or hipe");
2223 // Assign locations to all of the incoming arguments.
2224 SmallVector<CCValAssign, 16> ArgLocs;
2225 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2226 ArgLocs, *DAG.getContext());
2228 // Allocate shadow area for Win64
2230 CCInfo.AllocateStack(32, 8);
2232 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2234 unsigned LastVal = ~0U;
2236 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2237 CCValAssign &VA = ArgLocs[i];
2238 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2240 assert(VA.getValNo() != LastVal &&
2241 "Don't support value assigned to multiple locs yet");
2243 LastVal = VA.getValNo();
2245 if (VA.isRegLoc()) {
2246 EVT RegVT = VA.getLocVT();
2247 const TargetRegisterClass *RC;
2248 if (RegVT == MVT::i32)
2249 RC = &X86::GR32RegClass;
2250 else if (Is64Bit && RegVT == MVT::i64)
2251 RC = &X86::GR64RegClass;
2252 else if (RegVT == MVT::f32)
2253 RC = &X86::FR32RegClass;
2254 else if (RegVT == MVT::f64)
2255 RC = &X86::FR64RegClass;
2256 else if (RegVT.is512BitVector())
2257 RC = &X86::VR512RegClass;
2258 else if (RegVT.is256BitVector())
2259 RC = &X86::VR256RegClass;
2260 else if (RegVT.is128BitVector())
2261 RC = &X86::VR128RegClass;
2262 else if (RegVT == MVT::x86mmx)
2263 RC = &X86::VR64RegClass;
2264 else if (RegVT == MVT::i1)
2265 RC = &X86::VK1RegClass;
2266 else if (RegVT == MVT::v8i1)
2267 RC = &X86::VK8RegClass;
2268 else if (RegVT == MVT::v16i1)
2269 RC = &X86::VK16RegClass;
2271 llvm_unreachable("Unknown argument type!");
2273 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2274 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2276 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2277 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2279 if (VA.getLocInfo() == CCValAssign::SExt)
2280 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2281 DAG.getValueType(VA.getValVT()));
2282 else if (VA.getLocInfo() == CCValAssign::ZExt)
2283 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2284 DAG.getValueType(VA.getValVT()));
2285 else if (VA.getLocInfo() == CCValAssign::BCvt)
2286 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2288 if (VA.isExtInLoc()) {
2289 // Handle MMX values passed in XMM regs.
2290 if (RegVT.isVector())
2291 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2293 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2296 assert(VA.isMemLoc());
2297 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2300 // If value is passed via pointer - do a load.
2301 if (VA.getLocInfo() == CCValAssign::Indirect)
2302 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2303 MachinePointerInfo(), false, false, false, 0);
2305 InVals.push_back(ArgValue);
2308 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2309 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310 // The x86-64 ABIs require that for returning structs by value we copy
2311 // the sret argument into %rax/%eax (depending on ABI) for the return.
2312 // Win32 requires us to put the sret argument to %eax as well.
2313 // Save the argument into a virtual register so that we can access it
2314 // from the return points.
2315 if (Ins[i].Flags.isSRet()) {
2316 unsigned Reg = FuncInfo->getSRetReturnReg();
2318 MVT PtrTy = getPointerTy();
2319 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2320 FuncInfo->setSRetReturnReg(Reg);
2322 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2323 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2329 unsigned StackSize = CCInfo.getNextStackOffset();
2330 // Align stack specially for tail calls.
2331 if (FuncIsMadeTailCallSafe(CallConv,
2332 MF.getTarget().Options.GuaranteedTailCallOpt))
2333 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2335 // If the function takes variable number of arguments, make a frame index for
2336 // the start of the first vararg value... for expansion of llvm.va_start.
2338 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2339 CallConv != CallingConv::X86_ThisCall)) {
2340 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2343 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2345 // FIXME: We should really autogenerate these arrays
2346 static const MCPhysReg GPR64ArgRegsWin64[] = {
2347 X86::RCX, X86::RDX, X86::R8, X86::R9
2349 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2350 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2352 static const MCPhysReg XMMArgRegs64Bit[] = {
2353 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2354 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2356 const MCPhysReg *GPR64ArgRegs;
2357 unsigned NumXMMRegs = 0;
2360 // The XMM registers which might contain var arg parameters are shadowed
2361 // in their paired GPR. So we only need to save the GPR to their home
2363 TotalNumIntRegs = 4;
2364 GPR64ArgRegs = GPR64ArgRegsWin64;
2366 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2367 GPR64ArgRegs = GPR64ArgRegs64Bit;
2369 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2372 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2375 bool NoImplicitFloatOps = Fn->getAttributes().
2376 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2377 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2378 "SSE register cannot be used when SSE is disabled!");
2379 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2380 NoImplicitFloatOps) &&
2381 "SSE register cannot be used when SSE is disabled!");
2382 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2383 !Subtarget->hasSSE1())
2384 // Kernel mode asks for SSE to be disabled, so don't push them
2386 TotalNumXMMRegs = 0;
2389 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2390 // Get to the caller-allocated home save location. Add 8 to account
2391 // for the return address.
2392 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2393 FuncInfo->setRegSaveFrameIndex(
2394 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2395 // Fixup to set vararg frame on shadow area (4 x i64).
2397 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2399 // For X86-64, if there are vararg parameters that are passed via
2400 // registers, then we must store them to their spots on the stack so
2401 // they may be loaded by deferencing the result of va_next.
2402 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2403 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2404 FuncInfo->setRegSaveFrameIndex(
2405 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2409 // Store the integer parameter registers.
2410 SmallVector<SDValue, 8> MemOps;
2411 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2413 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2414 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2415 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2416 DAG.getIntPtrConstant(Offset));
2417 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2418 &X86::GR64RegClass);
2419 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2421 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2422 MachinePointerInfo::getFixedStack(
2423 FuncInfo->getRegSaveFrameIndex(), Offset),
2425 MemOps.push_back(Store);
2429 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2430 // Now store the XMM (fp + vector) parameter registers.
2431 SmallVector<SDValue, 11> SaveXMMOps;
2432 SaveXMMOps.push_back(Chain);
2434 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2435 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2436 SaveXMMOps.push_back(ALVal);
2438 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2439 FuncInfo->getRegSaveFrameIndex()));
2440 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2441 FuncInfo->getVarArgsFPOffset()));
2443 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2444 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2445 &X86::VR128RegClass);
2446 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2447 SaveXMMOps.push_back(Val);
2449 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2450 MVT::Other, SaveXMMOps));
2453 if (!MemOps.empty())
2454 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2458 // Some CCs need callee pop.
2459 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2460 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2461 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2463 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2464 // If this is an sret function, the return should pop the hidden pointer.
2465 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2466 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2467 argsAreStructReturn(Ins) == StackStructReturn)
2468 FuncInfo->setBytesToPopOnReturn(4);
2472 // RegSaveFrameIndex is X86-64 only.
2473 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2474 if (CallConv == CallingConv::X86_FastCall ||
2475 CallConv == CallingConv::X86_ThisCall)
2476 // fastcc functions can't have varargs.
2477 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2480 FuncInfo->setArgumentStackSize(StackSize);
2486 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2487 SDValue StackPtr, SDValue Arg,
2488 SDLoc dl, SelectionDAG &DAG,
2489 const CCValAssign &VA,
2490 ISD::ArgFlagsTy Flags) const {
2491 unsigned LocMemOffset = VA.getLocMemOffset();
2492 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2493 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2494 if (Flags.isByVal())
2495 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2497 return DAG.getStore(Chain, dl, Arg, PtrOff,
2498 MachinePointerInfo::getStack(LocMemOffset),
2502 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2503 /// optimization is performed and it is required.
2505 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2506 SDValue &OutRetAddr, SDValue Chain,
2507 bool IsTailCall, bool Is64Bit,
2508 int FPDiff, SDLoc dl) const {
2509 // Adjust the Return address stack slot.
2510 EVT VT = getPointerTy();
2511 OutRetAddr = getReturnAddressFrameIndex(DAG);
2513 // Load the "old" Return address.
2514 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2515 false, false, false, 0);
2516 return SDValue(OutRetAddr.getNode(), 1);
2519 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2520 /// optimization is performed and it is required (FPDiff!=0).
2521 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2522 SDValue Chain, SDValue RetAddrFrIdx,
2523 EVT PtrVT, unsigned SlotSize,
2524 int FPDiff, SDLoc dl) {
2525 // Store the return address to the appropriate stack slot.
2526 if (!FPDiff) return Chain;
2527 // Calculate the new stack slot for the return address.
2528 int NewReturnAddrFI =
2529 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2531 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2532 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2533 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2539 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2540 SmallVectorImpl<SDValue> &InVals) const {
2541 SelectionDAG &DAG = CLI.DAG;
2543 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2544 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2545 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2546 SDValue Chain = CLI.Chain;
2547 SDValue Callee = CLI.Callee;
2548 CallingConv::ID CallConv = CLI.CallConv;
2549 bool &isTailCall = CLI.IsTailCall;
2550 bool isVarArg = CLI.IsVarArg;
2552 MachineFunction &MF = DAG.getMachineFunction();
2553 bool Is64Bit = Subtarget->is64Bit();
2554 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2555 StructReturnType SR = callIsStructReturn(Outs);
2556 bool IsSibcall = false;
2558 if (MF.getTarget().Options.DisableTailCalls)
2561 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2563 // Force this to be a tail call. The verifier rules are enough to ensure
2564 // that we can lower this successfully without moving the return address
2567 } else if (isTailCall) {
2568 // Check if it's really possible to do a tail call.
2569 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2570 isVarArg, SR != NotStructReturn,
2571 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2572 Outs, OutVals, Ins, DAG);
2574 // Sibcalls are automatically detected tailcalls which do not require
2576 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2583 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2584 "Var args not supported with calling convention fastcc, ghc or hipe");
2586 // Analyze operands of the call, assigning locations to each operand.
2587 SmallVector<CCValAssign, 16> ArgLocs;
2588 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2589 ArgLocs, *DAG.getContext());
2591 // Allocate shadow area for Win64
2593 CCInfo.AllocateStack(32, 8);
2595 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2597 // Get a count of how many bytes are to be pushed on the stack.
2598 unsigned NumBytes = CCInfo.getNextStackOffset();
2600 // This is a sibcall. The memory operands are available in caller's
2601 // own caller's stack.
2603 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2604 IsTailCallConvention(CallConv))
2605 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2608 if (isTailCall && !IsSibcall && !IsMustTail) {
2609 // Lower arguments at fp - stackoffset + fpdiff.
2610 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2611 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2613 FPDiff = NumBytesCallerPushed - NumBytes;
2615 // Set the delta of movement of the returnaddr stackslot.
2616 // But only set if delta is greater than previous delta.
2617 if (FPDiff < X86Info->getTCReturnAddrDelta())
2618 X86Info->setTCReturnAddrDelta(FPDiff);
2621 unsigned NumBytesToPush = NumBytes;
2622 unsigned NumBytesToPop = NumBytes;
2624 // If we have an inalloca argument, all stack space has already been allocated
2625 // for us and be right at the top of the stack. We don't support multiple
2626 // arguments passed in memory when using inalloca.
2627 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2629 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2630 "an inalloca argument must be the only memory argument");
2634 Chain = DAG.getCALLSEQ_START(
2635 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2637 SDValue RetAddrFrIdx;
2638 // Load return address for tail calls.
2639 if (isTailCall && FPDiff)
2640 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2641 Is64Bit, FPDiff, dl);
2643 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2644 SmallVector<SDValue, 8> MemOpChains;
2647 // Walk the register/memloc assignments, inserting copies/loads. In the case
2648 // of tail call optimization arguments are handle later.
2649 const X86RegisterInfo *RegInfo =
2650 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2651 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2652 // Skip inalloca arguments, they have already been written.
2653 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2654 if (Flags.isInAlloca())
2657 CCValAssign &VA = ArgLocs[i];
2658 EVT RegVT = VA.getLocVT();
2659 SDValue Arg = OutVals[i];
2660 bool isByVal = Flags.isByVal();
2662 // Promote the value if needed.
2663 switch (VA.getLocInfo()) {
2664 default: llvm_unreachable("Unknown loc info!");
2665 case CCValAssign::Full: break;
2666 case CCValAssign::SExt:
2667 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2669 case CCValAssign::ZExt:
2670 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2672 case CCValAssign::AExt:
2673 if (RegVT.is128BitVector()) {
2674 // Special case: passing MMX values in XMM registers.
2675 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2676 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2677 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2679 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2681 case CCValAssign::BCvt:
2682 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2684 case CCValAssign::Indirect: {
2685 // Store the argument.
2686 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2687 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2688 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2689 MachinePointerInfo::getFixedStack(FI),
2696 if (VA.isRegLoc()) {
2697 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2698 if (isVarArg && IsWin64) {
2699 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2700 // shadow reg if callee is a varargs function.
2701 unsigned ShadowReg = 0;
2702 switch (VA.getLocReg()) {
2703 case X86::XMM0: ShadowReg = X86::RCX; break;
2704 case X86::XMM1: ShadowReg = X86::RDX; break;
2705 case X86::XMM2: ShadowReg = X86::R8; break;
2706 case X86::XMM3: ShadowReg = X86::R9; break;
2709 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2711 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2712 assert(VA.isMemLoc());
2713 if (!StackPtr.getNode())
2714 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2716 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2717 dl, DAG, VA, Flags));
2721 if (!MemOpChains.empty())
2722 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2724 if (Subtarget->isPICStyleGOT()) {
2725 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2728 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2729 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2731 // If we are tail calling and generating PIC/GOT style code load the
2732 // address of the callee into ECX. The value in ecx is used as target of
2733 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2734 // for tail calls on PIC/GOT architectures. Normally we would just put the
2735 // address of GOT into ebx and then call target@PLT. But for tail calls
2736 // ebx would be restored (since ebx is callee saved) before jumping to the
2739 // Note: The actual moving to ECX is done further down.
2740 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2741 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2742 !G->getGlobal()->hasProtectedVisibility())
2743 Callee = LowerGlobalAddress(Callee, DAG);
2744 else if (isa<ExternalSymbolSDNode>(Callee))
2745 Callee = LowerExternalSymbol(Callee, DAG);
2749 if (Is64Bit && isVarArg && !IsWin64) {
2750 // From AMD64 ABI document:
2751 // For calls that may call functions that use varargs or stdargs
2752 // (prototype-less calls or calls to functions containing ellipsis (...) in
2753 // the declaration) %al is used as hidden argument to specify the number
2754 // of SSE registers used. The contents of %al do not need to match exactly
2755 // the number of registers, but must be an ubound on the number of SSE
2756 // registers used and is in the range 0 - 8 inclusive.
2758 // Count the number of XMM registers allocated.
2759 static const MCPhysReg XMMArgRegs[] = {
2760 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2761 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2763 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2764 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2765 && "SSE registers cannot be used when SSE is disabled");
2767 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2768 DAG.getConstant(NumXMMRegs, MVT::i8)));
2771 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2772 // don't need this because the eligibility check rejects calls that require
2773 // shuffling arguments passed in memory.
2774 if (!IsSibcall && isTailCall) {
2775 // Force all the incoming stack arguments to be loaded from the stack
2776 // before any new outgoing arguments are stored to the stack, because the
2777 // outgoing stack slots may alias the incoming argument stack slots, and
2778 // the alias isn't otherwise explicit. This is slightly more conservative
2779 // than necessary, because it means that each store effectively depends
2780 // on every argument instead of just those arguments it would clobber.
2781 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2783 SmallVector<SDValue, 8> MemOpChains2;
2786 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2787 CCValAssign &VA = ArgLocs[i];
2790 assert(VA.isMemLoc());
2791 SDValue Arg = OutVals[i];
2792 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2793 // Skip inalloca arguments. They don't require any work.
2794 if (Flags.isInAlloca())
2796 // Create frame index.
2797 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2798 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2799 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2800 FIN = DAG.getFrameIndex(FI, getPointerTy());
2802 if (Flags.isByVal()) {
2803 // Copy relative to framepointer.
2804 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2805 if (!StackPtr.getNode())
2806 StackPtr = DAG.getCopyFromReg(Chain, dl,
2807 RegInfo->getStackRegister(),
2809 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2811 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2815 // Store relative to framepointer.
2816 MemOpChains2.push_back(
2817 DAG.getStore(ArgChain, dl, Arg, FIN,
2818 MachinePointerInfo::getFixedStack(FI),
2823 if (!MemOpChains2.empty())
2824 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2826 // Store the return address to the appropriate stack slot.
2827 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2828 getPointerTy(), RegInfo->getSlotSize(),
2832 // Build a sequence of copy-to-reg nodes chained together with token chain
2833 // and flag operands which copy the outgoing args into registers.
2835 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2836 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2837 RegsToPass[i].second, InFlag);
2838 InFlag = Chain.getValue(1);
2841 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2842 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2843 // In the 64-bit large code model, we have to make all calls
2844 // through a register, since the call instruction's 32-bit
2845 // pc-relative offset may not be large enough to hold the whole
2847 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2848 // If the callee is a GlobalAddress node (quite common, every direct call
2849 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2852 // We should use extra load for direct calls to dllimported functions in
2854 const GlobalValue *GV = G->getGlobal();
2855 if (!GV->hasDLLImportStorageClass()) {
2856 unsigned char OpFlags = 0;
2857 bool ExtraLoad = false;
2858 unsigned WrapperKind = ISD::DELETED_NODE;
2860 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2861 // external symbols most go through the PLT in PIC mode. If the symbol
2862 // has hidden or protected visibility, or if it is static or local, then
2863 // we don't need to use the PLT - we can directly call it.
2864 if (Subtarget->isTargetELF() &&
2865 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2866 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2867 OpFlags = X86II::MO_PLT;
2868 } else if (Subtarget->isPICStyleStubAny() &&
2869 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2870 (!Subtarget->getTargetTriple().isMacOSX() ||
2871 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2872 // PC-relative references to external symbols should go through $stub,
2873 // unless we're building with the leopard linker or later, which
2874 // automatically synthesizes these stubs.
2875 OpFlags = X86II::MO_DARWIN_STUB;
2876 } else if (Subtarget->isPICStyleRIPRel() &&
2877 isa<Function>(GV) &&
2878 cast<Function>(GV)->getAttributes().
2879 hasAttribute(AttributeSet::FunctionIndex,
2880 Attribute::NonLazyBind)) {
2881 // If the function is marked as non-lazy, generate an indirect call
2882 // which loads from the GOT directly. This avoids runtime overhead
2883 // at the cost of eager binding (and one extra byte of encoding).
2884 OpFlags = X86II::MO_GOTPCREL;
2885 WrapperKind = X86ISD::WrapperRIP;
2889 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2890 G->getOffset(), OpFlags);
2892 // Add a wrapper if needed.
2893 if (WrapperKind != ISD::DELETED_NODE)
2894 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2895 // Add extra indirection if needed.
2897 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2898 MachinePointerInfo::getGOT(),
2899 false, false, false, 0);
2901 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2902 unsigned char OpFlags = 0;
2904 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2905 // external symbols should go through the PLT.
2906 if (Subtarget->isTargetELF() &&
2907 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2908 OpFlags = X86II::MO_PLT;
2909 } else if (Subtarget->isPICStyleStubAny() &&
2910 (!Subtarget->getTargetTriple().isMacOSX() ||
2911 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2912 // PC-relative references to external symbols should go through $stub,
2913 // unless we're building with the leopard linker or later, which
2914 // automatically synthesizes these stubs.
2915 OpFlags = X86II::MO_DARWIN_STUB;
2918 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2922 // Returns a chain & a flag for retval copy to use.
2923 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2924 SmallVector<SDValue, 8> Ops;
2926 if (!IsSibcall && isTailCall) {
2927 Chain = DAG.getCALLSEQ_END(Chain,
2928 DAG.getIntPtrConstant(NumBytesToPop, true),
2929 DAG.getIntPtrConstant(0, true), InFlag, dl);
2930 InFlag = Chain.getValue(1);
2933 Ops.push_back(Chain);
2934 Ops.push_back(Callee);
2937 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2939 // Add argument registers to the end of the list so that they are known live
2941 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2942 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2943 RegsToPass[i].second.getValueType()));
2945 // Add a register mask operand representing the call-preserved registers.
2946 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2947 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2948 assert(Mask && "Missing call preserved mask for calling convention");
2949 Ops.push_back(DAG.getRegisterMask(Mask));
2951 if (InFlag.getNode())
2952 Ops.push_back(InFlag);
2956 //// If this is the first return lowered for this function, add the regs
2957 //// to the liveout set for the function.
2958 // This isn't right, although it's probably harmless on x86; liveouts
2959 // should be computed from returns not tail calls. Consider a void
2960 // function making a tail call to a function returning int.
2961 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2964 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2965 InFlag = Chain.getValue(1);
2967 // Create the CALLSEQ_END node.
2968 unsigned NumBytesForCalleeToPop;
2969 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2970 getTargetMachine().Options.GuaranteedTailCallOpt))
2971 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2972 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2973 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2974 SR == StackStructReturn)
2975 // If this is a call to a struct-return function, the callee
2976 // pops the hidden struct pointer, so we have to push it back.
2977 // This is common for Darwin/X86, Linux & Mingw32 targets.
2978 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2979 NumBytesForCalleeToPop = 4;
2981 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2983 // Returns a flag for retval copy to use.
2985 Chain = DAG.getCALLSEQ_END(Chain,
2986 DAG.getIntPtrConstant(NumBytesToPop, true),
2987 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2990 InFlag = Chain.getValue(1);
2993 // Handle result values, copying them out of physregs into vregs that we
2995 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2996 Ins, dl, DAG, InVals);
2999 //===----------------------------------------------------------------------===//
3000 // Fast Calling Convention (tail call) implementation
3001 //===----------------------------------------------------------------------===//
3003 // Like std call, callee cleans arguments, convention except that ECX is
3004 // reserved for storing the tail called function address. Only 2 registers are
3005 // free for argument passing (inreg). Tail call optimization is performed
3007 // * tailcallopt is enabled
3008 // * caller/callee are fastcc
3009 // On X86_64 architecture with GOT-style position independent code only local
3010 // (within module) calls are supported at the moment.
3011 // To keep the stack aligned according to platform abi the function
3012 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3013 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3014 // If a tail called function callee has more arguments than the caller the
3015 // caller needs to make sure that there is room to move the RETADDR to. This is
3016 // achieved by reserving an area the size of the argument delta right after the
3017 // original REtADDR, but before the saved framepointer or the spilled registers
3018 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3030 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3031 /// for a 16 byte align requirement.
3033 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3034 SelectionDAG& DAG) const {
3035 MachineFunction &MF = DAG.getMachineFunction();
3036 const TargetMachine &TM = MF.getTarget();
3037 const X86RegisterInfo *RegInfo =
3038 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3039 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3040 unsigned StackAlignment = TFI.getStackAlignment();
3041 uint64_t AlignMask = StackAlignment - 1;
3042 int64_t Offset = StackSize;
3043 unsigned SlotSize = RegInfo->getSlotSize();
3044 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3045 // Number smaller than 12 so just add the difference.
3046 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3048 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3049 Offset = ((~AlignMask) & Offset) + StackAlignment +
3050 (StackAlignment-SlotSize);
3055 /// MatchingStackOffset - Return true if the given stack call argument is
3056 /// already available in the same position (relatively) of the caller's
3057 /// incoming argument stack.
3059 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3060 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3061 const X86InstrInfo *TII) {
3062 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3064 if (Arg.getOpcode() == ISD::CopyFromReg) {
3065 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3066 if (!TargetRegisterInfo::isVirtualRegister(VR))
3068 MachineInstr *Def = MRI->getVRegDef(VR);
3071 if (!Flags.isByVal()) {
3072 if (!TII->isLoadFromStackSlot(Def, FI))
3075 unsigned Opcode = Def->getOpcode();
3076 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3077 Def->getOperand(1).isFI()) {
3078 FI = Def->getOperand(1).getIndex();
3079 Bytes = Flags.getByValSize();
3083 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3084 if (Flags.isByVal())
3085 // ByVal argument is passed in as a pointer but it's now being
3086 // dereferenced. e.g.
3087 // define @foo(%struct.X* %A) {
3088 // tail call @bar(%struct.X* byval %A)
3091 SDValue Ptr = Ld->getBasePtr();
3092 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3095 FI = FINode->getIndex();
3096 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3097 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3098 FI = FINode->getIndex();
3099 Bytes = Flags.getByValSize();
3103 assert(FI != INT_MAX);
3104 if (!MFI->isFixedObjectIndex(FI))
3106 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3109 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3110 /// for tail call optimization. Targets which want to do tail call
3111 /// optimization should implement this function.
3113 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3114 CallingConv::ID CalleeCC,
3116 bool isCalleeStructRet,
3117 bool isCallerStructRet,
3119 const SmallVectorImpl<ISD::OutputArg> &Outs,
3120 const SmallVectorImpl<SDValue> &OutVals,
3121 const SmallVectorImpl<ISD::InputArg> &Ins,
3122 SelectionDAG &DAG) const {
3123 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3126 // If -tailcallopt is specified, make fastcc functions tail-callable.
3127 const MachineFunction &MF = DAG.getMachineFunction();
3128 const Function *CallerF = MF.getFunction();
3130 // If the function return type is x86_fp80 and the callee return type is not,
3131 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3132 // perform a tailcall optimization here.
3133 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3136 CallingConv::ID CallerCC = CallerF->getCallingConv();
3137 bool CCMatch = CallerCC == CalleeCC;
3138 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3139 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3141 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3142 if (IsTailCallConvention(CalleeCC) && CCMatch)
3147 // Look for obvious safe cases to perform tail call optimization that do not
3148 // require ABI changes. This is what gcc calls sibcall.
3150 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3151 // emit a special epilogue.
3152 const X86RegisterInfo *RegInfo =
3153 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3154 if (RegInfo->needsStackRealignment(MF))
3157 // Also avoid sibcall optimization if either caller or callee uses struct
3158 // return semantics.
3159 if (isCalleeStructRet || isCallerStructRet)
3162 // An stdcall/thiscall caller is expected to clean up its arguments; the
3163 // callee isn't going to do that.
3164 // FIXME: this is more restrictive than needed. We could produce a tailcall
3165 // when the stack adjustment matches. For example, with a thiscall that takes
3166 // only one argument.
3167 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3168 CallerCC == CallingConv::X86_ThisCall))
3171 // Do not sibcall optimize vararg calls unless all arguments are passed via
3173 if (isVarArg && !Outs.empty()) {
3175 // Optimizing for varargs on Win64 is unlikely to be safe without
3176 // additional testing.
3177 if (IsCalleeWin64 || IsCallerWin64)
3180 SmallVector<CCValAssign, 16> ArgLocs;
3181 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3182 getTargetMachine(), ArgLocs, *DAG.getContext());
3184 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3185 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3186 if (!ArgLocs[i].isRegLoc())
3190 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3191 // stack. Therefore, if it's not used by the call it is not safe to optimize
3192 // this into a sibcall.
3193 bool Unused = false;
3194 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3201 SmallVector<CCValAssign, 16> RVLocs;
3202 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3203 getTargetMachine(), RVLocs, *DAG.getContext());
3204 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3205 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3206 CCValAssign &VA = RVLocs[i];
3207 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3212 // If the calling conventions do not match, then we'd better make sure the
3213 // results are returned in the same way as what the caller expects.
3215 SmallVector<CCValAssign, 16> RVLocs1;
3216 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3217 getTargetMachine(), RVLocs1, *DAG.getContext());
3218 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3220 SmallVector<CCValAssign, 16> RVLocs2;
3221 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3222 getTargetMachine(), RVLocs2, *DAG.getContext());
3223 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3225 if (RVLocs1.size() != RVLocs2.size())
3227 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3228 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3230 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3232 if (RVLocs1[i].isRegLoc()) {
3233 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3236 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3242 // If the callee takes no arguments then go on to check the results of the
3244 if (!Outs.empty()) {
3245 // Check if stack adjustment is needed. For now, do not do this if any
3246 // argument is passed on the stack.
3247 SmallVector<CCValAssign, 16> ArgLocs;
3248 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3249 getTargetMachine(), ArgLocs, *DAG.getContext());
3251 // Allocate shadow area for Win64
3253 CCInfo.AllocateStack(32, 8);
3255 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3256 if (CCInfo.getNextStackOffset()) {
3257 MachineFunction &MF = DAG.getMachineFunction();
3258 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3261 // Check if the arguments are already laid out in the right way as
3262 // the caller's fixed stack objects.
3263 MachineFrameInfo *MFI = MF.getFrameInfo();
3264 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3265 const X86InstrInfo *TII =
3266 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3267 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3268 CCValAssign &VA = ArgLocs[i];
3269 SDValue Arg = OutVals[i];
3270 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3271 if (VA.getLocInfo() == CCValAssign::Indirect)
3273 if (!VA.isRegLoc()) {
3274 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3281 // If the tailcall address may be in a register, then make sure it's
3282 // possible to register allocate for it. In 32-bit, the call address can
3283 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3284 // callee-saved registers are restored. These happen to be the same
3285 // registers used to pass 'inreg' arguments so watch out for those.
3286 if (!Subtarget->is64Bit() &&
3287 ((!isa<GlobalAddressSDNode>(Callee) &&
3288 !isa<ExternalSymbolSDNode>(Callee)) ||
3289 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3290 unsigned NumInRegs = 0;
3291 // In PIC we need an extra register to formulate the address computation
3293 unsigned MaxInRegs =
3294 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3296 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3297 CCValAssign &VA = ArgLocs[i];
3300 unsigned Reg = VA.getLocReg();
3303 case X86::EAX: case X86::EDX: case X86::ECX:
3304 if (++NumInRegs == MaxInRegs)
3316 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3317 const TargetLibraryInfo *libInfo) const {
3318 return X86::createFastISel(funcInfo, libInfo);
3321 //===----------------------------------------------------------------------===//
3322 // Other Lowering Hooks
3323 //===----------------------------------------------------------------------===//
3325 static bool MayFoldLoad(SDValue Op) {
3326 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3329 static bool MayFoldIntoStore(SDValue Op) {
3330 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3333 static bool isTargetShuffle(unsigned Opcode) {
3335 default: return false;
3336 case X86ISD::PSHUFD:
3337 case X86ISD::PSHUFHW:
3338 case X86ISD::PSHUFLW:
3340 case X86ISD::PALIGNR:
3341 case X86ISD::MOVLHPS:
3342 case X86ISD::MOVLHPD:
3343 case X86ISD::MOVHLPS:
3344 case X86ISD::MOVLPS:
3345 case X86ISD::MOVLPD:
3346 case X86ISD::MOVSHDUP:
3347 case X86ISD::MOVSLDUP:
3348 case X86ISD::MOVDDUP:
3351 case X86ISD::UNPCKL:
3352 case X86ISD::UNPCKH:
3353 case X86ISD::VPERMILP:
3354 case X86ISD::VPERM2X128:
3355 case X86ISD::VPERMI:
3360 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3361 SDValue V1, SelectionDAG &DAG) {
3363 default: llvm_unreachable("Unknown x86 shuffle node");
3364 case X86ISD::MOVSHDUP:
3365 case X86ISD::MOVSLDUP:
3366 case X86ISD::MOVDDUP:
3367 return DAG.getNode(Opc, dl, VT, V1);
3371 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3372 SDValue V1, unsigned TargetMask,
3373 SelectionDAG &DAG) {
3375 default: llvm_unreachable("Unknown x86 shuffle node");
3376 case X86ISD::PSHUFD:
3377 case X86ISD::PSHUFHW:
3378 case X86ISD::PSHUFLW:
3379 case X86ISD::VPERMILP:
3380 case X86ISD::VPERMI:
3381 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3385 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3386 SDValue V1, SDValue V2, unsigned TargetMask,
3387 SelectionDAG &DAG) {
3389 default: llvm_unreachable("Unknown x86 shuffle node");
3390 case X86ISD::PALIGNR:
3392 case X86ISD::VPERM2X128:
3393 return DAG.getNode(Opc, dl, VT, V1, V2,
3394 DAG.getConstant(TargetMask, MVT::i8));
3398 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3399 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3401 default: llvm_unreachable("Unknown x86 shuffle node");
3402 case X86ISD::MOVLHPS:
3403 case X86ISD::MOVLHPD:
3404 case X86ISD::MOVHLPS:
3405 case X86ISD::MOVLPS:
3406 case X86ISD::MOVLPD:
3409 case X86ISD::UNPCKL:
3410 case X86ISD::UNPCKH:
3411 return DAG.getNode(Opc, dl, VT, V1, V2);
3415 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3416 MachineFunction &MF = DAG.getMachineFunction();
3417 const X86RegisterInfo *RegInfo =
3418 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3419 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3420 int ReturnAddrIndex = FuncInfo->getRAIndex();
3422 if (ReturnAddrIndex == 0) {
3423 // Set up a frame object for the return address.
3424 unsigned SlotSize = RegInfo->getSlotSize();
3425 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3428 FuncInfo->setRAIndex(ReturnAddrIndex);
3431 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3434 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3435 bool hasSymbolicDisplacement) {
3436 // Offset should fit into 32 bit immediate field.
3437 if (!isInt<32>(Offset))
3440 // If we don't have a symbolic displacement - we don't have any extra
3442 if (!hasSymbolicDisplacement)
3445 // FIXME: Some tweaks might be needed for medium code model.
3446 if (M != CodeModel::Small && M != CodeModel::Kernel)
3449 // For small code model we assume that latest object is 16MB before end of 31
3450 // bits boundary. We may also accept pretty large negative constants knowing
3451 // that all objects are in the positive half of address space.
3452 if (M == CodeModel::Small && Offset < 16*1024*1024)
3455 // For kernel code model we know that all object resist in the negative half
3456 // of 32bits address space. We may not accept negative offsets, since they may
3457 // be just off and we may accept pretty large positive ones.
3458 if (M == CodeModel::Kernel && Offset > 0)
3464 /// isCalleePop - Determines whether the callee is required to pop its
3465 /// own arguments. Callee pop is necessary to support tail calls.
3466 bool X86::isCalleePop(CallingConv::ID CallingConv,
3467 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3471 switch (CallingConv) {
3474 case CallingConv::X86_StdCall:
3476 case CallingConv::X86_FastCall:
3478 case CallingConv::X86_ThisCall:
3480 case CallingConv::Fast:
3482 case CallingConv::GHC:
3484 case CallingConv::HiPE:
3489 /// \brief Return true if the condition is an unsigned comparison operation.
3490 static bool isX86CCUnsigned(unsigned X86CC) {
3492 default: llvm_unreachable("Invalid integer condition!");
3493 case X86::COND_E: return true;
3494 case X86::COND_G: return false;
3495 case X86::COND_GE: return false;
3496 case X86::COND_L: return false;
3497 case X86::COND_LE: return false;
3498 case X86::COND_NE: return true;
3499 case X86::COND_B: return true;
3500 case X86::COND_A: return true;
3501 case X86::COND_BE: return true;
3502 case X86::COND_AE: return true;
3504 llvm_unreachable("covered switch fell through?!");
3507 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3508 /// specific condition code, returning the condition code and the LHS/RHS of the
3509 /// comparison to make.
3510 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3511 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3513 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3514 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3515 // X > -1 -> X == 0, jump !sign.
3516 RHS = DAG.getConstant(0, RHS.getValueType());
3517 return X86::COND_NS;
3519 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3520 // X < 0 -> X == 0, jump on sign.
3523 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3525 RHS = DAG.getConstant(0, RHS.getValueType());
3526 return X86::COND_LE;
3530 switch (SetCCOpcode) {
3531 default: llvm_unreachable("Invalid integer condition!");
3532 case ISD::SETEQ: return X86::COND_E;
3533 case ISD::SETGT: return X86::COND_G;
3534 case ISD::SETGE: return X86::COND_GE;
3535 case ISD::SETLT: return X86::COND_L;
3536 case ISD::SETLE: return X86::COND_LE;
3537 case ISD::SETNE: return X86::COND_NE;
3538 case ISD::SETULT: return X86::COND_B;
3539 case ISD::SETUGT: return X86::COND_A;
3540 case ISD::SETULE: return X86::COND_BE;
3541 case ISD::SETUGE: return X86::COND_AE;
3545 // First determine if it is required or is profitable to flip the operands.
3547 // If LHS is a foldable load, but RHS is not, flip the condition.
3548 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3549 !ISD::isNON_EXTLoad(RHS.getNode())) {
3550 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3551 std::swap(LHS, RHS);
3554 switch (SetCCOpcode) {
3560 std::swap(LHS, RHS);
3564 // On a floating point condition, the flags are set as follows:
3566 // 0 | 0 | 0 | X > Y
3567 // 0 | 0 | 1 | X < Y
3568 // 1 | 0 | 0 | X == Y
3569 // 1 | 1 | 1 | unordered
3570 switch (SetCCOpcode) {
3571 default: llvm_unreachable("Condcode should be pre-legalized away");
3573 case ISD::SETEQ: return X86::COND_E;
3574 case ISD::SETOLT: // flipped
3576 case ISD::SETGT: return X86::COND_A;
3577 case ISD::SETOLE: // flipped
3579 case ISD::SETGE: return X86::COND_AE;
3580 case ISD::SETUGT: // flipped
3582 case ISD::SETLT: return X86::COND_B;
3583 case ISD::SETUGE: // flipped
3585 case ISD::SETLE: return X86::COND_BE;
3587 case ISD::SETNE: return X86::COND_NE;
3588 case ISD::SETUO: return X86::COND_P;
3589 case ISD::SETO: return X86::COND_NP;
3591 case ISD::SETUNE: return X86::COND_INVALID;
3595 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3596 /// code. Current x86 isa includes the following FP cmov instructions:
3597 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3598 static bool hasFPCMov(unsigned X86CC) {
3614 /// isFPImmLegal - Returns true if the target can instruction select the
3615 /// specified FP immediate natively. If false, the legalizer will
3616 /// materialize the FP immediate as a load from a constant pool.
3617 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3618 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3619 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3625 /// \brief Returns true if it is beneficial to convert a load of a constant
3626 /// to just the constant itself.
3627 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3629 assert(Ty->isIntegerTy());
3631 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3632 if (BitSize == 0 || BitSize > 64)
3637 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3638 /// the specified range (L, H].
3639 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3640 return (Val < 0) || (Val >= Low && Val < Hi);
3643 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3644 /// specified value.
3645 static bool isUndefOrEqual(int Val, int CmpVal) {
3646 return (Val < 0 || Val == CmpVal);
3649 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3650 /// from position Pos and ending in Pos+Size, falls within the specified
3651 /// sequential range (L, L+Pos]. or is undef.
3652 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3653 unsigned Pos, unsigned Size, int Low) {
3654 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3655 if (!isUndefOrEqual(Mask[i], Low))
3660 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3661 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3662 /// the second operand.
3663 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3664 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3665 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3666 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3667 return (Mask[0] < 2 && Mask[1] < 2);
3671 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3672 /// is suitable for input to PSHUFHW.
3673 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3674 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3677 // Lower quadword copied in order or undef.
3678 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3681 // Upper quadword shuffled.
3682 for (unsigned i = 4; i != 8; ++i)
3683 if (!isUndefOrInRange(Mask[i], 4, 8))
3686 if (VT == MVT::v16i16) {
3687 // Lower quadword copied in order or undef.
3688 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3691 // Upper quadword shuffled.
3692 for (unsigned i = 12; i != 16; ++i)
3693 if (!isUndefOrInRange(Mask[i], 12, 16))
3700 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3701 /// is suitable for input to PSHUFLW.
3702 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3703 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3706 // Upper quadword copied in order.
3707 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3710 // Lower quadword shuffled.
3711 for (unsigned i = 0; i != 4; ++i)
3712 if (!isUndefOrInRange(Mask[i], 0, 4))
3715 if (VT == MVT::v16i16) {
3716 // Upper quadword copied in order.
3717 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3720 // Lower quadword shuffled.
3721 for (unsigned i = 8; i != 12; ++i)
3722 if (!isUndefOrInRange(Mask[i], 8, 12))
3729 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3730 /// is suitable for input to PALIGNR.
3731 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3732 const X86Subtarget *Subtarget) {
3733 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3734 (VT.is256BitVector() && !Subtarget->hasInt256()))
3737 unsigned NumElts = VT.getVectorNumElements();
3738 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3739 unsigned NumLaneElts = NumElts/NumLanes;
3741 // Do not handle 64-bit element shuffles with palignr.
3742 if (NumLaneElts == 2)
3745 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3747 for (i = 0; i != NumLaneElts; ++i) {
3752 // Lane is all undef, go to next lane
3753 if (i == NumLaneElts)
3756 int Start = Mask[i+l];
3758 // Make sure its in this lane in one of the sources
3759 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3760 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3763 // If not lane 0, then we must match lane 0
3764 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3767 // Correct second source to be contiguous with first source
3768 if (Start >= (int)NumElts)
3769 Start -= NumElts - NumLaneElts;
3771 // Make sure we're shifting in the right direction.
3772 if (Start <= (int)(i+l))
3777 // Check the rest of the elements to see if they are consecutive.
3778 for (++i; i != NumLaneElts; ++i) {
3779 int Idx = Mask[i+l];
3781 // Make sure its in this lane
3782 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3783 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3786 // If not lane 0, then we must match lane 0
3787 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3790 if (Idx >= (int)NumElts)
3791 Idx -= NumElts - NumLaneElts;
3793 if (!isUndefOrEqual(Idx, Start+i))
3802 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3803 /// the two vector operands have swapped position.
3804 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3805 unsigned NumElems) {
3806 for (unsigned i = 0; i != NumElems; ++i) {
3810 else if (idx < (int)NumElems)
3811 Mask[i] = idx + NumElems;
3813 Mask[i] = idx - NumElems;
3817 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3818 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3819 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3820 /// reverse of what x86 shuffles want.
3821 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3823 unsigned NumElems = VT.getVectorNumElements();
3824 unsigned NumLanes = VT.getSizeInBits()/128;
3825 unsigned NumLaneElems = NumElems/NumLanes;
3827 if (NumLaneElems != 2 && NumLaneElems != 4)
3830 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3831 bool symetricMaskRequired =
3832 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3834 // VSHUFPSY divides the resulting vector into 4 chunks.
3835 // The sources are also splitted into 4 chunks, and each destination
3836 // chunk must come from a different source chunk.
3838 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3839 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3841 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3842 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3844 // VSHUFPDY divides the resulting vector into 4 chunks.
3845 // The sources are also splitted into 4 chunks, and each destination
3846 // chunk must come from a different source chunk.
3848 // SRC1 => X3 X2 X1 X0
3849 // SRC2 => Y3 Y2 Y1 Y0
3851 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3853 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3854 unsigned HalfLaneElems = NumLaneElems/2;
3855 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3856 for (unsigned i = 0; i != NumLaneElems; ++i) {
3857 int Idx = Mask[i+l];
3858 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3859 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3861 // For VSHUFPSY, the mask of the second half must be the same as the
3862 // first but with the appropriate offsets. This works in the same way as
3863 // VPERMILPS works with masks.
3864 if (!symetricMaskRequired || Idx < 0)
3866 if (MaskVal[i] < 0) {
3867 MaskVal[i] = Idx - l;
3870 if ((signed)(Idx - l) != MaskVal[i])
3878 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3879 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3880 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3881 if (!VT.is128BitVector())
3884 unsigned NumElems = VT.getVectorNumElements();
3889 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3890 return isUndefOrEqual(Mask[0], 6) &&
3891 isUndefOrEqual(Mask[1], 7) &&
3892 isUndefOrEqual(Mask[2], 2) &&
3893 isUndefOrEqual(Mask[3], 3);
3896 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3897 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3899 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3900 if (!VT.is128BitVector())
3903 unsigned NumElems = VT.getVectorNumElements();
3908 return isUndefOrEqual(Mask[0], 2) &&
3909 isUndefOrEqual(Mask[1], 3) &&
3910 isUndefOrEqual(Mask[2], 2) &&
3911 isUndefOrEqual(Mask[3], 3);
3914 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3915 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3916 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3917 if (!VT.is128BitVector())
3920 unsigned NumElems = VT.getVectorNumElements();
3922 if (NumElems != 2 && NumElems != 4)
3925 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3926 if (!isUndefOrEqual(Mask[i], i + NumElems))
3929 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3930 if (!isUndefOrEqual(Mask[i], i))
3936 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3938 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3939 if (!VT.is128BitVector())
3942 unsigned NumElems = VT.getVectorNumElements();
3944 if (NumElems != 2 && NumElems != 4)
3947 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3948 if (!isUndefOrEqual(Mask[i], i))
3951 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3952 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3958 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3959 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3960 /// i. e: If all but one element come from the same vector.
3961 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3962 // TODO: Deal with AVX's VINSERTPS
3963 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3966 unsigned CorrectPosV1 = 0;
3967 unsigned CorrectPosV2 = 0;
3968 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3971 else if (Mask[i] == i + 4)
3974 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3975 // We have 3 elements from one vector, and one from another.
3982 // Some special combinations that can be optimized.
3985 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3986 SelectionDAG &DAG) {
3987 MVT VT = SVOp->getSimpleValueType(0);
3990 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3993 ArrayRef<int> Mask = SVOp->getMask();
3995 // These are the special masks that may be optimized.
3996 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3997 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3998 bool MatchEvenMask = true;
3999 bool MatchOddMask = true;
4000 for (int i=0; i<8; ++i) {
4001 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4002 MatchEvenMask = false;
4003 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4004 MatchOddMask = false;
4007 if (!MatchEvenMask && !MatchOddMask)
4010 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4012 SDValue Op0 = SVOp->getOperand(0);
4013 SDValue Op1 = SVOp->getOperand(1);
4015 if (MatchEvenMask) {
4016 // Shift the second operand right to 32 bits.
4017 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4018 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4020 // Shift the first operand left to 32 bits.
4021 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4022 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4024 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4025 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4028 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4029 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4030 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4031 bool HasInt256, bool V2IsSplat = false) {
4033 assert(VT.getSizeInBits() >= 128 &&
4034 "Unsupported vector type for unpckl");
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; 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 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4077 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4078 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4079 bool HasInt256, bool V2IsSplat = false) {
4080 assert(VT.getSizeInBits() >= 128 &&
4081 "Unsupported vector type for unpckh");
4083 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4085 unsigned NumOf256BitLanes;
4086 unsigned NumElts = VT.getVectorNumElements();
4087 if (VT.is256BitVector()) {
4088 if (NumElts != 4 && NumElts != 8 &&
4089 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4092 NumOf256BitLanes = 1;
4093 } else if (VT.is512BitVector()) {
4094 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4095 "Unsupported vector type for unpckh");
4097 NumOf256BitLanes = 2;
4100 NumOf256BitLanes = 1;
4103 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4104 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4106 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4107 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4108 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4109 int BitI = Mask[l256*NumEltsInStride+l+i];
4110 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4111 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4113 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4115 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4123 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4124 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4126 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4127 unsigned NumElts = VT.getVectorNumElements();
4128 bool Is256BitVec = VT.is256BitVector();
4130 if (VT.is512BitVector())
4132 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4133 "Unsupported vector type for unpckh");
4135 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4136 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4139 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4140 // FIXME: Need a better way to get rid of this, there's no latency difference
4141 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4142 // the former later. We should also remove the "_undef" special mask.
4143 if (NumElts == 4 && Is256BitVec)
4146 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4147 // independently on 128-bit lanes.
4148 unsigned NumLanes = VT.getSizeInBits()/128;
4149 unsigned NumLaneElts = NumElts/NumLanes;
4151 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4152 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4153 int BitI = Mask[l+i];
4154 int BitI1 = Mask[l+i+1];
4156 if (!isUndefOrEqual(BitI, j))
4158 if (!isUndefOrEqual(BitI1, j))
4166 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4167 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4169 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4170 unsigned NumElts = VT.getVectorNumElements();
4172 if (VT.is512BitVector())
4175 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4176 "Unsupported vector type for unpckh");
4178 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4179 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4182 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4183 // independently on 128-bit lanes.
4184 unsigned NumLanes = VT.getSizeInBits()/128;
4185 unsigned NumLaneElts = NumElts/NumLanes;
4187 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4188 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4189 int BitI = Mask[l+i];
4190 int BitI1 = Mask[l+i+1];
4191 if (!isUndefOrEqual(BitI, j))
4193 if (!isUndefOrEqual(BitI1, j))
4200 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4201 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4202 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4203 if (!VT.is512BitVector())
4206 unsigned NumElts = VT.getVectorNumElements();
4207 unsigned HalfSize = NumElts/2;
4208 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4209 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4214 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4215 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4223 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4224 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4225 /// MOVSD, and MOVD, i.e. setting the lowest element.
4226 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4227 if (VT.getVectorElementType().getSizeInBits() < 32)
4229 if (!VT.is128BitVector())
4232 unsigned NumElts = VT.getVectorNumElements();
4234 if (!isUndefOrEqual(Mask[0], NumElts))
4237 for (unsigned i = 1; i != NumElts; ++i)
4238 if (!isUndefOrEqual(Mask[i], i))
4244 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4245 /// as permutations between 128-bit chunks or halves. As an example: this
4247 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4248 /// The first half comes from the second half of V1 and the second half from the
4249 /// the second half of V2.
4250 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4251 if (!HasFp256 || !VT.is256BitVector())
4254 // The shuffle result is divided into half A and half B. In total the two
4255 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4256 // B must come from C, D, E or F.
4257 unsigned HalfSize = VT.getVectorNumElements()/2;
4258 bool MatchA = false, MatchB = false;
4260 // Check if A comes from one of C, D, E, F.
4261 for (unsigned Half = 0; Half != 4; ++Half) {
4262 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4268 // Check if B comes from one of C, D, E, F.
4269 for (unsigned Half = 0; Half != 4; ++Half) {
4270 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4276 return MatchA && MatchB;
4279 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4280 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4281 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4282 MVT VT = SVOp->getSimpleValueType(0);
4284 unsigned HalfSize = VT.getVectorNumElements()/2;
4286 unsigned FstHalf = 0, SndHalf = 0;
4287 for (unsigned i = 0; i < HalfSize; ++i) {
4288 if (SVOp->getMaskElt(i) > 0) {
4289 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4293 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4294 if (SVOp->getMaskElt(i) > 0) {
4295 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4300 return (FstHalf | (SndHalf << 4));
4303 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4304 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4305 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4309 unsigned NumElts = VT.getVectorNumElements();
4311 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4312 for (unsigned i = 0; i != NumElts; ++i) {
4315 Imm8 |= Mask[i] << (i*2);
4320 unsigned LaneSize = 4;
4321 SmallVector<int, 4> MaskVal(LaneSize, -1);
4323 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4324 for (unsigned i = 0; i != LaneSize; ++i) {
4325 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4329 if (MaskVal[i] < 0) {
4330 MaskVal[i] = Mask[i+l] - l;
4331 Imm8 |= MaskVal[i] << (i*2);
4334 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4341 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4342 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4343 /// Note that VPERMIL mask matching is different depending whether theunderlying
4344 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4345 /// to the same elements of the low, but to the higher half of the source.
4346 /// In VPERMILPD the two lanes could be shuffled independently of each other
4347 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4348 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4349 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4350 if (VT.getSizeInBits() < 256 || EltSize < 32)
4352 bool symetricMaskRequired = (EltSize == 32);
4353 unsigned NumElts = VT.getVectorNumElements();
4355 unsigned NumLanes = VT.getSizeInBits()/128;
4356 unsigned LaneSize = NumElts/NumLanes;
4357 // 2 or 4 elements in one lane
4359 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4360 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4361 for (unsigned i = 0; i != LaneSize; ++i) {
4362 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4364 if (symetricMaskRequired) {
4365 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4366 ExpectedMaskVal[i] = Mask[i+l] - l;
4369 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4377 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4378 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4379 /// element of vector 2 and the other elements to come from vector 1 in order.
4380 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4381 bool V2IsSplat = false, bool V2IsUndef = false) {
4382 if (!VT.is128BitVector())
4385 unsigned NumOps = VT.getVectorNumElements();
4386 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4389 if (!isUndefOrEqual(Mask[0], 0))
4392 for (unsigned i = 1; i != NumOps; ++i)
4393 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4394 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4395 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4401 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4402 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4403 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4404 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4405 const X86Subtarget *Subtarget) {
4406 if (!Subtarget->hasSSE3())
4409 unsigned NumElems = VT.getVectorNumElements();
4411 if ((VT.is128BitVector() && NumElems != 4) ||
4412 (VT.is256BitVector() && NumElems != 8) ||
4413 (VT.is512BitVector() && NumElems != 16))
4416 // "i+1" is the value the indexed mask element must have
4417 for (unsigned i = 0; i != NumElems; i += 2)
4418 if (!isUndefOrEqual(Mask[i], i+1) ||
4419 !isUndefOrEqual(Mask[i+1], i+1))
4425 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4426 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4427 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4428 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4429 const X86Subtarget *Subtarget) {
4430 if (!Subtarget->hasSSE3())
4433 unsigned NumElems = VT.getVectorNumElements();
4435 if ((VT.is128BitVector() && NumElems != 4) ||
4436 (VT.is256BitVector() && NumElems != 8) ||
4437 (VT.is512BitVector() && NumElems != 16))
4440 // "i" is the value the indexed mask element must have
4441 for (unsigned i = 0; i != NumElems; i += 2)
4442 if (!isUndefOrEqual(Mask[i], i) ||
4443 !isUndefOrEqual(Mask[i+1], i))
4449 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4450 /// specifies a shuffle of elements that is suitable for input to 256-bit
4451 /// version of MOVDDUP.
4452 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4453 if (!HasFp256 || !VT.is256BitVector())
4456 unsigned NumElts = VT.getVectorNumElements();
4460 for (unsigned i = 0; i != NumElts/2; ++i)
4461 if (!isUndefOrEqual(Mask[i], 0))
4463 for (unsigned i = NumElts/2; i != NumElts; ++i)
4464 if (!isUndefOrEqual(Mask[i], NumElts/2))
4469 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4470 /// specifies a shuffle of elements that is suitable for input to 128-bit
4471 /// version of MOVDDUP.
4472 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4473 if (!VT.is128BitVector())
4476 unsigned e = VT.getVectorNumElements() / 2;
4477 for (unsigned i = 0; i != e; ++i)
4478 if (!isUndefOrEqual(Mask[i], i))
4480 for (unsigned i = 0; i != e; ++i)
4481 if (!isUndefOrEqual(Mask[e+i], i))
4486 /// isVEXTRACTIndex - Return true if the specified
4487 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4488 /// suitable for instruction that extract 128 or 256 bit vectors
4489 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4490 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4491 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4494 // The index should be aligned on a vecWidth-bit boundary.
4496 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4498 MVT VT = N->getSimpleValueType(0);
4499 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4500 bool Result = (Index * ElSize) % vecWidth == 0;
4505 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4506 /// operand specifies a subvector insert that is suitable for input to
4507 /// insertion of 128 or 256-bit subvectors
4508 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4509 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4510 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4512 // The index should be aligned on a vecWidth-bit boundary.
4514 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4516 MVT VT = N->getSimpleValueType(0);
4517 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4518 bool Result = (Index * ElSize) % vecWidth == 0;
4523 bool X86::isVINSERT128Index(SDNode *N) {
4524 return isVINSERTIndex(N, 128);
4527 bool X86::isVINSERT256Index(SDNode *N) {
4528 return isVINSERTIndex(N, 256);
4531 bool X86::isVEXTRACT128Index(SDNode *N) {
4532 return isVEXTRACTIndex(N, 128);
4535 bool X86::isVEXTRACT256Index(SDNode *N) {
4536 return isVEXTRACTIndex(N, 256);
4539 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4540 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4541 /// Handles 128-bit and 256-bit.
4542 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4543 MVT VT = N->getSimpleValueType(0);
4545 assert((VT.getSizeInBits() >= 128) &&
4546 "Unsupported vector type for PSHUF/SHUFP");
4548 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4549 // independently on 128-bit lanes.
4550 unsigned NumElts = VT.getVectorNumElements();
4551 unsigned NumLanes = VT.getSizeInBits()/128;
4552 unsigned NumLaneElts = NumElts/NumLanes;
4554 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4555 "Only supports 2, 4 or 8 elements per lane");
4557 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4559 for (unsigned i = 0; i != NumElts; ++i) {
4560 int Elt = N->getMaskElt(i);
4561 if (Elt < 0) continue;
4562 Elt &= NumLaneElts - 1;
4563 unsigned ShAmt = (i << Shift) % 8;
4564 Mask |= Elt << ShAmt;
4570 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4571 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4572 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4573 MVT VT = N->getSimpleValueType(0);
4575 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4576 "Unsupported vector type for PSHUFHW");
4578 unsigned NumElts = VT.getVectorNumElements();
4581 for (unsigned l = 0; l != NumElts; l += 8) {
4582 // 8 nodes per lane, but we only care about the last 4.
4583 for (unsigned i = 0; i < 4; ++i) {
4584 int Elt = N->getMaskElt(l+i+4);
4585 if (Elt < 0) continue;
4586 Elt &= 0x3; // only 2-bits.
4587 Mask |= Elt << (i * 2);
4594 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4595 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4596 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4597 MVT VT = N->getSimpleValueType(0);
4599 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4600 "Unsupported vector type for PSHUFHW");
4602 unsigned NumElts = VT.getVectorNumElements();
4605 for (unsigned l = 0; l != NumElts; l += 8) {
4606 // 8 nodes per lane, but we only care about the first 4.
4607 for (unsigned i = 0; i < 4; ++i) {
4608 int Elt = N->getMaskElt(l+i);
4609 if (Elt < 0) continue;
4610 Elt &= 0x3; // only 2-bits
4611 Mask |= Elt << (i * 2);
4618 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4619 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4620 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4621 MVT VT = SVOp->getSimpleValueType(0);
4622 unsigned EltSize = VT.is512BitVector() ? 1 :
4623 VT.getVectorElementType().getSizeInBits() >> 3;
4625 unsigned NumElts = VT.getVectorNumElements();
4626 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4627 unsigned NumLaneElts = NumElts/NumLanes;
4631 for (i = 0; i != NumElts; ++i) {
4632 Val = SVOp->getMaskElt(i);
4636 if (Val >= (int)NumElts)
4637 Val -= NumElts - NumLaneElts;
4639 assert(Val - i > 0 && "PALIGNR imm should be positive");
4640 return (Val - i) * EltSize;
4643 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4644 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4645 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4646 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4649 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4651 MVT VecVT = N->getOperand(0).getSimpleValueType();
4652 MVT ElVT = VecVT.getVectorElementType();
4654 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4655 return Index / NumElemsPerChunk;
4658 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4659 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4660 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4661 llvm_unreachable("Illegal insert subvector for VINSERT");
4664 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4666 MVT VecVT = N->getSimpleValueType(0);
4667 MVT ElVT = VecVT.getVectorElementType();
4669 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4670 return Index / NumElemsPerChunk;
4673 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4674 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4675 /// and VINSERTI128 instructions.
4676 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4677 return getExtractVEXTRACTImmediate(N, 128);
4680 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4681 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4682 /// and VINSERTI64x4 instructions.
4683 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4684 return getExtractVEXTRACTImmediate(N, 256);
4687 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4688 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4689 /// and VINSERTI128 instructions.
4690 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4691 return getInsertVINSERTImmediate(N, 128);
4694 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4695 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4696 /// and VINSERTI64x4 instructions.
4697 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4698 return getInsertVINSERTImmediate(N, 256);
4701 /// isZero - Returns true if Elt is a constant integer zero
4702 static bool isZero(SDValue V) {
4703 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4704 return C && C->isNullValue();
4707 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4709 bool X86::isZeroNode(SDValue Elt) {
4712 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4713 return CFP->getValueAPF().isPosZero();
4717 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4718 /// their permute mask.
4719 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4720 SelectionDAG &DAG) {
4721 MVT VT = SVOp->getSimpleValueType(0);
4722 unsigned NumElems = VT.getVectorNumElements();
4723 SmallVector<int, 8> MaskVec;
4725 for (unsigned i = 0; i != NumElems; ++i) {
4726 int Idx = SVOp->getMaskElt(i);
4728 if (Idx < (int)NumElems)
4733 MaskVec.push_back(Idx);
4735 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4736 SVOp->getOperand(0), &MaskVec[0]);
4739 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4740 /// match movhlps. The lower half elements should come from upper half of
4741 /// V1 (and in order), and the upper half elements should come from the upper
4742 /// half of V2 (and in order).
4743 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4744 if (!VT.is128BitVector())
4746 if (VT.getVectorNumElements() != 4)
4748 for (unsigned i = 0, e = 2; i != e; ++i)
4749 if (!isUndefOrEqual(Mask[i], i+2))
4751 for (unsigned i = 2; i != 4; ++i)
4752 if (!isUndefOrEqual(Mask[i], i+4))
4757 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4758 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4760 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4761 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4763 N = N->getOperand(0).getNode();
4764 if (!ISD::isNON_EXTLoad(N))
4767 *LD = cast<LoadSDNode>(N);
4771 // Test whether the given value is a vector value which will be legalized
4773 static bool WillBeConstantPoolLoad(SDNode *N) {
4774 if (N->getOpcode() != ISD::BUILD_VECTOR)
4777 // Check for any non-constant elements.
4778 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4779 switch (N->getOperand(i).getNode()->getOpcode()) {
4781 case ISD::ConstantFP:
4788 // Vectors of all-zeros and all-ones are materialized with special
4789 // instructions rather than being loaded.
4790 return !ISD::isBuildVectorAllZeros(N) &&
4791 !ISD::isBuildVectorAllOnes(N);
4794 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4795 /// match movlp{s|d}. The lower half elements should come from lower half of
4796 /// V1 (and in order), and the upper half elements should come from the upper
4797 /// half of V2 (and in order). And since V1 will become the source of the
4798 /// MOVLP, it must be either a vector load or a scalar load to vector.
4799 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4800 ArrayRef<int> Mask, MVT VT) {
4801 if (!VT.is128BitVector())
4804 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4806 // Is V2 is a vector load, don't do this transformation. We will try to use
4807 // load folding shufps op.
4808 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4811 unsigned NumElems = VT.getVectorNumElements();
4813 if (NumElems != 2 && NumElems != 4)
4815 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4816 if (!isUndefOrEqual(Mask[i], i))
4818 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4819 if (!isUndefOrEqual(Mask[i], i+NumElems))
4824 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4826 static bool isSplatVector(SDNode *N) {
4827 if (N->getOpcode() != ISD::BUILD_VECTOR)
4830 SDValue SplatValue = N->getOperand(0);
4831 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4832 if (N->getOperand(i) != SplatValue)
4837 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4838 /// to an zero vector.
4839 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4840 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4841 SDValue V1 = N->getOperand(0);
4842 SDValue V2 = N->getOperand(1);
4843 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4844 for (unsigned i = 0; i != NumElems; ++i) {
4845 int Idx = N->getMaskElt(i);
4846 if (Idx >= (int)NumElems) {
4847 unsigned Opc = V2.getOpcode();
4848 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4850 if (Opc != ISD::BUILD_VECTOR ||
4851 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4853 } else if (Idx >= 0) {
4854 unsigned Opc = V1.getOpcode();
4855 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4857 if (Opc != ISD::BUILD_VECTOR ||
4858 !X86::isZeroNode(V1.getOperand(Idx)))
4865 /// getZeroVector - Returns a vector of specified type with all zero elements.
4867 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4868 SelectionDAG &DAG, SDLoc dl) {
4869 assert(VT.isVector() && "Expected a vector type");
4871 // Always build SSE zero vectors as <4 x i32> bitcasted
4872 // to their dest type. This ensures they get CSE'd.
4874 if (VT.is128BitVector()) { // SSE
4875 if (Subtarget->hasSSE2()) { // SSE2
4876 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4877 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4879 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4880 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4882 } else if (VT.is256BitVector()) { // AVX
4883 if (Subtarget->hasInt256()) { // AVX2
4884 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4885 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4886 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4888 // 256-bit logic and arithmetic instructions in AVX are all
4889 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4890 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4891 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4892 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4894 } else if (VT.is512BitVector()) { // AVX-512
4895 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4896 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4897 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4898 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4899 } else if (VT.getScalarType() == MVT::i1) {
4900 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4901 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4902 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4903 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4905 llvm_unreachable("Unexpected vector type");
4907 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4910 /// getOnesVector - Returns a vector of specified type with all bits set.
4911 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4912 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4913 /// Then bitcast to their original type, ensuring they get CSE'd.
4914 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4916 assert(VT.isVector() && "Expected a vector type");
4918 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4920 if (VT.is256BitVector()) {
4921 if (HasInt256) { // AVX2
4922 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4923 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4925 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4926 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4928 } else if (VT.is128BitVector()) {
4929 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4931 llvm_unreachable("Unexpected vector type");
4933 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4936 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4937 /// that point to V2 points to its first element.
4938 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4939 for (unsigned i = 0; i != NumElems; ++i) {
4940 if (Mask[i] > (int)NumElems) {
4946 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4947 /// operation of specified width.
4948 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4950 unsigned NumElems = VT.getVectorNumElements();
4951 SmallVector<int, 8> Mask;
4952 Mask.push_back(NumElems);
4953 for (unsigned i = 1; i != NumElems; ++i)
4955 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4958 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4959 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4961 unsigned NumElems = VT.getVectorNumElements();
4962 SmallVector<int, 8> Mask;
4963 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4965 Mask.push_back(i + NumElems);
4967 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4970 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4971 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4973 unsigned NumElems = VT.getVectorNumElements();
4974 SmallVector<int, 8> Mask;
4975 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4976 Mask.push_back(i + Half);
4977 Mask.push_back(i + NumElems + Half);
4979 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4982 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4983 // a generic shuffle instruction because the target has no such instructions.
4984 // Generate shuffles which repeat i16 and i8 several times until they can be
4985 // represented by v4f32 and then be manipulated by target suported shuffles.
4986 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4987 MVT VT = V.getSimpleValueType();
4988 int NumElems = VT.getVectorNumElements();
4991 while (NumElems > 4) {
4992 if (EltNo < NumElems/2) {
4993 V = getUnpackl(DAG, dl, VT, V, V);
4995 V = getUnpackh(DAG, dl, VT, V, V);
4996 EltNo -= NumElems/2;
5003 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5004 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5005 MVT VT = V.getSimpleValueType();
5008 if (VT.is128BitVector()) {
5009 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5010 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5011 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5013 } else if (VT.is256BitVector()) {
5014 // To use VPERMILPS to splat scalars, the second half of indicies must
5015 // refer to the higher part, which is a duplication of the lower one,
5016 // because VPERMILPS can only handle in-lane permutations.
5017 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5018 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5020 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5021 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5024 llvm_unreachable("Vector size not supported");
5026 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5029 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5030 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5031 MVT SrcVT = SV->getSimpleValueType(0);
5032 SDValue V1 = SV->getOperand(0);
5035 int EltNo = SV->getSplatIndex();
5036 int NumElems = SrcVT.getVectorNumElements();
5037 bool Is256BitVec = SrcVT.is256BitVector();
5039 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5040 "Unknown how to promote splat for type");
5042 // Extract the 128-bit part containing the splat element and update
5043 // the splat element index when it refers to the higher register.
5045 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5046 if (EltNo >= NumElems/2)
5047 EltNo -= NumElems/2;
5050 // All i16 and i8 vector types can't be used directly by a generic shuffle
5051 // instruction because the target has no such instruction. Generate shuffles
5052 // which repeat i16 and i8 several times until they fit in i32, and then can
5053 // be manipulated by target suported shuffles.
5054 MVT EltVT = SrcVT.getVectorElementType();
5055 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5056 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5058 // Recreate the 256-bit vector and place the same 128-bit vector
5059 // into the low and high part. This is necessary because we want
5060 // to use VPERM* to shuffle the vectors
5062 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5065 return getLegalSplat(DAG, V1, EltNo);
5068 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5069 /// vector of zero or undef vector. This produces a shuffle where the low
5070 /// element of V2 is swizzled into the zero/undef vector, landing at element
5071 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5072 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5074 const X86Subtarget *Subtarget,
5075 SelectionDAG &DAG) {
5076 MVT VT = V2.getSimpleValueType();
5078 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5079 unsigned NumElems = VT.getVectorNumElements();
5080 SmallVector<int, 16> MaskVec;
5081 for (unsigned i = 0; i != NumElems; ++i)
5082 // If this is the insertion idx, put the low elt of V2 here.
5083 MaskVec.push_back(i == Idx ? NumElems : i);
5084 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5087 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5088 /// target specific opcode. Returns true if the Mask could be calculated.
5089 /// Sets IsUnary to true if only uses one source.
5090 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5091 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5092 unsigned NumElems = VT.getVectorNumElements();
5096 switch(N->getOpcode()) {
5098 ImmN = N->getOperand(N->getNumOperands()-1);
5099 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5101 case X86ISD::UNPCKH:
5102 DecodeUNPCKHMask(VT, Mask);
5104 case X86ISD::UNPCKL:
5105 DecodeUNPCKLMask(VT, Mask);
5107 case X86ISD::MOVHLPS:
5108 DecodeMOVHLPSMask(NumElems, Mask);
5110 case X86ISD::MOVLHPS:
5111 DecodeMOVLHPSMask(NumElems, Mask);
5113 case X86ISD::PALIGNR:
5114 ImmN = N->getOperand(N->getNumOperands()-1);
5115 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5117 case X86ISD::PSHUFD:
5118 case X86ISD::VPERMILP:
5119 ImmN = N->getOperand(N->getNumOperands()-1);
5120 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5123 case X86ISD::PSHUFHW:
5124 ImmN = N->getOperand(N->getNumOperands()-1);
5125 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5128 case X86ISD::PSHUFLW:
5129 ImmN = N->getOperand(N->getNumOperands()-1);
5130 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5133 case X86ISD::VPERMI:
5134 ImmN = N->getOperand(N->getNumOperands()-1);
5135 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5139 case X86ISD::MOVSD: {
5140 // The index 0 always comes from the first element of the second source,
5141 // this is why MOVSS and MOVSD are used in the first place. The other
5142 // elements come from the other positions of the first source vector
5143 Mask.push_back(NumElems);
5144 for (unsigned i = 1; i != NumElems; ++i) {
5149 case X86ISD::VPERM2X128:
5150 ImmN = N->getOperand(N->getNumOperands()-1);
5151 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5152 if (Mask.empty()) return false;
5154 case X86ISD::MOVDDUP:
5155 case X86ISD::MOVLHPD:
5156 case X86ISD::MOVLPD:
5157 case X86ISD::MOVLPS:
5158 case X86ISD::MOVSHDUP:
5159 case X86ISD::MOVSLDUP:
5160 // Not yet implemented
5162 default: llvm_unreachable("unknown target shuffle node");
5168 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5169 /// element of the result of the vector shuffle.
5170 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5173 return SDValue(); // Limit search depth.
5175 SDValue V = SDValue(N, 0);
5176 EVT VT = V.getValueType();
5177 unsigned Opcode = V.getOpcode();
5179 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5180 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5181 int Elt = SV->getMaskElt(Index);
5184 return DAG.getUNDEF(VT.getVectorElementType());
5186 unsigned NumElems = VT.getVectorNumElements();
5187 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5188 : SV->getOperand(1);
5189 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5192 // Recurse into target specific vector shuffles to find scalars.
5193 if (isTargetShuffle(Opcode)) {
5194 MVT ShufVT = V.getSimpleValueType();
5195 unsigned NumElems = ShufVT.getVectorNumElements();
5196 SmallVector<int, 16> ShuffleMask;
5199 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5202 int Elt = ShuffleMask[Index];
5204 return DAG.getUNDEF(ShufVT.getVectorElementType());
5206 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5208 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5212 // Actual nodes that may contain scalar elements
5213 if (Opcode == ISD::BITCAST) {
5214 V = V.getOperand(0);
5215 EVT SrcVT = V.getValueType();
5216 unsigned NumElems = VT.getVectorNumElements();
5218 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5222 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5223 return (Index == 0) ? V.getOperand(0)
5224 : DAG.getUNDEF(VT.getVectorElementType());
5226 if (V.getOpcode() == ISD::BUILD_VECTOR)
5227 return V.getOperand(Index);
5232 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5233 /// shuffle operation which come from a consecutively from a zero. The
5234 /// search can start in two different directions, from left or right.
5235 /// We count undefs as zeros until PreferredNum is reached.
5236 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5237 unsigned NumElems, bool ZerosFromLeft,
5239 unsigned PreferredNum = -1U) {
5240 unsigned NumZeros = 0;
5241 for (unsigned i = 0; i != NumElems; ++i) {
5242 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5243 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5247 if (X86::isZeroNode(Elt))
5249 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5250 NumZeros = std::min(NumZeros + 1, PreferredNum);
5258 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5259 /// correspond consecutively to elements from one of the vector operands,
5260 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5262 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5263 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5264 unsigned NumElems, unsigned &OpNum) {
5265 bool SeenV1 = false;
5266 bool SeenV2 = false;
5268 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5269 int Idx = SVOp->getMaskElt(i);
5270 // Ignore undef indicies
5274 if (Idx < (int)NumElems)
5279 // Only accept consecutive elements from the same vector
5280 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5284 OpNum = SeenV1 ? 0 : 1;
5288 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5289 /// logical left shift of a vector.
5290 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5291 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5293 SVOp->getSimpleValueType(0).getVectorNumElements();
5294 unsigned NumZeros = getNumOfConsecutiveZeros(
5295 SVOp, NumElems, false /* check zeros from right */, DAG,
5296 SVOp->getMaskElt(0));
5302 // Considering the elements in the mask that are not consecutive zeros,
5303 // check if they consecutively come from only one of the source vectors.
5305 // V1 = {X, A, B, C} 0
5307 // vector_shuffle V1, V2 <1, 2, 3, X>
5309 if (!isShuffleMaskConsecutive(SVOp,
5310 0, // Mask Start Index
5311 NumElems-NumZeros, // Mask End Index(exclusive)
5312 NumZeros, // Where to start looking in the src vector
5313 NumElems, // Number of elements in vector
5314 OpSrc)) // Which source operand ?
5319 ShVal = SVOp->getOperand(OpSrc);
5323 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5324 /// logical left shift of a vector.
5325 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5326 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5328 SVOp->getSimpleValueType(0).getVectorNumElements();
5329 unsigned NumZeros = getNumOfConsecutiveZeros(
5330 SVOp, NumElems, true /* check zeros from left */, DAG,
5331 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5337 // Considering the elements in the mask that are not consecutive zeros,
5338 // check if they consecutively come from only one of the source vectors.
5340 // 0 { A, B, X, X } = V2
5342 // vector_shuffle V1, V2 <X, X, 4, 5>
5344 if (!isShuffleMaskConsecutive(SVOp,
5345 NumZeros, // Mask Start Index
5346 NumElems, // Mask End Index(exclusive)
5347 0, // Where to start looking in the src vector
5348 NumElems, // Number of elements in vector
5349 OpSrc)) // Which source operand ?
5354 ShVal = SVOp->getOperand(OpSrc);
5358 /// isVectorShift - Returns true if the shuffle can be implemented as a
5359 /// logical left or right shift of a vector.
5360 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5361 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5362 // Although the logic below support any bitwidth size, there are no
5363 // shift instructions which handle more than 128-bit vectors.
5364 if (!SVOp->getSimpleValueType(0).is128BitVector())
5367 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5368 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5374 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5376 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5377 unsigned NumNonZero, unsigned NumZero,
5379 const X86Subtarget* Subtarget,
5380 const TargetLowering &TLI) {
5387 for (unsigned i = 0; i < 16; ++i) {
5388 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5389 if (ThisIsNonZero && First) {
5391 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5393 V = DAG.getUNDEF(MVT::v8i16);
5398 SDValue ThisElt, LastElt;
5399 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5400 if (LastIsNonZero) {
5401 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5402 MVT::i16, Op.getOperand(i-1));
5404 if (ThisIsNonZero) {
5405 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5406 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5407 ThisElt, DAG.getConstant(8, MVT::i8));
5409 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5413 if (ThisElt.getNode())
5414 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5415 DAG.getIntPtrConstant(i/2));
5419 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5422 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5424 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5425 unsigned NumNonZero, unsigned NumZero,
5427 const X86Subtarget* Subtarget,
5428 const TargetLowering &TLI) {
5435 for (unsigned i = 0; i < 8; ++i) {
5436 bool isNonZero = (NonZeros & (1 << i)) != 0;
5440 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5442 V = DAG.getUNDEF(MVT::v8i16);
5445 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5446 MVT::v8i16, V, Op.getOperand(i),
5447 DAG.getIntPtrConstant(i));
5454 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5455 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5456 unsigned NonZeros, unsigned NumNonZero,
5457 unsigned NumZero, SelectionDAG &DAG,
5458 const X86Subtarget *Subtarget,
5459 const TargetLowering &TLI) {
5460 // We know there's at least one non-zero element
5461 unsigned FirstNonZeroIdx = 0;
5462 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5463 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5464 X86::isZeroNode(FirstNonZero)) {
5466 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5469 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5470 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5473 SDValue V = FirstNonZero.getOperand(0);
5474 MVT VVT = V.getSimpleValueType();
5475 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5478 unsigned FirstNonZeroDst =
5479 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5480 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5481 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5482 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5484 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5485 SDValue Elem = Op.getOperand(Idx);
5486 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5489 // TODO: What else can be here? Deal with it.
5490 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5493 // TODO: Some optimizations are still possible here
5494 // ex: Getting one element from a vector, and the rest from another.
5495 if (Elem.getOperand(0) != V)
5498 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5501 else if (IncorrectIdx == -1U) {
5505 // There was already one element with an incorrect index.
5506 // We can't optimize this case to an insertps.
5510 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5512 EVT VT = Op.getSimpleValueType();
5513 unsigned ElementMoveMask = 0;
5514 if (IncorrectIdx == -1U)
5515 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5517 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5519 SDValue InsertpsMask =
5520 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5521 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5527 /// getVShift - Return a vector logical shift node.
5529 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5530 unsigned NumBits, SelectionDAG &DAG,
5531 const TargetLowering &TLI, SDLoc dl) {
5532 assert(VT.is128BitVector() && "Unknown type for VShift");
5533 EVT ShVT = MVT::v2i64;
5534 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5535 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5536 return DAG.getNode(ISD::BITCAST, dl, VT,
5537 DAG.getNode(Opc, dl, ShVT, SrcOp,
5538 DAG.getConstant(NumBits,
5539 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5543 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5545 // Check if the scalar load can be widened into a vector load. And if
5546 // the address is "base + cst" see if the cst can be "absorbed" into
5547 // the shuffle mask.
5548 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5549 SDValue Ptr = LD->getBasePtr();
5550 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5552 EVT PVT = LD->getValueType(0);
5553 if (PVT != MVT::i32 && PVT != MVT::f32)
5558 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5559 FI = FINode->getIndex();
5561 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5562 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5563 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5564 Offset = Ptr.getConstantOperandVal(1);
5565 Ptr = Ptr.getOperand(0);
5570 // FIXME: 256-bit vector instructions don't require a strict alignment,
5571 // improve this code to support it better.
5572 unsigned RequiredAlign = VT.getSizeInBits()/8;
5573 SDValue Chain = LD->getChain();
5574 // Make sure the stack object alignment is at least 16 or 32.
5575 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5576 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5577 if (MFI->isFixedObjectIndex(FI)) {
5578 // Can't change the alignment. FIXME: It's possible to compute
5579 // the exact stack offset and reference FI + adjust offset instead.
5580 // If someone *really* cares about this. That's the way to implement it.
5583 MFI->setObjectAlignment(FI, RequiredAlign);
5587 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5588 // Ptr + (Offset & ~15).
5591 if ((Offset % RequiredAlign) & 3)
5593 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5595 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5596 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5598 int EltNo = (Offset - StartOffset) >> 2;
5599 unsigned NumElems = VT.getVectorNumElements();
5601 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5602 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5603 LD->getPointerInfo().getWithOffset(StartOffset),
5604 false, false, false, 0);
5606 SmallVector<int, 8> Mask;
5607 for (unsigned i = 0; i != NumElems; ++i)
5608 Mask.push_back(EltNo);
5610 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5616 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5617 /// vector of type 'VT', see if the elements can be replaced by a single large
5618 /// load which has the same value as a build_vector whose operands are 'elts'.
5620 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5622 /// FIXME: we'd also like to handle the case where the last elements are zero
5623 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5624 /// There's even a handy isZeroNode for that purpose.
5625 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5626 SDLoc &DL, SelectionDAG &DAG,
5627 bool isAfterLegalize) {
5628 EVT EltVT = VT.getVectorElementType();
5629 unsigned NumElems = Elts.size();
5631 LoadSDNode *LDBase = nullptr;
5632 unsigned LastLoadedElt = -1U;
5634 // For each element in the initializer, see if we've found a load or an undef.
5635 // If we don't find an initial load element, or later load elements are
5636 // non-consecutive, bail out.
5637 for (unsigned i = 0; i < NumElems; ++i) {
5638 SDValue Elt = Elts[i];
5640 if (!Elt.getNode() ||
5641 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5644 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5646 LDBase = cast<LoadSDNode>(Elt.getNode());
5650 if (Elt.getOpcode() == ISD::UNDEF)
5653 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5654 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5659 // If we have found an entire vector of loads and undefs, then return a large
5660 // load of the entire vector width starting at the base pointer. If we found
5661 // consecutive loads for the low half, generate a vzext_load node.
5662 if (LastLoadedElt == NumElems - 1) {
5664 if (isAfterLegalize &&
5665 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5668 SDValue NewLd = SDValue();
5670 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5671 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5672 LDBase->getPointerInfo(),
5673 LDBase->isVolatile(), LDBase->isNonTemporal(),
5674 LDBase->isInvariant(), 0);
5675 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5676 LDBase->getPointerInfo(),
5677 LDBase->isVolatile(), LDBase->isNonTemporal(),
5678 LDBase->isInvariant(), LDBase->getAlignment());
5680 if (LDBase->hasAnyUseOfValue(1)) {
5681 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5683 SDValue(NewLd.getNode(), 1));
5684 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5685 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5686 SDValue(NewLd.getNode(), 1));
5691 if (NumElems == 4 && LastLoadedElt == 1 &&
5692 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5693 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5694 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5696 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5697 LDBase->getPointerInfo(),
5698 LDBase->getAlignment(),
5699 false/*isVolatile*/, true/*ReadMem*/,
5702 // Make sure the newly-created LOAD is in the same position as LDBase in
5703 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5704 // update uses of LDBase's output chain to use the TokenFactor.
5705 if (LDBase->hasAnyUseOfValue(1)) {
5706 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5707 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5708 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5709 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5710 SDValue(ResNode.getNode(), 1));
5713 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5718 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5719 /// to generate a splat value for the following cases:
5720 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5721 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5722 /// a scalar load, or a constant.
5723 /// The VBROADCAST node is returned when a pattern is found,
5724 /// or SDValue() otherwise.
5725 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5726 SelectionDAG &DAG) {
5727 if (!Subtarget->hasFp256())
5730 MVT VT = Op.getSimpleValueType();
5733 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5734 "Unsupported vector type for broadcast.");
5739 switch (Op.getOpcode()) {
5741 // Unknown pattern found.
5744 case ISD::BUILD_VECTOR: {
5745 // The BUILD_VECTOR node must be a splat.
5746 if (!isSplatVector(Op.getNode()))
5749 Ld = Op.getOperand(0);
5750 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5751 Ld.getOpcode() == ISD::ConstantFP);
5753 // The suspected load node has several users. Make sure that all
5754 // of its users are from the BUILD_VECTOR node.
5755 // Constants may have multiple users.
5756 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5761 case ISD::VECTOR_SHUFFLE: {
5762 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5764 // Shuffles must have a splat mask where the first element is
5766 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5769 SDValue Sc = Op.getOperand(0);
5770 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5771 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5773 if (!Subtarget->hasInt256())
5776 // Use the register form of the broadcast instruction available on AVX2.
5777 if (VT.getSizeInBits() >= 256)
5778 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5779 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5782 Ld = Sc.getOperand(0);
5783 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5784 Ld.getOpcode() == ISD::ConstantFP);
5786 // The scalar_to_vector node and the suspected
5787 // load node must have exactly one user.
5788 // Constants may have multiple users.
5790 // AVX-512 has register version of the broadcast
5791 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5792 Ld.getValueType().getSizeInBits() >= 32;
5793 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5800 bool IsGE256 = (VT.getSizeInBits() >= 256);
5802 // Handle the broadcasting a single constant scalar from the constant pool
5803 // into a vector. On Sandybridge it is still better to load a constant vector
5804 // from the constant pool and not to broadcast it from a scalar.
5805 if (ConstSplatVal && Subtarget->hasInt256()) {
5806 EVT CVT = Ld.getValueType();
5807 assert(!CVT.isVector() && "Must not broadcast a vector type");
5808 unsigned ScalarSize = CVT.getSizeInBits();
5810 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5811 const Constant *C = nullptr;
5812 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5813 C = CI->getConstantIntValue();
5814 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5815 C = CF->getConstantFPValue();
5817 assert(C && "Invalid constant type");
5819 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5820 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5821 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5822 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5823 MachinePointerInfo::getConstantPool(),
5824 false, false, false, Alignment);
5826 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5830 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5831 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5833 // Handle AVX2 in-register broadcasts.
5834 if (!IsLoad && Subtarget->hasInt256() &&
5835 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5836 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5838 // The scalar source must be a normal load.
5842 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5843 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5845 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5846 // double since there is no vbroadcastsd xmm
5847 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5848 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5849 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5852 // Unsupported broadcast.
5856 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5857 /// underlying vector and index.
5859 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5861 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5863 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5864 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5867 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5869 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5871 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5872 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5875 // In this case the vector is the extract_subvector expression and the index
5876 // is 2, as specified by the shuffle.
5877 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5878 SDValue ShuffleVec = SVOp->getOperand(0);
5879 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5880 assert(ShuffleVecVT.getVectorElementType() ==
5881 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5883 int ShuffleIdx = SVOp->getMaskElt(Idx);
5884 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5885 ExtractedFromVec = ShuffleVec;
5891 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5892 MVT VT = Op.getSimpleValueType();
5894 // Skip if insert_vec_elt is not supported.
5895 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5896 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5900 unsigned NumElems = Op.getNumOperands();
5904 SmallVector<unsigned, 4> InsertIndices;
5905 SmallVector<int, 8> Mask(NumElems, -1);
5907 for (unsigned i = 0; i != NumElems; ++i) {
5908 unsigned Opc = Op.getOperand(i).getOpcode();
5910 if (Opc == ISD::UNDEF)
5913 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5914 // Quit if more than 1 elements need inserting.
5915 if (InsertIndices.size() > 1)
5918 InsertIndices.push_back(i);
5922 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5923 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5924 // Quit if non-constant index.
5925 if (!isa<ConstantSDNode>(ExtIdx))
5927 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5929 // Quit if extracted from vector of different type.
5930 if (ExtractedFromVec.getValueType() != VT)
5933 if (!VecIn1.getNode())
5934 VecIn1 = ExtractedFromVec;
5935 else if (VecIn1 != ExtractedFromVec) {
5936 if (!VecIn2.getNode())
5937 VecIn2 = ExtractedFromVec;
5938 else if (VecIn2 != ExtractedFromVec)
5939 // Quit if more than 2 vectors to shuffle
5943 if (ExtractedFromVec == VecIn1)
5945 else if (ExtractedFromVec == VecIn2)
5946 Mask[i] = Idx + NumElems;
5949 if (!VecIn1.getNode())
5952 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5953 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5954 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5955 unsigned Idx = InsertIndices[i];
5956 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5957 DAG.getIntPtrConstant(Idx));
5963 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5965 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5967 MVT VT = Op.getSimpleValueType();
5968 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5969 "Unexpected type in LowerBUILD_VECTORvXi1!");
5972 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5973 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5974 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5975 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5978 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5979 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5980 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5981 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5984 bool AllContants = true;
5985 uint64_t Immediate = 0;
5986 int NonConstIdx = -1;
5987 bool IsSplat = true;
5988 unsigned NumNonConsts = 0;
5989 unsigned NumConsts = 0;
5990 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5991 SDValue In = Op.getOperand(idx);
5992 if (In.getOpcode() == ISD::UNDEF)
5994 if (!isa<ConstantSDNode>(In)) {
5995 AllContants = false;
6001 if (cast<ConstantSDNode>(In)->getZExtValue())
6002 Immediate |= (1ULL << idx);
6004 if (In != Op.getOperand(0))
6009 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6010 DAG.getConstant(Immediate, MVT::i16));
6011 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6012 DAG.getIntPtrConstant(0));
6015 if (NumNonConsts == 1 && NonConstIdx != 0) {
6018 SDValue VecAsImm = DAG.getConstant(Immediate,
6019 MVT::getIntegerVT(VT.getSizeInBits()));
6020 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6023 DstVec = DAG.getUNDEF(VT);
6024 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6025 Op.getOperand(NonConstIdx),
6026 DAG.getIntPtrConstant(NonConstIdx));
6028 if (!IsSplat && (NonConstIdx != 0))
6029 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6030 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6033 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6034 DAG.getConstant(-1, SelectVT),
6035 DAG.getConstant(0, SelectVT));
6037 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6038 DAG.getConstant((Immediate | 1), SelectVT),
6039 DAG.getConstant(Immediate, SelectVT));
6040 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6044 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6047 MVT VT = Op.getSimpleValueType();
6048 MVT ExtVT = VT.getVectorElementType();
6049 unsigned NumElems = Op.getNumOperands();
6051 // Generate vectors for predicate vectors.
6052 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6053 return LowerBUILD_VECTORvXi1(Op, DAG);
6055 // Vectors containing all zeros can be matched by pxor and xorps later
6056 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6057 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6058 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6059 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6062 return getZeroVector(VT, Subtarget, DAG, dl);
6065 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6066 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6067 // vpcmpeqd on 256-bit vectors.
6068 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6069 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6072 if (!VT.is512BitVector())
6073 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6076 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6077 if (Broadcast.getNode())
6080 unsigned EVTBits = ExtVT.getSizeInBits();
6082 unsigned NumZero = 0;
6083 unsigned NumNonZero = 0;
6084 unsigned NonZeros = 0;
6085 bool IsAllConstants = true;
6086 SmallSet<SDValue, 8> Values;
6087 for (unsigned i = 0; i < NumElems; ++i) {
6088 SDValue Elt = Op.getOperand(i);
6089 if (Elt.getOpcode() == ISD::UNDEF)
6092 if (Elt.getOpcode() != ISD::Constant &&
6093 Elt.getOpcode() != ISD::ConstantFP)
6094 IsAllConstants = false;
6095 if (X86::isZeroNode(Elt))
6098 NonZeros |= (1 << i);
6103 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6104 if (NumNonZero == 0)
6105 return DAG.getUNDEF(VT);
6107 // Special case for single non-zero, non-undef, element.
6108 if (NumNonZero == 1) {
6109 unsigned Idx = countTrailingZeros(NonZeros);
6110 SDValue Item = Op.getOperand(Idx);
6112 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6113 // the value are obviously zero, truncate the value to i32 and do the
6114 // insertion that way. Only do this if the value is non-constant or if the
6115 // value is a constant being inserted into element 0. It is cheaper to do
6116 // a constant pool load than it is to do a movd + shuffle.
6117 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6118 (!IsAllConstants || Idx == 0)) {
6119 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6121 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6122 EVT VecVT = MVT::v4i32;
6123 unsigned VecElts = 4;
6125 // Truncate the value (which may itself be a constant) to i32, and
6126 // convert it to a vector with movd (S2V+shuffle to zero extend).
6127 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6128 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6129 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6131 // Now we have our 32-bit value zero extended in the low element of
6132 // a vector. If Idx != 0, swizzle it into place.
6134 SmallVector<int, 4> Mask;
6135 Mask.push_back(Idx);
6136 for (unsigned i = 1; i != VecElts; ++i)
6138 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6141 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6145 // If we have a constant or non-constant insertion into the low element of
6146 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6147 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6148 // depending on what the source datatype is.
6151 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6153 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6154 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6155 if (VT.is256BitVector() || VT.is512BitVector()) {
6156 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6157 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6158 Item, DAG.getIntPtrConstant(0));
6160 assert(VT.is128BitVector() && "Expected an SSE value type!");
6161 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6162 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6163 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6166 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6167 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6168 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6169 if (VT.is256BitVector()) {
6170 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6171 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6173 assert(VT.is128BitVector() && "Expected an SSE value type!");
6174 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6176 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6180 // Is it a vector logical left shift?
6181 if (NumElems == 2 && Idx == 1 &&
6182 X86::isZeroNode(Op.getOperand(0)) &&
6183 !X86::isZeroNode(Op.getOperand(1))) {
6184 unsigned NumBits = VT.getSizeInBits();
6185 return getVShift(true, VT,
6186 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6187 VT, Op.getOperand(1)),
6188 NumBits/2, DAG, *this, dl);
6191 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6194 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6195 // is a non-constant being inserted into an element other than the low one,
6196 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6197 // movd/movss) to move this into the low element, then shuffle it into
6199 if (EVTBits == 32) {
6200 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6202 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6203 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6204 SmallVector<int, 8> MaskVec;
6205 for (unsigned i = 0; i != NumElems; ++i)
6206 MaskVec.push_back(i == Idx ? 0 : 1);
6207 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6211 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6212 if (Values.size() == 1) {
6213 if (EVTBits == 32) {
6214 // Instead of a shuffle like this:
6215 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6216 // Check if it's possible to issue this instead.
6217 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6218 unsigned Idx = countTrailingZeros(NonZeros);
6219 SDValue Item = Op.getOperand(Idx);
6220 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6221 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6226 // A vector full of immediates; various special cases are already
6227 // handled, so this is best done with a single constant-pool load.
6231 // For AVX-length vectors, build the individual 128-bit pieces and use
6232 // shuffles to put them in place.
6233 if (VT.is256BitVector() || VT.is512BitVector()) {
6234 SmallVector<SDValue, 64> V;
6235 for (unsigned i = 0; i != NumElems; ++i)
6236 V.push_back(Op.getOperand(i));
6238 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6240 // Build both the lower and upper subvector.
6241 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6242 makeArrayRef(&V[0], NumElems/2));
6243 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6244 makeArrayRef(&V[NumElems / 2], NumElems/2));
6246 // Recreate the wider vector with the lower and upper part.
6247 if (VT.is256BitVector())
6248 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6249 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6252 // Let legalizer expand 2-wide build_vectors.
6253 if (EVTBits == 64) {
6254 if (NumNonZero == 1) {
6255 // One half is zero or undef.
6256 unsigned Idx = countTrailingZeros(NonZeros);
6257 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6258 Op.getOperand(Idx));
6259 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6264 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6265 if (EVTBits == 8 && NumElems == 16) {
6266 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6268 if (V.getNode()) return V;
6271 if (EVTBits == 16 && NumElems == 8) {
6272 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6274 if (V.getNode()) return V;
6277 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6278 if (EVTBits == 32 && NumElems == 4) {
6279 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6280 NumZero, DAG, Subtarget, *this);
6285 // If element VT is == 32 bits, turn it into a number of shuffles.
6286 SmallVector<SDValue, 8> V(NumElems);
6287 if (NumElems == 4 && NumZero > 0) {
6288 for (unsigned i = 0; i < 4; ++i) {
6289 bool isZero = !(NonZeros & (1 << i));
6291 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6293 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6296 for (unsigned i = 0; i < 2; ++i) {
6297 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6300 V[i] = V[i*2]; // Must be a zero vector.
6303 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6306 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6309 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6314 bool Reverse1 = (NonZeros & 0x3) == 2;
6315 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6319 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6320 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6322 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6325 if (Values.size() > 1 && VT.is128BitVector()) {
6326 // Check for a build vector of consecutive loads.
6327 for (unsigned i = 0; i < NumElems; ++i)
6328 V[i] = Op.getOperand(i);
6330 // Check for elements which are consecutive loads.
6331 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6335 // Check for a build vector from mostly shuffle plus few inserting.
6336 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6340 // For SSE 4.1, use insertps to put the high elements into the low element.
6341 if (getSubtarget()->hasSSE41()) {
6343 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6344 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6346 Result = DAG.getUNDEF(VT);
6348 for (unsigned i = 1; i < NumElems; ++i) {
6349 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6350 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6351 Op.getOperand(i), DAG.getIntPtrConstant(i));
6356 // Otherwise, expand into a number of unpckl*, start by extending each of
6357 // our (non-undef) elements to the full vector width with the element in the
6358 // bottom slot of the vector (which generates no code for SSE).
6359 for (unsigned i = 0; i < NumElems; ++i) {
6360 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6361 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6363 V[i] = DAG.getUNDEF(VT);
6366 // Next, we iteratively mix elements, e.g. for v4f32:
6367 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6368 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6369 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6370 unsigned EltStride = NumElems >> 1;
6371 while (EltStride != 0) {
6372 for (unsigned i = 0; i < EltStride; ++i) {
6373 // If V[i+EltStride] is undef and this is the first round of mixing,
6374 // then it is safe to just drop this shuffle: V[i] is already in the
6375 // right place, the one element (since it's the first round) being
6376 // inserted as undef can be dropped. This isn't safe for successive
6377 // rounds because they will permute elements within both vectors.
6378 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6379 EltStride == NumElems/2)
6382 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6391 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6392 // to create 256-bit vectors from two other 128-bit ones.
6393 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6395 MVT ResVT = Op.getSimpleValueType();
6397 assert((ResVT.is256BitVector() ||
6398 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6400 SDValue V1 = Op.getOperand(0);
6401 SDValue V2 = Op.getOperand(1);
6402 unsigned NumElems = ResVT.getVectorNumElements();
6403 if(ResVT.is256BitVector())
6404 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6406 if (Op.getNumOperands() == 4) {
6407 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6408 ResVT.getVectorNumElements()/2);
6409 SDValue V3 = Op.getOperand(2);
6410 SDValue V4 = Op.getOperand(3);
6411 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6412 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6414 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6417 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6418 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6419 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6420 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6421 Op.getNumOperands() == 4)));
6423 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6424 // from two other 128-bit ones.
6426 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6427 return LowerAVXCONCAT_VECTORS(Op, DAG);
6430 // Try to lower a shuffle node into a simple blend instruction.
6432 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6433 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6434 SDValue V1 = SVOp->getOperand(0);
6435 SDValue V2 = SVOp->getOperand(1);
6437 MVT VT = SVOp->getSimpleValueType(0);
6438 MVT EltVT = VT.getVectorElementType();
6439 unsigned NumElems = VT.getVectorNumElements();
6441 // There is no blend with immediate in AVX-512.
6442 if (VT.is512BitVector())
6445 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6447 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6450 // Check the mask for BLEND and build the value.
6451 unsigned MaskValue = 0;
6452 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6453 unsigned NumLanes = (NumElems-1)/8 + 1;
6454 unsigned NumElemsInLane = NumElems / NumLanes;
6456 // Blend for v16i16 should be symetric for the both lanes.
6457 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6459 int SndLaneEltIdx = (NumLanes == 2) ?
6460 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6461 int EltIdx = SVOp->getMaskElt(i);
6463 if ((EltIdx < 0 || EltIdx == (int)i) &&
6464 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6467 if (((unsigned)EltIdx == (i + NumElems)) &&
6468 (SndLaneEltIdx < 0 ||
6469 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6470 MaskValue |= (1<<i);
6475 // Convert i32 vectors to floating point if it is not AVX2.
6476 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6478 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6479 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6481 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6482 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6485 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6486 DAG.getConstant(MaskValue, MVT::i32));
6487 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6490 /// In vector type \p VT, return true if the element at index \p InputIdx
6491 /// falls on a different 128-bit lane than \p OutputIdx.
6492 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6493 unsigned OutputIdx) {
6494 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6495 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6498 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6499 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6500 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6501 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6503 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6504 SelectionDAG &DAG) {
6505 MVT VT = V1.getSimpleValueType();
6506 assert(VT.is128BitVector() || VT.is256BitVector());
6508 MVT EltVT = VT.getVectorElementType();
6509 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6510 unsigned NumElts = VT.getVectorNumElements();
6512 SmallVector<SDValue, 32> PshufbMask;
6513 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6514 int InputIdx = MaskVals[OutputIdx];
6515 unsigned InputByteIdx;
6517 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6518 InputByteIdx = 0x80;
6520 // Cross lane is not allowed.
6521 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6523 InputByteIdx = InputIdx * EltSizeInBytes;
6524 // Index is an byte offset within the 128-bit lane.
6525 InputByteIdx &= 0xf;
6528 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6529 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6530 if (InputByteIdx != 0x80)
6535 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6537 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6538 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6539 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6542 // v8i16 shuffles - Prefer shuffles in the following order:
6543 // 1. [all] pshuflw, pshufhw, optional move
6544 // 2. [ssse3] 1 x pshufb
6545 // 3. [ssse3] 2 x pshufb + 1 x por
6546 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6548 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6549 SelectionDAG &DAG) {
6550 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6551 SDValue V1 = SVOp->getOperand(0);
6552 SDValue V2 = SVOp->getOperand(1);
6554 SmallVector<int, 8> MaskVals;
6556 // Determine if more than 1 of the words in each of the low and high quadwords
6557 // of the result come from the same quadword of one of the two inputs. Undef
6558 // mask values count as coming from any quadword, for better codegen.
6560 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6561 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6562 unsigned LoQuad[] = { 0, 0, 0, 0 };
6563 unsigned HiQuad[] = { 0, 0, 0, 0 };
6564 // Indices of quads used.
6565 std::bitset<4> InputQuads;
6566 for (unsigned i = 0; i < 8; ++i) {
6567 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6568 int EltIdx = SVOp->getMaskElt(i);
6569 MaskVals.push_back(EltIdx);
6578 InputQuads.set(EltIdx / 4);
6581 int BestLoQuad = -1;
6582 unsigned MaxQuad = 1;
6583 for (unsigned i = 0; i < 4; ++i) {
6584 if (LoQuad[i] > MaxQuad) {
6586 MaxQuad = LoQuad[i];
6590 int BestHiQuad = -1;
6592 for (unsigned i = 0; i < 4; ++i) {
6593 if (HiQuad[i] > MaxQuad) {
6595 MaxQuad = HiQuad[i];
6599 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6600 // of the two input vectors, shuffle them into one input vector so only a
6601 // single pshufb instruction is necessary. If there are more than 2 input
6602 // quads, disable the next transformation since it does not help SSSE3.
6603 bool V1Used = InputQuads[0] || InputQuads[1];
6604 bool V2Used = InputQuads[2] || InputQuads[3];
6605 if (Subtarget->hasSSSE3()) {
6606 if (InputQuads.count() == 2 && V1Used && V2Used) {
6607 BestLoQuad = InputQuads[0] ? 0 : 1;
6608 BestHiQuad = InputQuads[2] ? 2 : 3;
6610 if (InputQuads.count() > 2) {
6616 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6617 // the shuffle mask. If a quad is scored as -1, that means that it contains
6618 // words from all 4 input quadwords.
6620 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6622 BestLoQuad < 0 ? 0 : BestLoQuad,
6623 BestHiQuad < 0 ? 1 : BestHiQuad
6625 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6626 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6627 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6628 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6630 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6631 // source words for the shuffle, to aid later transformations.
6632 bool AllWordsInNewV = true;
6633 bool InOrder[2] = { true, true };
6634 for (unsigned i = 0; i != 8; ++i) {
6635 int idx = MaskVals[i];
6637 InOrder[i/4] = false;
6638 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6640 AllWordsInNewV = false;
6644 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6645 if (AllWordsInNewV) {
6646 for (int i = 0; i != 8; ++i) {
6647 int idx = MaskVals[i];
6650 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6651 if ((idx != i) && idx < 4)
6653 if ((idx != i) && idx > 3)
6662 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6663 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6664 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6665 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6666 unsigned TargetMask = 0;
6667 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6668 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6669 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6670 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6671 getShufflePSHUFLWImmediate(SVOp);
6672 V1 = NewV.getOperand(0);
6673 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6677 // Promote splats to a larger type which usually leads to more efficient code.
6678 // FIXME: Is this true if pshufb is available?
6679 if (SVOp->isSplat())
6680 return PromoteSplat(SVOp, DAG);
6682 // If we have SSSE3, and all words of the result are from 1 input vector,
6683 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6684 // is present, fall back to case 4.
6685 if (Subtarget->hasSSSE3()) {
6686 SmallVector<SDValue,16> pshufbMask;
6688 // If we have elements from both input vectors, set the high bit of the
6689 // shuffle mask element to zero out elements that come from V2 in the V1
6690 // mask, and elements that come from V1 in the V2 mask, so that the two
6691 // results can be OR'd together.
6692 bool TwoInputs = V1Used && V2Used;
6693 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6695 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6697 // Calculate the shuffle mask for the second input, shuffle it, and
6698 // OR it with the first shuffled input.
6699 CommuteVectorShuffleMask(MaskVals, 8);
6700 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6701 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6702 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6705 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6706 // and update MaskVals with new element order.
6707 std::bitset<8> InOrder;
6708 if (BestLoQuad >= 0) {
6709 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6710 for (int i = 0; i != 4; ++i) {
6711 int idx = MaskVals[i];
6714 } else if ((idx / 4) == BestLoQuad) {
6719 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6722 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6723 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6724 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6726 getShufflePSHUFLWImmediate(SVOp), DAG);
6730 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6731 // and update MaskVals with the new element order.
6732 if (BestHiQuad >= 0) {
6733 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6734 for (unsigned i = 4; i != 8; ++i) {
6735 int idx = MaskVals[i];
6738 } else if ((idx / 4) == BestHiQuad) {
6739 MaskV[i] = (idx & 3) + 4;
6743 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6746 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6747 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6748 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6750 getShufflePSHUFHWImmediate(SVOp), DAG);
6754 // In case BestHi & BestLo were both -1, which means each quadword has a word
6755 // from each of the four input quadwords, calculate the InOrder bitvector now
6756 // before falling through to the insert/extract cleanup.
6757 if (BestLoQuad == -1 && BestHiQuad == -1) {
6759 for (int i = 0; i != 8; ++i)
6760 if (MaskVals[i] < 0 || MaskVals[i] == i)
6764 // The other elements are put in the right place using pextrw and pinsrw.
6765 for (unsigned i = 0; i != 8; ++i) {
6768 int EltIdx = MaskVals[i];
6771 SDValue ExtOp = (EltIdx < 8) ?
6772 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6773 DAG.getIntPtrConstant(EltIdx)) :
6774 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6775 DAG.getIntPtrConstant(EltIdx - 8));
6776 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6777 DAG.getIntPtrConstant(i));
6782 /// \brief v16i16 shuffles
6784 /// FIXME: We only support generation of a single pshufb currently. We can
6785 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6786 /// well (e.g 2 x pshufb + 1 x por).
6788 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6789 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6790 SDValue V1 = SVOp->getOperand(0);
6791 SDValue V2 = SVOp->getOperand(1);
6794 if (V2.getOpcode() != ISD::UNDEF)
6797 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6798 return getPSHUFB(MaskVals, V1, dl, DAG);
6801 // v16i8 shuffles - Prefer shuffles in the following order:
6802 // 1. [ssse3] 1 x pshufb
6803 // 2. [ssse3] 2 x pshufb + 1 x por
6804 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6805 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6806 const X86Subtarget* Subtarget,
6807 SelectionDAG &DAG) {
6808 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6809 SDValue V1 = SVOp->getOperand(0);
6810 SDValue V2 = SVOp->getOperand(1);
6812 ArrayRef<int> MaskVals = SVOp->getMask();
6814 // Promote splats to a larger type which usually leads to more efficient code.
6815 // FIXME: Is this true if pshufb is available?
6816 if (SVOp->isSplat())
6817 return PromoteSplat(SVOp, DAG);
6819 // If we have SSSE3, case 1 is generated when all result bytes come from
6820 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6821 // present, fall back to case 3.
6823 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6824 if (Subtarget->hasSSSE3()) {
6825 SmallVector<SDValue,16> pshufbMask;
6827 // If all result elements are from one input vector, then only translate
6828 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6830 // Otherwise, we have elements from both input vectors, and must zero out
6831 // elements that come from V2 in the first mask, and V1 in the second mask
6832 // so that we can OR them together.
6833 for (unsigned i = 0; i != 16; ++i) {
6834 int EltIdx = MaskVals[i];
6835 if (EltIdx < 0 || EltIdx >= 16)
6837 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6839 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6840 DAG.getNode(ISD::BUILD_VECTOR, dl,
6841 MVT::v16i8, pshufbMask));
6843 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6844 // the 2nd operand if it's undefined or zero.
6845 if (V2.getOpcode() == ISD::UNDEF ||
6846 ISD::isBuildVectorAllZeros(V2.getNode()))
6849 // Calculate the shuffle mask for the second input, shuffle it, and
6850 // OR it with the first shuffled input.
6852 for (unsigned i = 0; i != 16; ++i) {
6853 int EltIdx = MaskVals[i];
6854 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6855 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6857 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6858 DAG.getNode(ISD::BUILD_VECTOR, dl,
6859 MVT::v16i8, pshufbMask));
6860 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6863 // No SSSE3 - Calculate in place words and then fix all out of place words
6864 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6865 // the 16 different words that comprise the two doublequadword input vectors.
6866 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6867 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6869 for (int i = 0; i != 8; ++i) {
6870 int Elt0 = MaskVals[i*2];
6871 int Elt1 = MaskVals[i*2+1];
6873 // This word of the result is all undef, skip it.
6874 if (Elt0 < 0 && Elt1 < 0)
6877 // This word of the result is already in the correct place, skip it.
6878 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6881 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6882 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6885 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6886 // using a single extract together, load it and store it.
6887 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6888 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6889 DAG.getIntPtrConstant(Elt1 / 2));
6890 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6891 DAG.getIntPtrConstant(i));
6895 // If Elt1 is defined, extract it from the appropriate source. If the
6896 // source byte is not also odd, shift the extracted word left 8 bits
6897 // otherwise clear the bottom 8 bits if we need to do an or.
6899 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6900 DAG.getIntPtrConstant(Elt1 / 2));
6901 if ((Elt1 & 1) == 0)
6902 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6904 TLI.getShiftAmountTy(InsElt.getValueType())));
6906 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6907 DAG.getConstant(0xFF00, MVT::i16));
6909 // If Elt0 is defined, extract it from the appropriate source. If the
6910 // source byte is not also even, shift the extracted word right 8 bits. If
6911 // Elt1 was also defined, OR the extracted values together before
6912 // inserting them in the result.
6914 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6915 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6916 if ((Elt0 & 1) != 0)
6917 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6919 TLI.getShiftAmountTy(InsElt0.getValueType())));
6921 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6922 DAG.getConstant(0x00FF, MVT::i16));
6923 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6926 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6927 DAG.getIntPtrConstant(i));
6929 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6932 // v32i8 shuffles - Translate to VPSHUFB if possible.
6934 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6935 const X86Subtarget *Subtarget,
6936 SelectionDAG &DAG) {
6937 MVT VT = SVOp->getSimpleValueType(0);
6938 SDValue V1 = SVOp->getOperand(0);
6939 SDValue V2 = SVOp->getOperand(1);
6941 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6943 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6944 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6945 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6947 // VPSHUFB may be generated if
6948 // (1) one of input vector is undefined or zeroinitializer.
6949 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6950 // And (2) the mask indexes don't cross the 128-bit lane.
6951 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6952 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6955 if (V1IsAllZero && !V2IsAllZero) {
6956 CommuteVectorShuffleMask(MaskVals, 32);
6959 return getPSHUFB(MaskVals, V1, dl, DAG);
6962 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6963 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6964 /// done when every pair / quad of shuffle mask elements point to elements in
6965 /// the right sequence. e.g.
6966 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6968 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6969 SelectionDAG &DAG) {
6970 MVT VT = SVOp->getSimpleValueType(0);
6972 unsigned NumElems = VT.getVectorNumElements();
6975 switch (VT.SimpleTy) {
6976 default: llvm_unreachable("Unexpected!");
6979 return SDValue(SVOp, 0);
6980 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6981 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6982 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6983 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6984 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6985 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6988 SmallVector<int, 8> MaskVec;
6989 for (unsigned i = 0; i != NumElems; i += Scale) {
6991 for (unsigned j = 0; j != Scale; ++j) {
6992 int EltIdx = SVOp->getMaskElt(i+j);
6996 StartIdx = (EltIdx / Scale);
6997 if (EltIdx != (int)(StartIdx*Scale + j))
7000 MaskVec.push_back(StartIdx);
7003 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7004 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7005 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7008 /// getVZextMovL - Return a zero-extending vector move low node.
7010 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7011 SDValue SrcOp, SelectionDAG &DAG,
7012 const X86Subtarget *Subtarget, SDLoc dl) {
7013 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7014 LoadSDNode *LD = nullptr;
7015 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7016 LD = dyn_cast<LoadSDNode>(SrcOp);
7018 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7020 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7021 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7022 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7023 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7024 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7026 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7027 return DAG.getNode(ISD::BITCAST, dl, VT,
7028 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7029 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7037 return DAG.getNode(ISD::BITCAST, dl, VT,
7038 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7039 DAG.getNode(ISD::BITCAST, dl,
7043 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7044 /// which could not be matched by any known target speficic shuffle
7046 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7048 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7049 if (NewOp.getNode())
7052 MVT VT = SVOp->getSimpleValueType(0);
7054 unsigned NumElems = VT.getVectorNumElements();
7055 unsigned NumLaneElems = NumElems / 2;
7058 MVT EltVT = VT.getVectorElementType();
7059 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7062 SmallVector<int, 16> Mask;
7063 for (unsigned l = 0; l < 2; ++l) {
7064 // Build a shuffle mask for the output, discovering on the fly which
7065 // input vectors to use as shuffle operands (recorded in InputUsed).
7066 // If building a suitable shuffle vector proves too hard, then bail
7067 // out with UseBuildVector set.
7068 bool UseBuildVector = false;
7069 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7070 unsigned LaneStart = l * NumLaneElems;
7071 for (unsigned i = 0; i != NumLaneElems; ++i) {
7072 // The mask element. This indexes into the input.
7073 int Idx = SVOp->getMaskElt(i+LaneStart);
7075 // the mask element does not index into any input vector.
7080 // The input vector this mask element indexes into.
7081 int Input = Idx / NumLaneElems;
7083 // Turn the index into an offset from the start of the input vector.
7084 Idx -= Input * NumLaneElems;
7086 // Find or create a shuffle vector operand to hold this input.
7088 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7089 if (InputUsed[OpNo] == Input)
7090 // This input vector is already an operand.
7092 if (InputUsed[OpNo] < 0) {
7093 // Create a new operand for this input vector.
7094 InputUsed[OpNo] = Input;
7099 if (OpNo >= array_lengthof(InputUsed)) {
7100 // More than two input vectors used! Give up on trying to create a
7101 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7102 UseBuildVector = true;
7106 // Add the mask index for the new shuffle vector.
7107 Mask.push_back(Idx + OpNo * NumLaneElems);
7110 if (UseBuildVector) {
7111 SmallVector<SDValue, 16> SVOps;
7112 for (unsigned i = 0; i != NumLaneElems; ++i) {
7113 // The mask element. This indexes into the input.
7114 int Idx = SVOp->getMaskElt(i+LaneStart);
7116 SVOps.push_back(DAG.getUNDEF(EltVT));
7120 // The input vector this mask element indexes into.
7121 int Input = Idx / NumElems;
7123 // Turn the index into an offset from the start of the input vector.
7124 Idx -= Input * NumElems;
7126 // Extract the vector element by hand.
7127 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7128 SVOp->getOperand(Input),
7129 DAG.getIntPtrConstant(Idx)));
7132 // Construct the output using a BUILD_VECTOR.
7133 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7134 } else if (InputUsed[0] < 0) {
7135 // No input vectors were used! The result is undefined.
7136 Output[l] = DAG.getUNDEF(NVT);
7138 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7139 (InputUsed[0] % 2) * NumLaneElems,
7141 // If only one input was used, use an undefined vector for the other.
7142 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7143 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7144 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7145 // At least one input vector was used. Create a new shuffle vector.
7146 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7152 // Concatenate the result back
7153 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7156 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7157 /// 4 elements, and match them with several different shuffle types.
7159 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7160 SDValue V1 = SVOp->getOperand(0);
7161 SDValue V2 = SVOp->getOperand(1);
7163 MVT VT = SVOp->getSimpleValueType(0);
7165 assert(VT.is128BitVector() && "Unsupported vector size");
7167 std::pair<int, int> Locs[4];
7168 int Mask1[] = { -1, -1, -1, -1 };
7169 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7173 for (unsigned i = 0; i != 4; ++i) {
7174 int Idx = PermMask[i];
7176 Locs[i] = std::make_pair(-1, -1);
7178 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7180 Locs[i] = std::make_pair(0, NumLo);
7184 Locs[i] = std::make_pair(1, NumHi);
7186 Mask1[2+NumHi] = Idx;
7192 if (NumLo <= 2 && NumHi <= 2) {
7193 // If no more than two elements come from either vector. This can be
7194 // implemented with two shuffles. First shuffle gather the elements.
7195 // The second shuffle, which takes the first shuffle as both of its
7196 // vector operands, put the elements into the right order.
7197 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7199 int Mask2[] = { -1, -1, -1, -1 };
7201 for (unsigned i = 0; i != 4; ++i)
7202 if (Locs[i].first != -1) {
7203 unsigned Idx = (i < 2) ? 0 : 4;
7204 Idx += Locs[i].first * 2 + Locs[i].second;
7208 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7211 if (NumLo == 3 || NumHi == 3) {
7212 // Otherwise, we must have three elements from one vector, call it X, and
7213 // one element from the other, call it Y. First, use a shufps to build an
7214 // intermediate vector with the one element from Y and the element from X
7215 // that will be in the same half in the final destination (the indexes don't
7216 // matter). Then, use a shufps to build the final vector, taking the half
7217 // containing the element from Y from the intermediate, and the other half
7220 // Normalize it so the 3 elements come from V1.
7221 CommuteVectorShuffleMask(PermMask, 4);
7225 // Find the element from V2.
7227 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7228 int Val = PermMask[HiIndex];
7235 Mask1[0] = PermMask[HiIndex];
7237 Mask1[2] = PermMask[HiIndex^1];
7239 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7242 Mask1[0] = PermMask[0];
7243 Mask1[1] = PermMask[1];
7244 Mask1[2] = HiIndex & 1 ? 6 : 4;
7245 Mask1[3] = HiIndex & 1 ? 4 : 6;
7246 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7249 Mask1[0] = HiIndex & 1 ? 2 : 0;
7250 Mask1[1] = HiIndex & 1 ? 0 : 2;
7251 Mask1[2] = PermMask[2];
7252 Mask1[3] = PermMask[3];
7257 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7260 // Break it into (shuffle shuffle_hi, shuffle_lo).
7261 int LoMask[] = { -1, -1, -1, -1 };
7262 int HiMask[] = { -1, -1, -1, -1 };
7264 int *MaskPtr = LoMask;
7265 unsigned MaskIdx = 0;
7268 for (unsigned i = 0; i != 4; ++i) {
7275 int Idx = PermMask[i];
7277 Locs[i] = std::make_pair(-1, -1);
7278 } else if (Idx < 4) {
7279 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7280 MaskPtr[LoIdx] = Idx;
7283 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7284 MaskPtr[HiIdx] = Idx;
7289 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7290 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7291 int MaskOps[] = { -1, -1, -1, -1 };
7292 for (unsigned i = 0; i != 4; ++i)
7293 if (Locs[i].first != -1)
7294 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7295 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7298 static bool MayFoldVectorLoad(SDValue V) {
7299 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7300 V = V.getOperand(0);
7302 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7303 V = V.getOperand(0);
7304 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7305 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7306 // BUILD_VECTOR (load), undef
7307 V = V.getOperand(0);
7309 return MayFoldLoad(V);
7313 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7314 MVT VT = Op.getSimpleValueType();
7316 // Canonizalize to v2f64.
7317 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7318 return DAG.getNode(ISD::BITCAST, dl, VT,
7319 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7324 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7326 SDValue V1 = Op.getOperand(0);
7327 SDValue V2 = Op.getOperand(1);
7328 MVT VT = Op.getSimpleValueType();
7330 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7332 if (HasSSE2 && VT == MVT::v2f64)
7333 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7335 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7336 return DAG.getNode(ISD::BITCAST, dl, VT,
7337 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7338 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7339 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7343 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7344 SDValue V1 = Op.getOperand(0);
7345 SDValue V2 = Op.getOperand(1);
7346 MVT VT = Op.getSimpleValueType();
7348 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7349 "unsupported shuffle type");
7351 if (V2.getOpcode() == ISD::UNDEF)
7355 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7359 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7360 SDValue V1 = Op.getOperand(0);
7361 SDValue V2 = Op.getOperand(1);
7362 MVT VT = Op.getSimpleValueType();
7363 unsigned NumElems = VT.getVectorNumElements();
7365 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7366 // operand of these instructions is only memory, so check if there's a
7367 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7369 bool CanFoldLoad = false;
7371 // Trivial case, when V2 comes from a load.
7372 if (MayFoldVectorLoad(V2))
7375 // When V1 is a load, it can be folded later into a store in isel, example:
7376 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7378 // (MOVLPSmr addr:$src1, VR128:$src2)
7379 // So, recognize this potential and also use MOVLPS or MOVLPD
7380 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7383 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7385 if (HasSSE2 && NumElems == 2)
7386 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7389 // If we don't care about the second element, proceed to use movss.
7390 if (SVOp->getMaskElt(1) != -1)
7391 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7394 // movl and movlp will both match v2i64, but v2i64 is never matched by
7395 // movl earlier because we make it strict to avoid messing with the movlp load
7396 // folding logic (see the code above getMOVLP call). Match it here then,
7397 // this is horrible, but will stay like this until we move all shuffle
7398 // matching to x86 specific nodes. Note that for the 1st condition all
7399 // types are matched with movsd.
7401 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7402 // as to remove this logic from here, as much as possible
7403 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7404 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7405 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7408 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7410 // Invert the operand order and use SHUFPS to match it.
7411 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7412 getShuffleSHUFImmediate(SVOp), DAG);
7415 // It is only safe to call this function if isINSERTPSMask is true for
7416 // this shufflevector mask.
7417 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7418 SelectionDAG &DAG) {
7419 // Generate an insertps instruction when inserting an f32 from memory onto a
7420 // v4f32 or when copying a member from one v4f32 to another.
7421 // We also use it for transferring i32 from one register to another,
7422 // since it simply copies the same bits.
7423 // If we're transferring an i32 from memory to a specific element in a
7424 // register, we output a generic DAG that will match the PINSRD
7426 // TODO: Optimize for AVX cases too (VINSERTPS)
7427 MVT VT = SVOp->getSimpleValueType(0);
7428 MVT EVT = VT.getVectorElementType();
7429 SDValue V1 = SVOp->getOperand(0);
7430 SDValue V2 = SVOp->getOperand(1);
7431 auto Mask = SVOp->getMask();
7432 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7433 "unsupported vector type for insertps/pinsrd");
7435 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7436 [](const int &i) { return i < 4; });
7444 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7445 [](const int &i) { return i < 4; }) -
7450 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7451 [](const int &i) { return i >= 4; }) -
7455 if (MayFoldLoad(From)) {
7456 // Trivial case, when From comes from a load and is only used by the
7457 // shuffle. Make it use insertps from the vector that we need from that
7459 SDValue Addr = From.getOperand(1);
7461 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7462 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7463 Addr.getSimpleValueType()));
7465 LoadSDNode *Load = cast<LoadSDNode>(From);
7467 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7468 DAG.getMachineFunction().getMachineMemOperand(
7469 Load->getMemOperand(), 0, EVT.getStoreSize()));
7471 if (EVT == MVT::f32) {
7472 // Create this as a scalar to vector to match the instruction pattern.
7473 SDValue LoadScalarToVector =
7474 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7475 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7476 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7478 } else { // EVT == MVT::i32
7479 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7480 // instruction, to match the PINSRD instruction, which loads an i32 to a
7481 // certain vector element.
7482 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7483 DAG.getConstant(DestIndex, MVT::i32));
7487 // Vector-element-to-vector
7488 unsigned SrcIndex = Mask[DestIndex] % 4;
7489 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7490 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7493 // Reduce a vector shuffle to zext.
7494 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7495 SelectionDAG &DAG) {
7496 // PMOVZX is only available from SSE41.
7497 if (!Subtarget->hasSSE41())
7500 MVT VT = Op.getSimpleValueType();
7502 // Only AVX2 support 256-bit vector integer extending.
7503 if (!Subtarget->hasInt256() && VT.is256BitVector())
7506 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7508 SDValue V1 = Op.getOperand(0);
7509 SDValue V2 = Op.getOperand(1);
7510 unsigned NumElems = VT.getVectorNumElements();
7512 // Extending is an unary operation and the element type of the source vector
7513 // won't be equal to or larger than i64.
7514 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7515 VT.getVectorElementType() == MVT::i64)
7518 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7519 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7520 while ((1U << Shift) < NumElems) {
7521 if (SVOp->getMaskElt(1U << Shift) == 1)
7524 // The maximal ratio is 8, i.e. from i8 to i64.
7529 // Check the shuffle mask.
7530 unsigned Mask = (1U << Shift) - 1;
7531 for (unsigned i = 0; i != NumElems; ++i) {
7532 int EltIdx = SVOp->getMaskElt(i);
7533 if ((i & Mask) != 0 && EltIdx != -1)
7535 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7539 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7540 MVT NeVT = MVT::getIntegerVT(NBits);
7541 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7543 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7546 // Simplify the operand as it's prepared to be fed into shuffle.
7547 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7548 if (V1.getOpcode() == ISD::BITCAST &&
7549 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7550 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7551 V1.getOperand(0).getOperand(0)
7552 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7553 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7554 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7555 ConstantSDNode *CIdx =
7556 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7557 // If it's foldable, i.e. normal load with single use, we will let code
7558 // selection to fold it. Otherwise, we will short the conversion sequence.
7559 if (CIdx && CIdx->getZExtValue() == 0 &&
7560 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7561 MVT FullVT = V.getSimpleValueType();
7562 MVT V1VT = V1.getSimpleValueType();
7563 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7564 // The "ext_vec_elt" node is wider than the result node.
7565 // In this case we should extract subvector from V.
7566 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7567 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7568 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7569 FullVT.getVectorNumElements()/Ratio);
7570 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7571 DAG.getIntPtrConstant(0));
7573 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7577 return DAG.getNode(ISD::BITCAST, DL, VT,
7578 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7581 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7582 SelectionDAG &DAG) {
7583 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7584 MVT VT = Op.getSimpleValueType();
7586 SDValue V1 = Op.getOperand(0);
7587 SDValue V2 = Op.getOperand(1);
7589 if (isZeroShuffle(SVOp))
7590 return getZeroVector(VT, Subtarget, DAG, dl);
7592 // Handle splat operations
7593 if (SVOp->isSplat()) {
7594 // Use vbroadcast whenever the splat comes from a foldable load
7595 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7596 if (Broadcast.getNode())
7600 // Check integer expanding shuffles.
7601 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7602 if (NewOp.getNode())
7605 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7607 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7609 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7610 if (NewOp.getNode())
7611 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7612 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7613 // FIXME: Figure out a cleaner way to do this.
7614 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7615 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7616 if (NewOp.getNode()) {
7617 MVT NewVT = NewOp.getSimpleValueType();
7618 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7619 NewVT, true, false))
7620 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7623 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7624 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7625 if (NewOp.getNode()) {
7626 MVT NewVT = NewOp.getSimpleValueType();
7627 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7628 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7637 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7638 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7639 SDValue V1 = Op.getOperand(0);
7640 SDValue V2 = Op.getOperand(1);
7641 MVT VT = Op.getSimpleValueType();
7643 unsigned NumElems = VT.getVectorNumElements();
7644 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7645 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7646 bool V1IsSplat = false;
7647 bool V2IsSplat = false;
7648 bool HasSSE2 = Subtarget->hasSSE2();
7649 bool HasFp256 = Subtarget->hasFp256();
7650 bool HasInt256 = Subtarget->hasInt256();
7651 MachineFunction &MF = DAG.getMachineFunction();
7652 bool OptForSize = MF.getFunction()->getAttributes().
7653 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7655 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7657 if (V1IsUndef && V2IsUndef)
7658 return DAG.getUNDEF(VT);
7660 // When we create a shuffle node we put the UNDEF node to second operand,
7661 // but in some cases the first operand may be transformed to UNDEF.
7662 // In this case we should just commute the node.
7664 return CommuteVectorShuffle(SVOp, DAG);
7666 // Vector shuffle lowering takes 3 steps:
7668 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7669 // narrowing and commutation of operands should be handled.
7670 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7672 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7673 // so the shuffle can be broken into other shuffles and the legalizer can
7674 // try the lowering again.
7676 // The general idea is that no vector_shuffle operation should be left to
7677 // be matched during isel, all of them must be converted to a target specific
7680 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7681 // narrowing and commutation of operands should be handled. The actual code
7682 // doesn't include all of those, work in progress...
7683 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7684 if (NewOp.getNode())
7687 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7689 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7690 // unpckh_undef). Only use pshufd if speed is more important than size.
7691 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7692 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7693 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7694 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7696 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7697 V2IsUndef && MayFoldVectorLoad(V1))
7698 return getMOVDDup(Op, dl, V1, DAG);
7700 if (isMOVHLPS_v_undef_Mask(M, VT))
7701 return getMOVHighToLow(Op, dl, DAG);
7703 // Use to match splats
7704 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7705 (VT == MVT::v2f64 || VT == MVT::v2i64))
7706 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7708 if (isPSHUFDMask(M, VT)) {
7709 // The actual implementation will match the mask in the if above and then
7710 // during isel it can match several different instructions, not only pshufd
7711 // as its name says, sad but true, emulate the behavior for now...
7712 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7713 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7715 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7717 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7718 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7720 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7721 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7724 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7728 if (isPALIGNRMask(M, VT, Subtarget))
7729 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7730 getShufflePALIGNRImmediate(SVOp),
7733 // Check if this can be converted into a logical shift.
7734 bool isLeft = false;
7737 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7738 if (isShift && ShVal.hasOneUse()) {
7739 // If the shifted value has multiple uses, it may be cheaper to use
7740 // v_set0 + movlhps or movhlps, etc.
7741 MVT EltVT = VT.getVectorElementType();
7742 ShAmt *= EltVT.getSizeInBits();
7743 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7746 if (isMOVLMask(M, VT)) {
7747 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7748 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7749 if (!isMOVLPMask(M, VT)) {
7750 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7751 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7753 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7754 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7758 // FIXME: fold these into legal mask.
7759 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7760 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7762 if (isMOVHLPSMask(M, VT))
7763 return getMOVHighToLow(Op, dl, DAG);
7765 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7766 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7768 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7769 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7771 if (isMOVLPMask(M, VT))
7772 return getMOVLP(Op, dl, DAG, HasSSE2);
7774 if (ShouldXformToMOVHLPS(M, VT) ||
7775 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7776 return CommuteVectorShuffle(SVOp, DAG);
7779 // No better options. Use a vshldq / vsrldq.
7780 MVT EltVT = VT.getVectorElementType();
7781 ShAmt *= EltVT.getSizeInBits();
7782 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7785 bool Commuted = false;
7786 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7787 // 1,1,1,1 -> v8i16 though.
7788 V1IsSplat = isSplatVector(V1.getNode());
7789 V2IsSplat = isSplatVector(V2.getNode());
7791 // Canonicalize the splat or undef, if present, to be on the RHS.
7792 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7793 CommuteVectorShuffleMask(M, NumElems);
7795 std::swap(V1IsSplat, V2IsSplat);
7799 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7800 // Shuffling low element of v1 into undef, just return v1.
7803 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7804 // the instruction selector will not match, so get a canonical MOVL with
7805 // swapped operands to undo the commute.
7806 return getMOVL(DAG, dl, VT, V2, V1);
7809 if (isUNPCKLMask(M, VT, HasInt256))
7810 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7812 if (isUNPCKHMask(M, VT, HasInt256))
7813 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7816 // Normalize mask so all entries that point to V2 points to its first
7817 // element then try to match unpck{h|l} again. If match, return a
7818 // new vector_shuffle with the corrected mask.p
7819 SmallVector<int, 8> NewMask(M.begin(), M.end());
7820 NormalizeMask(NewMask, NumElems);
7821 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7822 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7823 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7824 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7828 // Commute is back and try unpck* again.
7829 // FIXME: this seems wrong.
7830 CommuteVectorShuffleMask(M, NumElems);
7832 std::swap(V1IsSplat, V2IsSplat);
7834 if (isUNPCKLMask(M, VT, HasInt256))
7835 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7837 if (isUNPCKHMask(M, VT, HasInt256))
7838 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7841 // Normalize the node to match x86 shuffle ops if needed
7842 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7843 return CommuteVectorShuffle(SVOp, DAG);
7845 // The checks below are all present in isShuffleMaskLegal, but they are
7846 // inlined here right now to enable us to directly emit target specific
7847 // nodes, and remove one by one until they don't return Op anymore.
7849 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7850 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7851 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7852 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7855 if (isPSHUFHWMask(M, VT, HasInt256))
7856 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7857 getShufflePSHUFHWImmediate(SVOp),
7860 if (isPSHUFLWMask(M, VT, HasInt256))
7861 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7862 getShufflePSHUFLWImmediate(SVOp),
7865 if (isSHUFPMask(M, VT))
7866 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7867 getShuffleSHUFImmediate(SVOp), DAG);
7869 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7870 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7871 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7872 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7874 //===--------------------------------------------------------------------===//
7875 // Generate target specific nodes for 128 or 256-bit shuffles only
7876 // supported in the AVX instruction set.
7879 // Handle VMOVDDUPY permutations
7880 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7881 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7883 // Handle VPERMILPS/D* permutations
7884 if (isVPERMILPMask(M, VT)) {
7885 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7886 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7887 getShuffleSHUFImmediate(SVOp), DAG);
7888 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7889 getShuffleSHUFImmediate(SVOp), DAG);
7893 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7894 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7895 Idx*(NumElems/2), DAG, dl);
7897 // Handle VPERM2F128/VPERM2I128 permutations
7898 if (isVPERM2X128Mask(M, VT, HasFp256))
7899 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7900 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7902 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7903 if (BlendOp.getNode())
7906 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7907 return getINSERTPS(SVOp, dl, DAG);
7910 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7911 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7913 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7914 VT.is512BitVector()) {
7915 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7916 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7917 SmallVector<SDValue, 16> permclMask;
7918 for (unsigned i = 0; i != NumElems; ++i) {
7919 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7922 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7924 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7925 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7926 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7927 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7928 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7931 //===--------------------------------------------------------------------===//
7932 // Since no target specific shuffle was selected for this generic one,
7933 // lower it into other known shuffles. FIXME: this isn't true yet, but
7934 // this is the plan.
7937 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7938 if (VT == MVT::v8i16) {
7939 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7940 if (NewOp.getNode())
7944 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7945 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7946 if (NewOp.getNode())
7950 if (VT == MVT::v16i8) {
7951 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7952 if (NewOp.getNode())
7956 if (VT == MVT::v32i8) {
7957 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7958 if (NewOp.getNode())
7962 // Handle all 128-bit wide vectors with 4 elements, and match them with
7963 // several different shuffle types.
7964 if (NumElems == 4 && VT.is128BitVector())
7965 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7967 // Handle general 256-bit shuffles
7968 if (VT.is256BitVector())
7969 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7974 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
7975 // Some types for vselect were previously set to Expand, not Legal or
7976 // Custom. Return an empty SDValue so we fall-through to Expand, after
7977 // the Custom lowering phase.
7978 MVT VT = Op.getSimpleValueType();
7979 switch (VT.SimpleTy) {
7987 // This node is Legal.
7991 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7992 MVT VT = Op.getSimpleValueType();
7995 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7998 if (VT.getSizeInBits() == 8) {
7999 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8000 Op.getOperand(0), Op.getOperand(1));
8001 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8002 DAG.getValueType(VT));
8003 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8006 if (VT.getSizeInBits() == 16) {
8007 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8008 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8010 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8011 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8012 DAG.getNode(ISD::BITCAST, dl,
8016 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8017 Op.getOperand(0), Op.getOperand(1));
8018 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8019 DAG.getValueType(VT));
8020 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8023 if (VT == MVT::f32) {
8024 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8025 // the result back to FR32 register. It's only worth matching if the
8026 // result has a single use which is a store or a bitcast to i32. And in
8027 // the case of a store, it's not worth it if the index is a constant 0,
8028 // because a MOVSSmr can be used instead, which is smaller and faster.
8029 if (!Op.hasOneUse())
8031 SDNode *User = *Op.getNode()->use_begin();
8032 if ((User->getOpcode() != ISD::STORE ||
8033 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8034 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8035 (User->getOpcode() != ISD::BITCAST ||
8036 User->getValueType(0) != MVT::i32))
8038 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8039 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8042 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8045 if (VT == MVT::i32 || VT == MVT::i64) {
8046 // ExtractPS/pextrq works with constant index.
8047 if (isa<ConstantSDNode>(Op.getOperand(1)))
8053 /// Extract one bit from mask vector, like v16i1 or v8i1.
8054 /// AVX-512 feature.
8056 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8057 SDValue Vec = Op.getOperand(0);
8059 MVT VecVT = Vec.getSimpleValueType();
8060 SDValue Idx = Op.getOperand(1);
8061 MVT EltVT = Op.getSimpleValueType();
8063 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8065 // variable index can't be handled in mask registers,
8066 // extend vector to VR512
8067 if (!isa<ConstantSDNode>(Idx)) {
8068 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8069 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8070 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8071 ExtVT.getVectorElementType(), Ext, Idx);
8072 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8075 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8076 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8077 unsigned MaxSift = rc->getSize()*8 - 1;
8078 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8079 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8080 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8081 DAG.getConstant(MaxSift, MVT::i8));
8082 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8083 DAG.getIntPtrConstant(0));
8087 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8088 SelectionDAG &DAG) const {
8090 SDValue Vec = Op.getOperand(0);
8091 MVT VecVT = Vec.getSimpleValueType();
8092 SDValue Idx = Op.getOperand(1);
8094 if (Op.getSimpleValueType() == MVT::i1)
8095 return ExtractBitFromMaskVector(Op, DAG);
8097 if (!isa<ConstantSDNode>(Idx)) {
8098 if (VecVT.is512BitVector() ||
8099 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8100 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8103 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8104 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8105 MaskEltVT.getSizeInBits());
8107 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8108 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8109 getZeroVector(MaskVT, Subtarget, DAG, dl),
8110 Idx, DAG.getConstant(0, getPointerTy()));
8111 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8112 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8113 Perm, DAG.getConstant(0, getPointerTy()));
8118 // If this is a 256-bit vector result, first extract the 128-bit vector and
8119 // then extract the element from the 128-bit vector.
8120 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8122 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8123 // Get the 128-bit vector.
8124 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8125 MVT EltVT = VecVT.getVectorElementType();
8127 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8129 //if (IdxVal >= NumElems/2)
8130 // IdxVal -= NumElems/2;
8131 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8132 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8133 DAG.getConstant(IdxVal, MVT::i32));
8136 assert(VecVT.is128BitVector() && "Unexpected vector length");
8138 if (Subtarget->hasSSE41()) {
8139 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8144 MVT VT = Op.getSimpleValueType();
8145 // TODO: handle v16i8.
8146 if (VT.getSizeInBits() == 16) {
8147 SDValue Vec = Op.getOperand(0);
8148 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8150 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8151 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8152 DAG.getNode(ISD::BITCAST, dl,
8155 // Transform it so it match pextrw which produces a 32-bit result.
8156 MVT EltVT = MVT::i32;
8157 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8158 Op.getOperand(0), Op.getOperand(1));
8159 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8160 DAG.getValueType(VT));
8161 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8164 if (VT.getSizeInBits() == 32) {
8165 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8169 // SHUFPS the element to the lowest double word, then movss.
8170 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8171 MVT VVT = Op.getOperand(0).getSimpleValueType();
8172 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8173 DAG.getUNDEF(VVT), Mask);
8174 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8175 DAG.getIntPtrConstant(0));
8178 if (VT.getSizeInBits() == 64) {
8179 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8180 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8181 // to match extract_elt for f64.
8182 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8186 // UNPCKHPD the element to the lowest double word, then movsd.
8187 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8188 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8189 int Mask[2] = { 1, -1 };
8190 MVT VVT = Op.getOperand(0).getSimpleValueType();
8191 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8192 DAG.getUNDEF(VVT), Mask);
8193 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8194 DAG.getIntPtrConstant(0));
8200 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8201 MVT VT = Op.getSimpleValueType();
8202 MVT EltVT = VT.getVectorElementType();
8205 SDValue N0 = Op.getOperand(0);
8206 SDValue N1 = Op.getOperand(1);
8207 SDValue N2 = Op.getOperand(2);
8209 if (!VT.is128BitVector())
8212 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8213 isa<ConstantSDNode>(N2)) {
8215 if (VT == MVT::v8i16)
8216 Opc = X86ISD::PINSRW;
8217 else if (VT == MVT::v16i8)
8218 Opc = X86ISD::PINSRB;
8220 Opc = X86ISD::PINSRB;
8222 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8224 if (N1.getValueType() != MVT::i32)
8225 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8226 if (N2.getValueType() != MVT::i32)
8227 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8228 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8231 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8232 // Bits [7:6] of the constant are the source select. This will always be
8233 // zero here. The DAG Combiner may combine an extract_elt index into these
8234 // bits. For example (insert (extract, 3), 2) could be matched by putting
8235 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8236 // Bits [5:4] of the constant are the destination select. This is the
8237 // value of the incoming immediate.
8238 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8239 // combine either bitwise AND or insert of float 0.0 to set these bits.
8240 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8241 // Create this as a scalar to vector..
8242 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8243 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8246 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8247 // PINSR* works with constant index.
8253 /// Insert one bit to mask vector, like v16i1 or v8i1.
8254 /// AVX-512 feature.
8256 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8258 SDValue Vec = Op.getOperand(0);
8259 SDValue Elt = Op.getOperand(1);
8260 SDValue Idx = Op.getOperand(2);
8261 MVT VecVT = Vec.getSimpleValueType();
8263 if (!isa<ConstantSDNode>(Idx)) {
8264 // Non constant index. Extend source and destination,
8265 // insert element and then truncate the result.
8266 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8267 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8268 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8269 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8270 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8271 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8274 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8275 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8276 if (Vec.getOpcode() == ISD::UNDEF)
8277 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8278 DAG.getConstant(IdxVal, MVT::i8));
8279 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8280 unsigned MaxSift = rc->getSize()*8 - 1;
8281 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8282 DAG.getConstant(MaxSift, MVT::i8));
8283 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8284 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8285 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8288 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8289 MVT VT = Op.getSimpleValueType();
8290 MVT EltVT = VT.getVectorElementType();
8292 if (EltVT == MVT::i1)
8293 return InsertBitToMaskVector(Op, DAG);
8296 SDValue N0 = Op.getOperand(0);
8297 SDValue N1 = Op.getOperand(1);
8298 SDValue N2 = Op.getOperand(2);
8300 // If this is a 256-bit vector result, first extract the 128-bit vector,
8301 // insert the element into the extracted half and then place it back.
8302 if (VT.is256BitVector() || VT.is512BitVector()) {
8303 if (!isa<ConstantSDNode>(N2))
8306 // Get the desired 128-bit vector half.
8307 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8308 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8310 // Insert the element into the desired half.
8311 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8312 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8314 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8315 DAG.getConstant(IdxIn128, MVT::i32));
8317 // Insert the changed part back to the 256-bit vector
8318 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8321 if (Subtarget->hasSSE41())
8322 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8324 if (EltVT == MVT::i8)
8327 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8328 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8329 // as its second argument.
8330 if (N1.getValueType() != MVT::i32)
8331 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8332 if (N2.getValueType() != MVT::i32)
8333 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8334 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8339 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8341 MVT OpVT = Op.getSimpleValueType();
8343 // If this is a 256-bit vector result, first insert into a 128-bit
8344 // vector and then insert into the 256-bit vector.
8345 if (!OpVT.is128BitVector()) {
8346 // Insert into a 128-bit vector.
8347 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8348 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8349 OpVT.getVectorNumElements() / SizeFactor);
8351 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8353 // Insert the 128-bit vector.
8354 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8357 if (OpVT == MVT::v1i64 &&
8358 Op.getOperand(0).getValueType() == MVT::i64)
8359 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8361 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8362 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8363 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8364 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8367 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8368 // a simple subregister reference or explicit instructions to grab
8369 // upper bits of a vector.
8370 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8371 SelectionDAG &DAG) {
8373 SDValue In = Op.getOperand(0);
8374 SDValue Idx = Op.getOperand(1);
8375 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8376 MVT ResVT = Op.getSimpleValueType();
8377 MVT InVT = In.getSimpleValueType();
8379 if (Subtarget->hasFp256()) {
8380 if (ResVT.is128BitVector() &&
8381 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8382 isa<ConstantSDNode>(Idx)) {
8383 return Extract128BitVector(In, IdxVal, DAG, dl);
8385 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8386 isa<ConstantSDNode>(Idx)) {
8387 return Extract256BitVector(In, IdxVal, DAG, dl);
8393 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8394 // simple superregister reference or explicit instructions to insert
8395 // the upper bits of a vector.
8396 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8397 SelectionDAG &DAG) {
8398 if (Subtarget->hasFp256()) {
8399 SDLoc dl(Op.getNode());
8400 SDValue Vec = Op.getNode()->getOperand(0);
8401 SDValue SubVec = Op.getNode()->getOperand(1);
8402 SDValue Idx = Op.getNode()->getOperand(2);
8404 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8405 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8406 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8407 isa<ConstantSDNode>(Idx)) {
8408 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8409 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8412 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8413 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8414 isa<ConstantSDNode>(Idx)) {
8415 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8416 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8422 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8423 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8424 // one of the above mentioned nodes. It has to be wrapped because otherwise
8425 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8426 // be used to form addressing mode. These wrapped nodes will be selected
8429 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8430 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8432 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8434 unsigned char OpFlag = 0;
8435 unsigned WrapperKind = X86ISD::Wrapper;
8436 CodeModel::Model M = getTargetMachine().getCodeModel();
8438 if (Subtarget->isPICStyleRIPRel() &&
8439 (M == CodeModel::Small || M == CodeModel::Kernel))
8440 WrapperKind = X86ISD::WrapperRIP;
8441 else if (Subtarget->isPICStyleGOT())
8442 OpFlag = X86II::MO_GOTOFF;
8443 else if (Subtarget->isPICStyleStubPIC())
8444 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8446 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8448 CP->getOffset(), OpFlag);
8450 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8451 // With PIC, the address is actually $g + Offset.
8453 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8454 DAG.getNode(X86ISD::GlobalBaseReg,
8455 SDLoc(), getPointerTy()),
8462 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8463 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8465 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8467 unsigned char OpFlag = 0;
8468 unsigned WrapperKind = X86ISD::Wrapper;
8469 CodeModel::Model M = getTargetMachine().getCodeModel();
8471 if (Subtarget->isPICStyleRIPRel() &&
8472 (M == CodeModel::Small || M == CodeModel::Kernel))
8473 WrapperKind = X86ISD::WrapperRIP;
8474 else if (Subtarget->isPICStyleGOT())
8475 OpFlag = X86II::MO_GOTOFF;
8476 else if (Subtarget->isPICStyleStubPIC())
8477 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8479 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8482 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8484 // With PIC, the address is actually $g + Offset.
8486 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8487 DAG.getNode(X86ISD::GlobalBaseReg,
8488 SDLoc(), getPointerTy()),
8495 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8496 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8498 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8500 unsigned char OpFlag = 0;
8501 unsigned WrapperKind = X86ISD::Wrapper;
8502 CodeModel::Model M = getTargetMachine().getCodeModel();
8504 if (Subtarget->isPICStyleRIPRel() &&
8505 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8506 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8507 OpFlag = X86II::MO_GOTPCREL;
8508 WrapperKind = X86ISD::WrapperRIP;
8509 } else if (Subtarget->isPICStyleGOT()) {
8510 OpFlag = X86II::MO_GOT;
8511 } else if (Subtarget->isPICStyleStubPIC()) {
8512 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8513 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8514 OpFlag = X86II::MO_DARWIN_NONLAZY;
8517 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8520 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8522 // With PIC, the address is actually $g + Offset.
8523 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8524 !Subtarget->is64Bit()) {
8525 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8526 DAG.getNode(X86ISD::GlobalBaseReg,
8527 SDLoc(), getPointerTy()),
8531 // For symbols that require a load from a stub to get the address, emit the
8533 if (isGlobalStubReference(OpFlag))
8534 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8535 MachinePointerInfo::getGOT(), false, false, false, 0);
8541 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8542 // Create the TargetBlockAddressAddress node.
8543 unsigned char OpFlags =
8544 Subtarget->ClassifyBlockAddressReference();
8545 CodeModel::Model M = getTargetMachine().getCodeModel();
8546 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8547 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8549 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8552 if (Subtarget->isPICStyleRIPRel() &&
8553 (M == CodeModel::Small || M == CodeModel::Kernel))
8554 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8556 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8558 // With PIC, the address is actually $g + Offset.
8559 if (isGlobalRelativeToPICBase(OpFlags)) {
8560 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8561 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8569 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8570 int64_t Offset, SelectionDAG &DAG) const {
8571 // Create the TargetGlobalAddress node, folding in the constant
8572 // offset if it is legal.
8573 unsigned char OpFlags =
8574 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8575 CodeModel::Model M = getTargetMachine().getCodeModel();
8577 if (OpFlags == X86II::MO_NO_FLAG &&
8578 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8579 // A direct static reference to a global.
8580 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8583 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8586 if (Subtarget->isPICStyleRIPRel() &&
8587 (M == CodeModel::Small || M == CodeModel::Kernel))
8588 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8590 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8592 // With PIC, the address is actually $g + Offset.
8593 if (isGlobalRelativeToPICBase(OpFlags)) {
8594 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8595 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8599 // For globals that require a load from a stub to get the address, emit the
8601 if (isGlobalStubReference(OpFlags))
8602 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8603 MachinePointerInfo::getGOT(), false, false, false, 0);
8605 // If there was a non-zero offset that we didn't fold, create an explicit
8608 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8609 DAG.getConstant(Offset, getPointerTy()));
8615 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8616 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8617 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8618 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8622 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8623 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8624 unsigned char OperandFlags, bool LocalDynamic = false) {
8625 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8626 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8628 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8629 GA->getValueType(0),
8633 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8637 SDValue Ops[] = { Chain, TGA, *InFlag };
8638 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8640 SDValue Ops[] = { Chain, TGA };
8641 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8644 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8645 MFI->setAdjustsStack(true);
8647 SDValue Flag = Chain.getValue(1);
8648 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8651 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8653 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8656 SDLoc dl(GA); // ? function entry point might be better
8657 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8658 DAG.getNode(X86ISD::GlobalBaseReg,
8659 SDLoc(), PtrVT), InFlag);
8660 InFlag = Chain.getValue(1);
8662 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8665 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8667 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8669 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8670 X86::RAX, X86II::MO_TLSGD);
8673 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8679 // Get the start address of the TLS block for this module.
8680 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8681 .getInfo<X86MachineFunctionInfo>();
8682 MFI->incNumLocalDynamicTLSAccesses();
8686 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8687 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8690 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8691 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8692 InFlag = Chain.getValue(1);
8693 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8694 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8697 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8701 unsigned char OperandFlags = X86II::MO_DTPOFF;
8702 unsigned WrapperKind = X86ISD::Wrapper;
8703 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8704 GA->getValueType(0),
8705 GA->getOffset(), OperandFlags);
8706 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8708 // Add x@dtpoff with the base.
8709 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8712 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8713 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8714 const EVT PtrVT, TLSModel::Model model,
8715 bool is64Bit, bool isPIC) {
8718 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8719 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8720 is64Bit ? 257 : 256));
8722 SDValue ThreadPointer =
8723 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8724 MachinePointerInfo(Ptr), false, false, false, 0);
8726 unsigned char OperandFlags = 0;
8727 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8729 unsigned WrapperKind = X86ISD::Wrapper;
8730 if (model == TLSModel::LocalExec) {
8731 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8732 } else if (model == TLSModel::InitialExec) {
8734 OperandFlags = X86II::MO_GOTTPOFF;
8735 WrapperKind = X86ISD::WrapperRIP;
8737 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8740 llvm_unreachable("Unexpected model");
8743 // emit "addl x@ntpoff,%eax" (local exec)
8744 // or "addl x@indntpoff,%eax" (initial exec)
8745 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8747 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8748 GA->getOffset(), OperandFlags);
8749 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8751 if (model == TLSModel::InitialExec) {
8752 if (isPIC && !is64Bit) {
8753 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8754 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8758 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8759 MachinePointerInfo::getGOT(), false, false, false, 0);
8762 // The address of the thread local variable is the add of the thread
8763 // pointer with the offset of the variable.
8764 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8768 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8770 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8771 const GlobalValue *GV = GA->getGlobal();
8773 if (Subtarget->isTargetELF()) {
8774 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8777 case TLSModel::GeneralDynamic:
8778 if (Subtarget->is64Bit())
8779 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8780 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8781 case TLSModel::LocalDynamic:
8782 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8783 Subtarget->is64Bit());
8784 case TLSModel::InitialExec:
8785 case TLSModel::LocalExec:
8786 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8787 Subtarget->is64Bit(),
8788 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8790 llvm_unreachable("Unknown TLS model.");
8793 if (Subtarget->isTargetDarwin()) {
8794 // Darwin only has one model of TLS. Lower to that.
8795 unsigned char OpFlag = 0;
8796 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8797 X86ISD::WrapperRIP : X86ISD::Wrapper;
8799 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8801 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8802 !Subtarget->is64Bit();
8804 OpFlag = X86II::MO_TLVP_PIC_BASE;
8806 OpFlag = X86II::MO_TLVP;
8808 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8809 GA->getValueType(0),
8810 GA->getOffset(), OpFlag);
8811 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8813 // With PIC32, the address is actually $g + Offset.
8815 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8816 DAG.getNode(X86ISD::GlobalBaseReg,
8817 SDLoc(), getPointerTy()),
8820 // Lowering the machine isd will make sure everything is in the right
8822 SDValue Chain = DAG.getEntryNode();
8823 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8824 SDValue Args[] = { Chain, Offset };
8825 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8827 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8828 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8829 MFI->setAdjustsStack(true);
8831 // And our return value (tls address) is in the standard call return value
8833 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8834 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8838 if (Subtarget->isTargetKnownWindowsMSVC() ||
8839 Subtarget->isTargetWindowsGNU()) {
8840 // Just use the implicit TLS architecture
8841 // Need to generate someting similar to:
8842 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8844 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8845 // mov rcx, qword [rdx+rcx*8]
8846 // mov eax, .tls$:tlsvar
8847 // [rax+rcx] contains the address
8848 // Windows 64bit: gs:0x58
8849 // Windows 32bit: fs:__tls_array
8851 // If GV is an alias then use the aliasee for determining
8852 // thread-localness.
8853 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8854 GV = GA->getAliasee();
8856 SDValue Chain = DAG.getEntryNode();
8858 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8859 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8860 // use its literal value of 0x2C.
8861 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8862 ? Type::getInt8PtrTy(*DAG.getContext(),
8864 : Type::getInt32PtrTy(*DAG.getContext(),
8868 Subtarget->is64Bit()
8869 ? DAG.getIntPtrConstant(0x58)
8870 : (Subtarget->isTargetWindowsGNU()
8871 ? DAG.getIntPtrConstant(0x2C)
8872 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8874 SDValue ThreadPointer =
8875 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8876 MachinePointerInfo(Ptr), false, false, false, 0);
8878 // Load the _tls_index variable
8879 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8880 if (Subtarget->is64Bit())
8881 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8882 IDX, MachinePointerInfo(), MVT::i32,
8885 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8886 false, false, false, 0);
8888 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8890 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8892 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8893 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8894 false, false, false, 0);
8896 // Get the offset of start of .tls section
8897 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8898 GA->getValueType(0),
8899 GA->getOffset(), X86II::MO_SECREL);
8900 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8902 // The address of the thread local variable is the add of the thread
8903 // pointer with the offset of the variable.
8904 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8907 llvm_unreachable("TLS not implemented for this target.");
8910 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8911 /// and take a 2 x i32 value to shift plus a shift amount.
8912 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8913 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8914 MVT VT = Op.getSimpleValueType();
8915 unsigned VTBits = VT.getSizeInBits();
8917 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8918 SDValue ShOpLo = Op.getOperand(0);
8919 SDValue ShOpHi = Op.getOperand(1);
8920 SDValue ShAmt = Op.getOperand(2);
8921 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8922 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8924 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8925 DAG.getConstant(VTBits - 1, MVT::i8));
8926 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8927 DAG.getConstant(VTBits - 1, MVT::i8))
8928 : DAG.getConstant(0, VT);
8931 if (Op.getOpcode() == ISD::SHL_PARTS) {
8932 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8933 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8935 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8936 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8939 // If the shift amount is larger or equal than the width of a part we can't
8940 // rely on the results of shld/shrd. Insert a test and select the appropriate
8941 // values for large shift amounts.
8942 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8943 DAG.getConstant(VTBits, MVT::i8));
8944 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8945 AndNode, DAG.getConstant(0, MVT::i8));
8948 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8949 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8950 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8952 if (Op.getOpcode() == ISD::SHL_PARTS) {
8953 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8954 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8956 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8957 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8960 SDValue Ops[2] = { Lo, Hi };
8961 return DAG.getMergeValues(Ops, dl);
8964 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8965 SelectionDAG &DAG) const {
8966 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8968 if (SrcVT.isVector())
8971 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8972 "Unknown SINT_TO_FP to lower!");
8974 // These are really Legal; return the operand so the caller accepts it as
8976 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8978 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8979 Subtarget->is64Bit()) {
8984 unsigned Size = SrcVT.getSizeInBits()/8;
8985 MachineFunction &MF = DAG.getMachineFunction();
8986 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8987 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8988 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8990 MachinePointerInfo::getFixedStack(SSFI),
8992 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8995 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8997 SelectionDAG &DAG) const {
9001 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9003 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9005 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9007 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9009 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9010 MachineMemOperand *MMO;
9012 int SSFI = FI->getIndex();
9014 DAG.getMachineFunction()
9015 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9016 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9018 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9019 StackSlot = StackSlot.getOperand(1);
9021 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9022 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9024 Tys, Ops, SrcVT, MMO);
9027 Chain = Result.getValue(1);
9028 SDValue InFlag = Result.getValue(2);
9030 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9031 // shouldn't be necessary except that RFP cannot be live across
9032 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9033 MachineFunction &MF = DAG.getMachineFunction();
9034 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9035 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9036 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9037 Tys = DAG.getVTList(MVT::Other);
9039 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9041 MachineMemOperand *MMO =
9042 DAG.getMachineFunction()
9043 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9044 MachineMemOperand::MOStore, SSFISize, SSFISize);
9046 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9047 Ops, Op.getValueType(), MMO);
9048 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9049 MachinePointerInfo::getFixedStack(SSFI),
9050 false, false, false, 0);
9056 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9057 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9058 SelectionDAG &DAG) const {
9059 // This algorithm is not obvious. Here it is what we're trying to output:
9062 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9063 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9067 pshufd $0x4e, %xmm0, %xmm1
9073 LLVMContext *Context = DAG.getContext();
9075 // Build some magic constants.
9076 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9077 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9078 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9080 SmallVector<Constant*,2> CV1;
9082 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9083 APInt(64, 0x4330000000000000ULL))));
9085 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9086 APInt(64, 0x4530000000000000ULL))));
9087 Constant *C1 = ConstantVector::get(CV1);
9088 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9090 // Load the 64-bit value into an XMM register.
9091 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9093 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9094 MachinePointerInfo::getConstantPool(),
9095 false, false, false, 16);
9096 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9097 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9100 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9101 MachinePointerInfo::getConstantPool(),
9102 false, false, false, 16);
9103 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9104 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9107 if (Subtarget->hasSSE3()) {
9108 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9109 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9111 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9112 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9114 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9115 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9119 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9120 DAG.getIntPtrConstant(0));
9123 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9124 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9125 SelectionDAG &DAG) const {
9127 // FP constant to bias correct the final result.
9128 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9131 // Load the 32-bit value into an XMM register.
9132 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9135 // Zero out the upper parts of the register.
9136 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9138 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9139 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9140 DAG.getIntPtrConstant(0));
9142 // Or the load with the bias.
9143 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9144 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9145 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9147 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9148 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9149 MVT::v2f64, Bias)));
9150 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9151 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9152 DAG.getIntPtrConstant(0));
9154 // Subtract the bias.
9155 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9157 // Handle final rounding.
9158 EVT DestVT = Op.getValueType();
9160 if (DestVT.bitsLT(MVT::f64))
9161 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9162 DAG.getIntPtrConstant(0));
9163 if (DestVT.bitsGT(MVT::f64))
9164 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9166 // Handle final rounding.
9170 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9171 SelectionDAG &DAG) const {
9172 SDValue N0 = Op.getOperand(0);
9173 MVT SVT = N0.getSimpleValueType();
9176 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9177 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9178 "Custom UINT_TO_FP is not supported!");
9180 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9181 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9182 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9185 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9186 SelectionDAG &DAG) const {
9187 SDValue N0 = Op.getOperand(0);
9190 if (Op.getValueType().isVector())
9191 return lowerUINT_TO_FP_vec(Op, DAG);
9193 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9194 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9195 // the optimization here.
9196 if (DAG.SignBitIsZero(N0))
9197 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9199 MVT SrcVT = N0.getSimpleValueType();
9200 MVT DstVT = Op.getSimpleValueType();
9201 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9202 return LowerUINT_TO_FP_i64(Op, DAG);
9203 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9204 return LowerUINT_TO_FP_i32(Op, DAG);
9205 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9208 // Make a 64-bit buffer, and use it to build an FILD.
9209 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9210 if (SrcVT == MVT::i32) {
9211 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9212 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9213 getPointerTy(), StackSlot, WordOff);
9214 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9215 StackSlot, MachinePointerInfo(),
9217 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9218 OffsetSlot, MachinePointerInfo(),
9220 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9224 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9225 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9226 StackSlot, MachinePointerInfo(),
9228 // For i64 source, we need to add the appropriate power of 2 if the input
9229 // was negative. This is the same as the optimization in
9230 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9231 // we must be careful to do the computation in x87 extended precision, not
9232 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9233 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9234 MachineMemOperand *MMO =
9235 DAG.getMachineFunction()
9236 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9237 MachineMemOperand::MOLoad, 8, 8);
9239 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9240 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9241 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9244 APInt FF(32, 0x5F800000ULL);
9246 // Check whether the sign bit is set.
9247 SDValue SignSet = DAG.getSetCC(dl,
9248 getSetCCResultType(*DAG.getContext(), MVT::i64),
9249 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9252 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9253 SDValue FudgePtr = DAG.getConstantPool(
9254 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9257 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9258 SDValue Zero = DAG.getIntPtrConstant(0);
9259 SDValue Four = DAG.getIntPtrConstant(4);
9260 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9262 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9264 // Load the value out, extending it from f32 to f80.
9265 // FIXME: Avoid the extend by constructing the right constant pool?
9266 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9267 FudgePtr, MachinePointerInfo::getConstantPool(),
9268 MVT::f32, false, false, 4);
9269 // Extend everything to 80 bits to force it to be done on x87.
9270 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9271 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9274 std::pair<SDValue,SDValue>
9275 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9276 bool IsSigned, bool IsReplace) const {
9279 EVT DstTy = Op.getValueType();
9281 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9282 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9286 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9287 DstTy.getSimpleVT() >= MVT::i16 &&
9288 "Unknown FP_TO_INT to lower!");
9290 // These are really Legal.
9291 if (DstTy == MVT::i32 &&
9292 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9293 return std::make_pair(SDValue(), SDValue());
9294 if (Subtarget->is64Bit() &&
9295 DstTy == MVT::i64 &&
9296 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9297 return std::make_pair(SDValue(), SDValue());
9299 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9300 // stack slot, or into the FTOL runtime function.
9301 MachineFunction &MF = DAG.getMachineFunction();
9302 unsigned MemSize = DstTy.getSizeInBits()/8;
9303 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9304 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9307 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9308 Opc = X86ISD::WIN_FTOL;
9310 switch (DstTy.getSimpleVT().SimpleTy) {
9311 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9312 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9313 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9314 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9317 SDValue Chain = DAG.getEntryNode();
9318 SDValue Value = Op.getOperand(0);
9319 EVT TheVT = Op.getOperand(0).getValueType();
9320 // FIXME This causes a redundant load/store if the SSE-class value is already
9321 // in memory, such as if it is on the callstack.
9322 if (isScalarFPTypeInSSEReg(TheVT)) {
9323 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9324 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9325 MachinePointerInfo::getFixedStack(SSFI),
9327 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9329 Chain, StackSlot, DAG.getValueType(TheVT)
9332 MachineMemOperand *MMO =
9333 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9334 MachineMemOperand::MOLoad, MemSize, MemSize);
9335 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9336 Chain = Value.getValue(1);
9337 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9338 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9341 MachineMemOperand *MMO =
9342 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9343 MachineMemOperand::MOStore, MemSize, MemSize);
9345 if (Opc != X86ISD::WIN_FTOL) {
9346 // Build the FP_TO_INT*_IN_MEM
9347 SDValue Ops[] = { Chain, Value, StackSlot };
9348 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9350 return std::make_pair(FIST, StackSlot);
9352 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9353 DAG.getVTList(MVT::Other, MVT::Glue),
9355 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9356 MVT::i32, ftol.getValue(1));
9357 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9358 MVT::i32, eax.getValue(2));
9359 SDValue Ops[] = { eax, edx };
9360 SDValue pair = IsReplace
9361 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9362 : DAG.getMergeValues(Ops, DL);
9363 return std::make_pair(pair, SDValue());
9367 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9368 const X86Subtarget *Subtarget) {
9369 MVT VT = Op->getSimpleValueType(0);
9370 SDValue In = Op->getOperand(0);
9371 MVT InVT = In.getSimpleValueType();
9374 // Optimize vectors in AVX mode:
9377 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9378 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9379 // Concat upper and lower parts.
9382 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9383 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9384 // Concat upper and lower parts.
9387 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9388 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9389 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9392 if (Subtarget->hasInt256())
9393 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9395 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9396 SDValue Undef = DAG.getUNDEF(InVT);
9397 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9398 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9399 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9401 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9402 VT.getVectorNumElements()/2);
9404 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9405 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9407 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9410 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9411 SelectionDAG &DAG) {
9412 MVT VT = Op->getSimpleValueType(0);
9413 SDValue In = Op->getOperand(0);
9414 MVT InVT = In.getSimpleValueType();
9416 unsigned int NumElts = VT.getVectorNumElements();
9417 if (NumElts != 8 && NumElts != 16)
9420 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9421 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9423 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9424 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9425 // Now we have only mask extension
9426 assert(InVT.getVectorElementType() == MVT::i1);
9427 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9428 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9429 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9430 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9431 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9432 MachinePointerInfo::getConstantPool(),
9433 false, false, false, Alignment);
9435 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9436 if (VT.is512BitVector())
9438 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9441 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9442 SelectionDAG &DAG) {
9443 if (Subtarget->hasFp256()) {
9444 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9452 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9453 SelectionDAG &DAG) {
9455 MVT VT = Op.getSimpleValueType();
9456 SDValue In = Op.getOperand(0);
9457 MVT SVT = In.getSimpleValueType();
9459 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9460 return LowerZERO_EXTEND_AVX512(Op, DAG);
9462 if (Subtarget->hasFp256()) {
9463 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9468 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9469 VT.getVectorNumElements() != SVT.getVectorNumElements());
9473 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9475 MVT VT = Op.getSimpleValueType();
9476 SDValue In = Op.getOperand(0);
9477 MVT InVT = In.getSimpleValueType();
9479 if (VT == MVT::i1) {
9480 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9481 "Invalid scalar TRUNCATE operation");
9482 if (InVT == MVT::i32)
9484 if (InVT.getSizeInBits() == 64)
9485 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9486 else if (InVT.getSizeInBits() < 32)
9487 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9488 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9490 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9491 "Invalid TRUNCATE operation");
9493 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9494 if (VT.getVectorElementType().getSizeInBits() >=8)
9495 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9497 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9498 unsigned NumElts = InVT.getVectorNumElements();
9499 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9500 if (InVT.getSizeInBits() < 512) {
9501 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9502 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9506 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9507 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9508 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9509 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9510 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9511 MachinePointerInfo::getConstantPool(),
9512 false, false, false, Alignment);
9513 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9514 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9515 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9518 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9519 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9520 if (Subtarget->hasInt256()) {
9521 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9522 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9523 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9525 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9526 DAG.getIntPtrConstant(0));
9529 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9530 DAG.getIntPtrConstant(0));
9531 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9532 DAG.getIntPtrConstant(2));
9533 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9534 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9535 static const int ShufMask[] = {0, 2, 4, 6};
9536 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9539 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9540 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9541 if (Subtarget->hasInt256()) {
9542 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9544 SmallVector<SDValue,32> pshufbMask;
9545 for (unsigned i = 0; i < 2; ++i) {
9546 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9547 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9548 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9549 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9550 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9551 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9552 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9553 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9554 for (unsigned j = 0; j < 8; ++j)
9555 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9557 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9558 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9559 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9561 static const int ShufMask[] = {0, 2, -1, -1};
9562 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9564 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9565 DAG.getIntPtrConstant(0));
9566 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9569 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9570 DAG.getIntPtrConstant(0));
9572 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9573 DAG.getIntPtrConstant(4));
9575 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9576 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9579 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9580 -1, -1, -1, -1, -1, -1, -1, -1};
9582 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9583 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9584 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9586 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9587 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9589 // The MOVLHPS Mask:
9590 static const int ShufMask2[] = {0, 1, 4, 5};
9591 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9592 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9595 // Handle truncation of V256 to V128 using shuffles.
9596 if (!VT.is128BitVector() || !InVT.is256BitVector())
9599 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9601 unsigned NumElems = VT.getVectorNumElements();
9602 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9604 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9605 // Prepare truncation shuffle mask
9606 for (unsigned i = 0; i != NumElems; ++i)
9608 SDValue V = DAG.getVectorShuffle(NVT, DL,
9609 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9610 DAG.getUNDEF(NVT), &MaskVec[0]);
9611 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9612 DAG.getIntPtrConstant(0));
9615 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9616 SelectionDAG &DAG) const {
9617 assert(!Op.getSimpleValueType().isVector());
9619 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9620 /*IsSigned=*/ true, /*IsReplace=*/ false);
9621 SDValue FIST = Vals.first, StackSlot = Vals.second;
9622 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9623 if (!FIST.getNode()) return Op;
9625 if (StackSlot.getNode())
9627 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9628 FIST, StackSlot, MachinePointerInfo(),
9629 false, false, false, 0);
9631 // The node is the result.
9635 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9636 SelectionDAG &DAG) const {
9637 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9638 /*IsSigned=*/ false, /*IsReplace=*/ false);
9639 SDValue FIST = Vals.first, StackSlot = Vals.second;
9640 assert(FIST.getNode() && "Unexpected failure");
9642 if (StackSlot.getNode())
9644 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9645 FIST, StackSlot, MachinePointerInfo(),
9646 false, false, false, 0);
9648 // The node is the result.
9652 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9654 MVT VT = Op.getSimpleValueType();
9655 SDValue In = Op.getOperand(0);
9656 MVT SVT = In.getSimpleValueType();
9658 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9660 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9661 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9662 In, DAG.getUNDEF(SVT)));
9665 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9666 LLVMContext *Context = DAG.getContext();
9668 MVT VT = Op.getSimpleValueType();
9670 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9671 if (VT.isVector()) {
9672 EltVT = VT.getVectorElementType();
9673 NumElts = VT.getVectorNumElements();
9676 if (EltVT == MVT::f64)
9677 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9678 APInt(64, ~(1ULL << 63))));
9680 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9681 APInt(32, ~(1U << 31))));
9682 C = ConstantVector::getSplat(NumElts, C);
9683 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9684 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9685 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9686 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9687 MachinePointerInfo::getConstantPool(),
9688 false, false, false, Alignment);
9689 if (VT.isVector()) {
9690 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9691 return DAG.getNode(ISD::BITCAST, dl, VT,
9692 DAG.getNode(ISD::AND, dl, ANDVT,
9693 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9695 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9697 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9700 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9701 LLVMContext *Context = DAG.getContext();
9703 MVT VT = Op.getSimpleValueType();
9705 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9706 if (VT.isVector()) {
9707 EltVT = VT.getVectorElementType();
9708 NumElts = VT.getVectorNumElements();
9711 if (EltVT == MVT::f64)
9712 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9713 APInt(64, 1ULL << 63)));
9715 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9716 APInt(32, 1U << 31)));
9717 C = ConstantVector::getSplat(NumElts, C);
9718 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9719 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9720 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9721 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9722 MachinePointerInfo::getConstantPool(),
9723 false, false, false, Alignment);
9724 if (VT.isVector()) {
9725 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9726 return DAG.getNode(ISD::BITCAST, dl, VT,
9727 DAG.getNode(ISD::XOR, dl, XORVT,
9728 DAG.getNode(ISD::BITCAST, dl, XORVT,
9730 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9733 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9736 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9738 LLVMContext *Context = DAG.getContext();
9739 SDValue Op0 = Op.getOperand(0);
9740 SDValue Op1 = Op.getOperand(1);
9742 MVT VT = Op.getSimpleValueType();
9743 MVT SrcVT = Op1.getSimpleValueType();
9745 // If second operand is smaller, extend it first.
9746 if (SrcVT.bitsLT(VT)) {
9747 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9750 // And if it is bigger, shrink it first.
9751 if (SrcVT.bitsGT(VT)) {
9752 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9756 // At this point the operands and the result should have the same
9757 // type, and that won't be f80 since that is not custom lowered.
9759 // First get the sign bit of second operand.
9760 SmallVector<Constant*,4> CV;
9761 if (SrcVT == MVT::f64) {
9762 const fltSemantics &Sem = APFloat::IEEEdouble;
9763 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9764 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9766 const fltSemantics &Sem = APFloat::IEEEsingle;
9767 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9768 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9769 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9770 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9772 Constant *C = ConstantVector::get(CV);
9773 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9774 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9775 MachinePointerInfo::getConstantPool(),
9776 false, false, false, 16);
9777 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9779 // Shift sign bit right or left if the two operands have different types.
9780 if (SrcVT.bitsGT(VT)) {
9781 // Op0 is MVT::f32, Op1 is MVT::f64.
9782 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9783 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9784 DAG.getConstant(32, MVT::i32));
9785 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9786 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9787 DAG.getIntPtrConstant(0));
9790 // Clear first operand sign bit.
9792 if (VT == MVT::f64) {
9793 const fltSemantics &Sem = APFloat::IEEEdouble;
9794 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9795 APInt(64, ~(1ULL << 63)))));
9796 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9798 const fltSemantics &Sem = APFloat::IEEEsingle;
9799 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9800 APInt(32, ~(1U << 31)))));
9801 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9802 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9803 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9805 C = ConstantVector::get(CV);
9806 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9807 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9808 MachinePointerInfo::getConstantPool(),
9809 false, false, false, 16);
9810 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9812 // Or the value with the sign bit.
9813 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9816 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9817 SDValue N0 = Op.getOperand(0);
9819 MVT VT = Op.getSimpleValueType();
9821 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9822 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9823 DAG.getConstant(1, VT));
9824 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9827 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9829 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9830 SelectionDAG &DAG) {
9831 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9833 if (!Subtarget->hasSSE41())
9836 if (!Op->hasOneUse())
9839 SDNode *N = Op.getNode();
9842 SmallVector<SDValue, 8> Opnds;
9843 DenseMap<SDValue, unsigned> VecInMap;
9844 SmallVector<SDValue, 8> VecIns;
9845 EVT VT = MVT::Other;
9847 // Recognize a special case where a vector is casted into wide integer to
9849 Opnds.push_back(N->getOperand(0));
9850 Opnds.push_back(N->getOperand(1));
9852 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9853 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9854 // BFS traverse all OR'd operands.
9855 if (I->getOpcode() == ISD::OR) {
9856 Opnds.push_back(I->getOperand(0));
9857 Opnds.push_back(I->getOperand(1));
9858 // Re-evaluate the number of nodes to be traversed.
9859 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9863 // Quit if a non-EXTRACT_VECTOR_ELT
9864 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9867 // Quit if without a constant index.
9868 SDValue Idx = I->getOperand(1);
9869 if (!isa<ConstantSDNode>(Idx))
9872 SDValue ExtractedFromVec = I->getOperand(0);
9873 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9874 if (M == VecInMap.end()) {
9875 VT = ExtractedFromVec.getValueType();
9876 // Quit if not 128/256-bit vector.
9877 if (!VT.is128BitVector() && !VT.is256BitVector())
9879 // Quit if not the same type.
9880 if (VecInMap.begin() != VecInMap.end() &&
9881 VT != VecInMap.begin()->first.getValueType())
9883 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9884 VecIns.push_back(ExtractedFromVec);
9886 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9889 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9890 "Not extracted from 128-/256-bit vector.");
9892 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9894 for (DenseMap<SDValue, unsigned>::const_iterator
9895 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9896 // Quit if not all elements are used.
9897 if (I->second != FullMask)
9901 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9903 // Cast all vectors into TestVT for PTEST.
9904 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9905 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9907 // If more than one full vectors are evaluated, OR them first before PTEST.
9908 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9909 // Each iteration will OR 2 nodes and append the result until there is only
9910 // 1 node left, i.e. the final OR'd value of all vectors.
9911 SDValue LHS = VecIns[Slot];
9912 SDValue RHS = VecIns[Slot + 1];
9913 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9916 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9917 VecIns.back(), VecIns.back());
9920 /// \brief return true if \c Op has a use that doesn't just read flags.
9921 static bool hasNonFlagsUse(SDValue Op) {
9922 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9925 unsigned UOpNo = UI.getOperandNo();
9926 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9927 // Look pass truncate.
9928 UOpNo = User->use_begin().getOperandNo();
9929 User = *User->use_begin();
9932 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9933 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9939 /// Emit nodes that will be selected as "test Op0,Op0", or something
9941 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9942 SelectionDAG &DAG) const {
9943 if (Op.getValueType() == MVT::i1)
9944 // KORTEST instruction should be selected
9945 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9946 DAG.getConstant(0, Op.getValueType()));
9948 // CF and OF aren't always set the way we want. Determine which
9949 // of these we need.
9950 bool NeedCF = false;
9951 bool NeedOF = false;
9954 case X86::COND_A: case X86::COND_AE:
9955 case X86::COND_B: case X86::COND_BE:
9958 case X86::COND_G: case X86::COND_GE:
9959 case X86::COND_L: case X86::COND_LE:
9960 case X86::COND_O: case X86::COND_NO:
9964 // See if we can use the EFLAGS value from the operand instead of
9965 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9966 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9967 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9968 // Emit a CMP with 0, which is the TEST pattern.
9969 //if (Op.getValueType() == MVT::i1)
9970 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9971 // DAG.getConstant(0, MVT::i1));
9972 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9973 DAG.getConstant(0, Op.getValueType()));
9975 unsigned Opcode = 0;
9976 unsigned NumOperands = 0;
9978 // Truncate operations may prevent the merge of the SETCC instruction
9979 // and the arithmetic instruction before it. Attempt to truncate the operands
9980 // of the arithmetic instruction and use a reduced bit-width instruction.
9981 bool NeedTruncation = false;
9982 SDValue ArithOp = Op;
9983 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9984 SDValue Arith = Op->getOperand(0);
9985 // Both the trunc and the arithmetic op need to have one user each.
9986 if (Arith->hasOneUse())
9987 switch (Arith.getOpcode()) {
9994 NeedTruncation = true;
10000 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10001 // which may be the result of a CAST. We use the variable 'Op', which is the
10002 // non-casted variable when we check for possible users.
10003 switch (ArithOp.getOpcode()) {
10005 // Due to an isel shortcoming, be conservative if this add is likely to be
10006 // selected as part of a load-modify-store instruction. When the root node
10007 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10008 // uses of other nodes in the match, such as the ADD in this case. This
10009 // leads to the ADD being left around and reselected, with the result being
10010 // two adds in the output. Alas, even if none our users are stores, that
10011 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10012 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10013 // climbing the DAG back to the root, and it doesn't seem to be worth the
10015 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10016 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10017 if (UI->getOpcode() != ISD::CopyToReg &&
10018 UI->getOpcode() != ISD::SETCC &&
10019 UI->getOpcode() != ISD::STORE)
10022 if (ConstantSDNode *C =
10023 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10024 // An add of one will be selected as an INC.
10025 if (C->getAPIntValue() == 1) {
10026 Opcode = X86ISD::INC;
10031 // An add of negative one (subtract of one) will be selected as a DEC.
10032 if (C->getAPIntValue().isAllOnesValue()) {
10033 Opcode = X86ISD::DEC;
10039 // Otherwise use a regular EFLAGS-setting add.
10040 Opcode = X86ISD::ADD;
10045 // If we have a constant logical shift that's only used in a comparison
10046 // against zero turn it into an equivalent AND. This allows turning it into
10047 // a TEST instruction later.
10048 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
10049 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10050 EVT VT = Op.getValueType();
10051 unsigned BitWidth = VT.getSizeInBits();
10052 unsigned ShAmt = Op->getConstantOperandVal(1);
10053 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10055 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10056 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10057 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10058 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10060 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10061 DAG.getConstant(Mask, VT));
10062 DAG.ReplaceAllUsesWith(Op, New);
10068 // If the primary and result isn't used, don't bother using X86ISD::AND,
10069 // because a TEST instruction will be better.
10070 if (!hasNonFlagsUse(Op))
10076 // Due to the ISEL shortcoming noted above, be conservative if this op is
10077 // likely to be selected as part of a load-modify-store instruction.
10078 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10079 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10080 if (UI->getOpcode() == ISD::STORE)
10083 // Otherwise use a regular EFLAGS-setting instruction.
10084 switch (ArithOp.getOpcode()) {
10085 default: llvm_unreachable("unexpected operator!");
10086 case ISD::SUB: Opcode = X86ISD::SUB; break;
10087 case ISD::XOR: Opcode = X86ISD::XOR; break;
10088 case ISD::AND: Opcode = X86ISD::AND; break;
10090 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10091 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10092 if (EFLAGS.getNode())
10095 Opcode = X86ISD::OR;
10109 return SDValue(Op.getNode(), 1);
10115 // If we found that truncation is beneficial, perform the truncation and
10117 if (NeedTruncation) {
10118 EVT VT = Op.getValueType();
10119 SDValue WideVal = Op->getOperand(0);
10120 EVT WideVT = WideVal.getValueType();
10121 unsigned ConvertedOp = 0;
10122 // Use a target machine opcode to prevent further DAGCombine
10123 // optimizations that may separate the arithmetic operations
10124 // from the setcc node.
10125 switch (WideVal.getOpcode()) {
10127 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10128 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10129 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10130 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10131 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10135 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10136 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10137 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10138 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10139 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10145 // Emit a CMP with 0, which is the TEST pattern.
10146 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10147 DAG.getConstant(0, Op.getValueType()));
10149 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10150 SmallVector<SDValue, 4> Ops;
10151 for (unsigned i = 0; i != NumOperands; ++i)
10152 Ops.push_back(Op.getOperand(i));
10154 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10155 DAG.ReplaceAllUsesWith(Op, New);
10156 return SDValue(New.getNode(), 1);
10159 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10161 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10162 SDLoc dl, SelectionDAG &DAG) const {
10163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10164 if (C->getAPIntValue() == 0)
10165 return EmitTest(Op0, X86CC, dl, DAG);
10167 if (Op0.getValueType() == MVT::i1)
10168 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10171 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10172 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10173 // Do the comparison at i32 if it's smaller, besides the Atom case.
10174 // This avoids subregister aliasing issues. Keep the smaller reference
10175 // if we're optimizing for size, however, as that'll allow better folding
10176 // of memory operations.
10177 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10178 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10179 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10180 !Subtarget->isAtom()) {
10181 unsigned ExtendOp =
10182 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10183 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10184 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10186 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10187 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10188 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10190 return SDValue(Sub.getNode(), 1);
10192 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10195 /// Convert a comparison if required by the subtarget.
10196 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10197 SelectionDAG &DAG) const {
10198 // If the subtarget does not support the FUCOMI instruction, floating-point
10199 // comparisons have to be converted.
10200 if (Subtarget->hasCMov() ||
10201 Cmp.getOpcode() != X86ISD::CMP ||
10202 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10203 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10206 // The instruction selector will select an FUCOM instruction instead of
10207 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10208 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10209 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10211 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10212 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10213 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10214 DAG.getConstant(8, MVT::i8));
10215 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10216 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10219 static bool isAllOnes(SDValue V) {
10220 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10221 return C && C->isAllOnesValue();
10224 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10225 /// if it's possible.
10226 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10227 SDLoc dl, SelectionDAG &DAG) const {
10228 SDValue Op0 = And.getOperand(0);
10229 SDValue Op1 = And.getOperand(1);
10230 if (Op0.getOpcode() == ISD::TRUNCATE)
10231 Op0 = Op0.getOperand(0);
10232 if (Op1.getOpcode() == ISD::TRUNCATE)
10233 Op1 = Op1.getOperand(0);
10236 if (Op1.getOpcode() == ISD::SHL)
10237 std::swap(Op0, Op1);
10238 if (Op0.getOpcode() == ISD::SHL) {
10239 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10240 if (And00C->getZExtValue() == 1) {
10241 // If we looked past a truncate, check that it's only truncating away
10243 unsigned BitWidth = Op0.getValueSizeInBits();
10244 unsigned AndBitWidth = And.getValueSizeInBits();
10245 if (BitWidth > AndBitWidth) {
10247 DAG.computeKnownBits(Op0, Zeros, Ones);
10248 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10252 RHS = Op0.getOperand(1);
10254 } else if (Op1.getOpcode() == ISD::Constant) {
10255 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10256 uint64_t AndRHSVal = AndRHS->getZExtValue();
10257 SDValue AndLHS = Op0;
10259 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10260 LHS = AndLHS.getOperand(0);
10261 RHS = AndLHS.getOperand(1);
10264 // Use BT if the immediate can't be encoded in a TEST instruction.
10265 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10267 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10271 if (LHS.getNode()) {
10272 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10273 // instruction. Since the shift amount is in-range-or-undefined, we know
10274 // that doing a bittest on the i32 value is ok. We extend to i32 because
10275 // the encoding for the i16 version is larger than the i32 version.
10276 // Also promote i16 to i32 for performance / code size reason.
10277 if (LHS.getValueType() == MVT::i8 ||
10278 LHS.getValueType() == MVT::i16)
10279 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10281 // If the operand types disagree, extend the shift amount to match. Since
10282 // BT ignores high bits (like shifts) we can use anyextend.
10283 if (LHS.getValueType() != RHS.getValueType())
10284 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10286 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10287 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10288 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10289 DAG.getConstant(Cond, MVT::i8), BT);
10295 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10297 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10302 // SSE Condition code mapping:
10311 switch (SetCCOpcode) {
10312 default: llvm_unreachable("Unexpected SETCC condition");
10314 case ISD::SETEQ: SSECC = 0; break;
10316 case ISD::SETGT: Swap = true; // Fallthrough
10318 case ISD::SETOLT: SSECC = 1; break;
10320 case ISD::SETGE: Swap = true; // Fallthrough
10322 case ISD::SETOLE: SSECC = 2; break;
10323 case ISD::SETUO: SSECC = 3; break;
10325 case ISD::SETNE: SSECC = 4; break;
10326 case ISD::SETULE: Swap = true; // Fallthrough
10327 case ISD::SETUGE: SSECC = 5; break;
10328 case ISD::SETULT: Swap = true; // Fallthrough
10329 case ISD::SETUGT: SSECC = 6; break;
10330 case ISD::SETO: SSECC = 7; break;
10332 case ISD::SETONE: SSECC = 8; break;
10335 std::swap(Op0, Op1);
10340 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10341 // ones, and then concatenate the result back.
10342 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10343 MVT VT = Op.getSimpleValueType();
10345 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10346 "Unsupported value type for operation");
10348 unsigned NumElems = VT.getVectorNumElements();
10350 SDValue CC = Op.getOperand(2);
10352 // Extract the LHS vectors
10353 SDValue LHS = Op.getOperand(0);
10354 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10355 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10357 // Extract the RHS vectors
10358 SDValue RHS = Op.getOperand(1);
10359 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10360 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10362 // Issue the operation on the smaller types and concatenate the result back
10363 MVT EltVT = VT.getVectorElementType();
10364 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10365 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10366 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10367 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10370 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10371 const X86Subtarget *Subtarget) {
10372 SDValue Op0 = Op.getOperand(0);
10373 SDValue Op1 = Op.getOperand(1);
10374 SDValue CC = Op.getOperand(2);
10375 MVT VT = Op.getSimpleValueType();
10378 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10379 Op.getValueType().getScalarType() == MVT::i1 &&
10380 "Cannot set masked compare for this operation");
10382 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10384 bool Unsigned = false;
10387 switch (SetCCOpcode) {
10388 default: llvm_unreachable("Unexpected SETCC condition");
10389 case ISD::SETNE: SSECC = 4; break;
10390 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10391 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10392 case ISD::SETLT: Swap = true; //fall-through
10393 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10394 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10395 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10396 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10397 case ISD::SETULE: Unsigned = true; //fall-through
10398 case ISD::SETLE: SSECC = 2; break;
10402 std::swap(Op0, Op1);
10404 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10405 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10406 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10407 DAG.getConstant(SSECC, MVT::i8));
10410 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10411 /// operand \p Op1. If non-trivial (for example because it's not constant)
10412 /// return an empty value.
10413 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10415 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10419 MVT VT = Op1.getSimpleValueType();
10420 MVT EVT = VT.getVectorElementType();
10421 unsigned n = VT.getVectorNumElements();
10422 SmallVector<SDValue, 8> ULTOp1;
10424 for (unsigned i = 0; i < n; ++i) {
10425 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10426 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10429 // Avoid underflow.
10430 APInt Val = Elt->getAPIntValue();
10434 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10437 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10440 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10441 SelectionDAG &DAG) {
10442 SDValue Op0 = Op.getOperand(0);
10443 SDValue Op1 = Op.getOperand(1);
10444 SDValue CC = Op.getOperand(2);
10445 MVT VT = Op.getSimpleValueType();
10446 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10447 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10452 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10453 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10456 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10457 unsigned Opc = X86ISD::CMPP;
10458 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10459 assert(VT.getVectorNumElements() <= 16);
10460 Opc = X86ISD::CMPM;
10462 // In the two special cases we can't handle, emit two comparisons.
10465 unsigned CombineOpc;
10466 if (SetCCOpcode == ISD::SETUEQ) {
10467 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10469 assert(SetCCOpcode == ISD::SETONE);
10470 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10473 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10474 DAG.getConstant(CC0, MVT::i8));
10475 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10476 DAG.getConstant(CC1, MVT::i8));
10477 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10479 // Handle all other FP comparisons here.
10480 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10481 DAG.getConstant(SSECC, MVT::i8));
10484 // Break 256-bit integer vector compare into smaller ones.
10485 if (VT.is256BitVector() && !Subtarget->hasInt256())
10486 return Lower256IntVSETCC(Op, DAG);
10488 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10489 EVT OpVT = Op1.getValueType();
10490 if (Subtarget->hasAVX512()) {
10491 if (Op1.getValueType().is512BitVector() ||
10492 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10493 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10495 // In AVX-512 architecture setcc returns mask with i1 elements,
10496 // But there is no compare instruction for i8 and i16 elements.
10497 // We are not talking about 512-bit operands in this case, these
10498 // types are illegal.
10500 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10501 OpVT.getVectorElementType().getSizeInBits() >= 8))
10502 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10503 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10506 // We are handling one of the integer comparisons here. Since SSE only has
10507 // GT and EQ comparisons for integer, swapping operands and multiple
10508 // operations may be required for some comparisons.
10510 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10511 bool Subus = false;
10513 switch (SetCCOpcode) {
10514 default: llvm_unreachable("Unexpected SETCC condition");
10515 case ISD::SETNE: Invert = true;
10516 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10517 case ISD::SETLT: Swap = true;
10518 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10519 case ISD::SETGE: Swap = true;
10520 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10521 Invert = true; break;
10522 case ISD::SETULT: Swap = true;
10523 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10524 FlipSigns = true; break;
10525 case ISD::SETUGE: Swap = true;
10526 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10527 FlipSigns = true; Invert = true; break;
10530 // Special case: Use min/max operations for SETULE/SETUGE
10531 MVT VET = VT.getVectorElementType();
10533 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10534 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10537 switch (SetCCOpcode) {
10539 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10540 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10543 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10546 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10547 if (!MinMax && hasSubus) {
10548 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10550 // t = psubus Op0, Op1
10551 // pcmpeq t, <0..0>
10552 switch (SetCCOpcode) {
10554 case ISD::SETULT: {
10555 // If the comparison is against a constant we can turn this into a
10556 // setule. With psubus, setule does not require a swap. This is
10557 // beneficial because the constant in the register is no longer
10558 // destructed as the destination so it can be hoisted out of a loop.
10559 // Only do this pre-AVX since vpcmp* is no longer destructive.
10560 if (Subtarget->hasAVX())
10562 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10563 if (ULEOp1.getNode()) {
10565 Subus = true; Invert = false; Swap = false;
10569 // Psubus is better than flip-sign because it requires no inversion.
10570 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10571 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10575 Opc = X86ISD::SUBUS;
10581 std::swap(Op0, Op1);
10583 // Check that the operation in question is available (most are plain SSE2,
10584 // but PCMPGTQ and PCMPEQQ have different requirements).
10585 if (VT == MVT::v2i64) {
10586 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10587 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10589 // First cast everything to the right type.
10590 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10591 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10593 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10594 // bits of the inputs before performing those operations. The lower
10595 // compare is always unsigned.
10598 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10600 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10601 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10602 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10603 Sign, Zero, Sign, Zero);
10605 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10606 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10608 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10609 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10610 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10612 // Create masks for only the low parts/high parts of the 64 bit integers.
10613 static const int MaskHi[] = { 1, 1, 3, 3 };
10614 static const int MaskLo[] = { 0, 0, 2, 2 };
10615 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10616 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10617 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10619 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10620 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10623 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10625 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10628 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10629 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10630 // pcmpeqd + pshufd + pand.
10631 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10633 // First cast everything to the right type.
10634 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10635 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10638 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10640 // Make sure the lower and upper halves are both all-ones.
10641 static const int Mask[] = { 1, 0, 3, 2 };
10642 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10643 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10646 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10648 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10652 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10653 // bits of the inputs before performing those operations.
10655 EVT EltVT = VT.getVectorElementType();
10656 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10657 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10658 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10661 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10663 // If the logical-not of the result is required, perform that now.
10665 Result = DAG.getNOT(dl, Result, VT);
10668 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10671 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10672 getZeroVector(VT, Subtarget, DAG, dl));
10677 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10679 MVT VT = Op.getSimpleValueType();
10681 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10683 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10684 && "SetCC type must be 8-bit or 1-bit integer");
10685 SDValue Op0 = Op.getOperand(0);
10686 SDValue Op1 = Op.getOperand(1);
10688 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10690 // Optimize to BT if possible.
10691 // Lower (X & (1 << N)) == 0 to BT(X, N).
10692 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10693 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10694 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10695 Op1.getOpcode() == ISD::Constant &&
10696 cast<ConstantSDNode>(Op1)->isNullValue() &&
10697 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10698 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10699 if (NewSetCC.getNode())
10703 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10705 if (Op1.getOpcode() == ISD::Constant &&
10706 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10707 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10708 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10710 // If the input is a setcc, then reuse the input setcc or use a new one with
10711 // the inverted condition.
10712 if (Op0.getOpcode() == X86ISD::SETCC) {
10713 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10714 bool Invert = (CC == ISD::SETNE) ^
10715 cast<ConstantSDNode>(Op1)->isNullValue();
10719 CCode = X86::GetOppositeBranchCondition(CCode);
10720 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10721 DAG.getConstant(CCode, MVT::i8),
10722 Op0.getOperand(1));
10724 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10728 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10729 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10730 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10732 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10733 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10736 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10737 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10738 if (X86CC == X86::COND_INVALID)
10741 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10742 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10743 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10744 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10746 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10750 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10751 static bool isX86LogicalCmp(SDValue Op) {
10752 unsigned Opc = Op.getNode()->getOpcode();
10753 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10754 Opc == X86ISD::SAHF)
10756 if (Op.getResNo() == 1 &&
10757 (Opc == X86ISD::ADD ||
10758 Opc == X86ISD::SUB ||
10759 Opc == X86ISD::ADC ||
10760 Opc == X86ISD::SBB ||
10761 Opc == X86ISD::SMUL ||
10762 Opc == X86ISD::UMUL ||
10763 Opc == X86ISD::INC ||
10764 Opc == X86ISD::DEC ||
10765 Opc == X86ISD::OR ||
10766 Opc == X86ISD::XOR ||
10767 Opc == X86ISD::AND))
10770 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10776 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10777 if (V.getOpcode() != ISD::TRUNCATE)
10780 SDValue VOp0 = V.getOperand(0);
10781 unsigned InBits = VOp0.getValueSizeInBits();
10782 unsigned Bits = V.getValueSizeInBits();
10783 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10786 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10787 bool addTest = true;
10788 SDValue Cond = Op.getOperand(0);
10789 SDValue Op1 = Op.getOperand(1);
10790 SDValue Op2 = Op.getOperand(2);
10792 EVT VT = Op1.getValueType();
10795 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10796 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10797 // sequence later on.
10798 if (Cond.getOpcode() == ISD::SETCC &&
10799 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10800 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10801 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10802 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10803 int SSECC = translateX86FSETCC(
10804 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10807 if (Subtarget->hasAVX512()) {
10808 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10809 DAG.getConstant(SSECC, MVT::i8));
10810 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10812 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10813 DAG.getConstant(SSECC, MVT::i8));
10814 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10815 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10816 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10820 if (Cond.getOpcode() == ISD::SETCC) {
10821 SDValue NewCond = LowerSETCC(Cond, DAG);
10822 if (NewCond.getNode())
10826 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10827 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10828 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10829 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10830 if (Cond.getOpcode() == X86ISD::SETCC &&
10831 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10832 isZero(Cond.getOperand(1).getOperand(1))) {
10833 SDValue Cmp = Cond.getOperand(1);
10835 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10837 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10838 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10839 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10841 SDValue CmpOp0 = Cmp.getOperand(0);
10842 // Apply further optimizations for special cases
10843 // (select (x != 0), -1, 0) -> neg & sbb
10844 // (select (x == 0), 0, -1) -> neg & sbb
10845 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10846 if (YC->isNullValue() &&
10847 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10848 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10849 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10850 DAG.getConstant(0, CmpOp0.getValueType()),
10852 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10853 DAG.getConstant(X86::COND_B, MVT::i8),
10854 SDValue(Neg.getNode(), 1));
10858 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10859 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10860 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10862 SDValue Res = // Res = 0 or -1.
10863 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10864 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10866 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10867 Res = DAG.getNOT(DL, Res, Res.getValueType());
10869 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10870 if (!N2C || !N2C->isNullValue())
10871 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10876 // Look past (and (setcc_carry (cmp ...)), 1).
10877 if (Cond.getOpcode() == ISD::AND &&
10878 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10879 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10880 if (C && C->getAPIntValue() == 1)
10881 Cond = Cond.getOperand(0);
10884 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10885 // setting operand in place of the X86ISD::SETCC.
10886 unsigned CondOpcode = Cond.getOpcode();
10887 if (CondOpcode == X86ISD::SETCC ||
10888 CondOpcode == X86ISD::SETCC_CARRY) {
10889 CC = Cond.getOperand(0);
10891 SDValue Cmp = Cond.getOperand(1);
10892 unsigned Opc = Cmp.getOpcode();
10893 MVT VT = Op.getSimpleValueType();
10895 bool IllegalFPCMov = false;
10896 if (VT.isFloatingPoint() && !VT.isVector() &&
10897 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10898 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10900 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10901 Opc == X86ISD::BT) { // FIXME
10905 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10906 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10907 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10908 Cond.getOperand(0).getValueType() != MVT::i8)) {
10909 SDValue LHS = Cond.getOperand(0);
10910 SDValue RHS = Cond.getOperand(1);
10911 unsigned X86Opcode;
10914 switch (CondOpcode) {
10915 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10916 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10917 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10918 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10919 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10920 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10921 default: llvm_unreachable("unexpected overflowing operator");
10923 if (CondOpcode == ISD::UMULO)
10924 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10927 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10929 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10931 if (CondOpcode == ISD::UMULO)
10932 Cond = X86Op.getValue(2);
10934 Cond = X86Op.getValue(1);
10936 CC = DAG.getConstant(X86Cond, MVT::i8);
10941 // Look pass the truncate if the high bits are known zero.
10942 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10943 Cond = Cond.getOperand(0);
10945 // We know the result of AND is compared against zero. Try to match
10947 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10948 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10949 if (NewSetCC.getNode()) {
10950 CC = NewSetCC.getOperand(0);
10951 Cond = NewSetCC.getOperand(1);
10958 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10959 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10962 // a < b ? -1 : 0 -> RES = ~setcc_carry
10963 // a < b ? 0 : -1 -> RES = setcc_carry
10964 // a >= b ? -1 : 0 -> RES = setcc_carry
10965 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10966 if (Cond.getOpcode() == X86ISD::SUB) {
10967 Cond = ConvertCmpIfNecessary(Cond, DAG);
10968 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10970 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10971 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10972 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10973 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10974 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10975 return DAG.getNOT(DL, Res, Res.getValueType());
10980 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10981 // widen the cmov and push the truncate through. This avoids introducing a new
10982 // branch during isel and doesn't add any extensions.
10983 if (Op.getValueType() == MVT::i8 &&
10984 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10985 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10986 if (T1.getValueType() == T2.getValueType() &&
10987 // Blacklist CopyFromReg to avoid partial register stalls.
10988 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10989 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10990 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10991 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10995 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10996 // condition is true.
10997 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10998 SDValue Ops[] = { Op2, Op1, CC, Cond };
10999 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11002 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11003 MVT VT = Op->getSimpleValueType(0);
11004 SDValue In = Op->getOperand(0);
11005 MVT InVT = In.getSimpleValueType();
11008 unsigned int NumElts = VT.getVectorNumElements();
11009 if (NumElts != 8 && NumElts != 16)
11012 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11013 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11015 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11016 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11018 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11019 Constant *C = ConstantInt::get(*DAG.getContext(),
11020 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11022 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11023 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11024 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11025 MachinePointerInfo::getConstantPool(),
11026 false, false, false, Alignment);
11027 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11028 if (VT.is512BitVector())
11030 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11033 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11034 SelectionDAG &DAG) {
11035 MVT VT = Op->getSimpleValueType(0);
11036 SDValue In = Op->getOperand(0);
11037 MVT InVT = In.getSimpleValueType();
11040 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11041 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11043 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11044 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11045 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11048 if (Subtarget->hasInt256())
11049 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11051 // Optimize vectors in AVX mode
11052 // Sign extend v8i16 to v8i32 and
11055 // Divide input vector into two parts
11056 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11057 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11058 // concat the vectors to original VT
11060 unsigned NumElems = InVT.getVectorNumElements();
11061 SDValue Undef = DAG.getUNDEF(InVT);
11063 SmallVector<int,8> ShufMask1(NumElems, -1);
11064 for (unsigned i = 0; i != NumElems/2; ++i)
11067 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11069 SmallVector<int,8> ShufMask2(NumElems, -1);
11070 for (unsigned i = 0; i != NumElems/2; ++i)
11071 ShufMask2[i] = i + NumElems/2;
11073 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11075 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11076 VT.getVectorNumElements()/2);
11078 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11079 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11081 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11084 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11085 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11086 // from the AND / OR.
11087 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11088 Opc = Op.getOpcode();
11089 if (Opc != ISD::OR && Opc != ISD::AND)
11091 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11092 Op.getOperand(0).hasOneUse() &&
11093 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11094 Op.getOperand(1).hasOneUse());
11097 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11098 // 1 and that the SETCC node has a single use.
11099 static bool isXor1OfSetCC(SDValue Op) {
11100 if (Op.getOpcode() != ISD::XOR)
11102 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11103 if (N1C && N1C->getAPIntValue() == 1) {
11104 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11105 Op.getOperand(0).hasOneUse();
11110 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11111 bool addTest = true;
11112 SDValue Chain = Op.getOperand(0);
11113 SDValue Cond = Op.getOperand(1);
11114 SDValue Dest = Op.getOperand(2);
11117 bool Inverted = false;
11119 if (Cond.getOpcode() == ISD::SETCC) {
11120 // Check for setcc([su]{add,sub,mul}o == 0).
11121 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11122 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11123 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11124 Cond.getOperand(0).getResNo() == 1 &&
11125 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11126 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11127 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11128 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11129 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11130 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11132 Cond = Cond.getOperand(0);
11134 SDValue NewCond = LowerSETCC(Cond, DAG);
11135 if (NewCond.getNode())
11140 // FIXME: LowerXALUO doesn't handle these!!
11141 else if (Cond.getOpcode() == X86ISD::ADD ||
11142 Cond.getOpcode() == X86ISD::SUB ||
11143 Cond.getOpcode() == X86ISD::SMUL ||
11144 Cond.getOpcode() == X86ISD::UMUL)
11145 Cond = LowerXALUO(Cond, DAG);
11148 // Look pass (and (setcc_carry (cmp ...)), 1).
11149 if (Cond.getOpcode() == ISD::AND &&
11150 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11151 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11152 if (C && C->getAPIntValue() == 1)
11153 Cond = Cond.getOperand(0);
11156 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11157 // setting operand in place of the X86ISD::SETCC.
11158 unsigned CondOpcode = Cond.getOpcode();
11159 if (CondOpcode == X86ISD::SETCC ||
11160 CondOpcode == X86ISD::SETCC_CARRY) {
11161 CC = Cond.getOperand(0);
11163 SDValue Cmp = Cond.getOperand(1);
11164 unsigned Opc = Cmp.getOpcode();
11165 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11166 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11170 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11174 // These can only come from an arithmetic instruction with overflow,
11175 // e.g. SADDO, UADDO.
11176 Cond = Cond.getNode()->getOperand(1);
11182 CondOpcode = Cond.getOpcode();
11183 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11184 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11185 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11186 Cond.getOperand(0).getValueType() != MVT::i8)) {
11187 SDValue LHS = Cond.getOperand(0);
11188 SDValue RHS = Cond.getOperand(1);
11189 unsigned X86Opcode;
11192 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11193 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11195 switch (CondOpcode) {
11196 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11198 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11200 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11203 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11204 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11206 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11208 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11211 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11212 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11213 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11214 default: llvm_unreachable("unexpected overflowing operator");
11217 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11218 if (CondOpcode == ISD::UMULO)
11219 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11222 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11224 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11226 if (CondOpcode == ISD::UMULO)
11227 Cond = X86Op.getValue(2);
11229 Cond = X86Op.getValue(1);
11231 CC = DAG.getConstant(X86Cond, MVT::i8);
11235 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11236 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11237 if (CondOpc == ISD::OR) {
11238 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11239 // two branches instead of an explicit OR instruction with a
11241 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11242 isX86LogicalCmp(Cmp)) {
11243 CC = Cond.getOperand(0).getOperand(0);
11244 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11245 Chain, Dest, CC, Cmp);
11246 CC = Cond.getOperand(1).getOperand(0);
11250 } else { // ISD::AND
11251 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11252 // two branches instead of an explicit AND instruction with a
11253 // separate test. However, we only do this if this block doesn't
11254 // have a fall-through edge, because this requires an explicit
11255 // jmp when the condition is false.
11256 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11257 isX86LogicalCmp(Cmp) &&
11258 Op.getNode()->hasOneUse()) {
11259 X86::CondCode CCode =
11260 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11261 CCode = X86::GetOppositeBranchCondition(CCode);
11262 CC = DAG.getConstant(CCode, MVT::i8);
11263 SDNode *User = *Op.getNode()->use_begin();
11264 // Look for an unconditional branch following this conditional branch.
11265 // We need this because we need to reverse the successors in order
11266 // to implement FCMP_OEQ.
11267 if (User->getOpcode() == ISD::BR) {
11268 SDValue FalseBB = User->getOperand(1);
11270 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11271 assert(NewBR == User);
11275 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11276 Chain, Dest, CC, Cmp);
11277 X86::CondCode CCode =
11278 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11279 CCode = X86::GetOppositeBranchCondition(CCode);
11280 CC = DAG.getConstant(CCode, MVT::i8);
11286 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11287 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11288 // It should be transformed during dag combiner except when the condition
11289 // is set by a arithmetics with overflow node.
11290 X86::CondCode CCode =
11291 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11292 CCode = X86::GetOppositeBranchCondition(CCode);
11293 CC = DAG.getConstant(CCode, MVT::i8);
11294 Cond = Cond.getOperand(0).getOperand(1);
11296 } else if (Cond.getOpcode() == ISD::SETCC &&
11297 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11298 // For FCMP_OEQ, we can emit
11299 // two branches instead of an explicit AND instruction with a
11300 // separate test. However, we only do this if this block doesn't
11301 // have a fall-through edge, because this requires an explicit
11302 // jmp when the condition is false.
11303 if (Op.getNode()->hasOneUse()) {
11304 SDNode *User = *Op.getNode()->use_begin();
11305 // Look for an unconditional branch following this conditional branch.
11306 // We need this because we need to reverse the successors in order
11307 // to implement FCMP_OEQ.
11308 if (User->getOpcode() == ISD::BR) {
11309 SDValue FalseBB = User->getOperand(1);
11311 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11312 assert(NewBR == User);
11316 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11317 Cond.getOperand(0), Cond.getOperand(1));
11318 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11319 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11320 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11321 Chain, Dest, CC, Cmp);
11322 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11327 } else if (Cond.getOpcode() == ISD::SETCC &&
11328 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11329 // For FCMP_UNE, we can emit
11330 // two branches instead of an explicit AND instruction with a
11331 // separate test. However, we only do this if this block doesn't
11332 // have a fall-through edge, because this requires an explicit
11333 // jmp when the condition is false.
11334 if (Op.getNode()->hasOneUse()) {
11335 SDNode *User = *Op.getNode()->use_begin();
11336 // Look for an unconditional branch following this conditional branch.
11337 // We need this because we need to reverse the successors in order
11338 // to implement FCMP_UNE.
11339 if (User->getOpcode() == ISD::BR) {
11340 SDValue FalseBB = User->getOperand(1);
11342 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11343 assert(NewBR == User);
11346 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11347 Cond.getOperand(0), Cond.getOperand(1));
11348 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11349 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11350 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11351 Chain, Dest, CC, Cmp);
11352 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11362 // Look pass the truncate if the high bits are known zero.
11363 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11364 Cond = Cond.getOperand(0);
11366 // We know the result of AND is compared against zero. Try to match
11368 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11369 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11370 if (NewSetCC.getNode()) {
11371 CC = NewSetCC.getOperand(0);
11372 Cond = NewSetCC.getOperand(1);
11379 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11380 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11382 Cond = ConvertCmpIfNecessary(Cond, DAG);
11383 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11384 Chain, Dest, CC, Cond);
11387 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11388 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11389 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11390 // that the guard pages used by the OS virtual memory manager are allocated in
11391 // correct sequence.
11393 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11394 SelectionDAG &DAG) const {
11395 MachineFunction &MF = DAG.getMachineFunction();
11396 bool SplitStack = MF.shouldSplitStack();
11397 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11402 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11403 SDNode* Node = Op.getNode();
11405 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11406 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11407 " not tell us which reg is the stack pointer!");
11408 EVT VT = Node->getValueType(0);
11409 SDValue Tmp1 = SDValue(Node, 0);
11410 SDValue Tmp2 = SDValue(Node, 1);
11411 SDValue Tmp3 = Node->getOperand(2);
11412 SDValue Chain = Tmp1.getOperand(0);
11414 // Chain the dynamic stack allocation so that it doesn't modify the stack
11415 // pointer when other instructions are using the stack.
11416 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11419 SDValue Size = Tmp2.getOperand(1);
11420 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11421 Chain = SP.getValue(1);
11422 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11423 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11424 unsigned StackAlign = TFI.getStackAlignment();
11425 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11426 if (Align > StackAlign)
11427 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11428 DAG.getConstant(-(uint64_t)Align, VT));
11429 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11431 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11432 DAG.getIntPtrConstant(0, true), SDValue(),
11435 SDValue Ops[2] = { Tmp1, Tmp2 };
11436 return DAG.getMergeValues(Ops, dl);
11440 SDValue Chain = Op.getOperand(0);
11441 SDValue Size = Op.getOperand(1);
11442 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11443 EVT VT = Op.getNode()->getValueType(0);
11445 bool Is64Bit = Subtarget->is64Bit();
11446 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11449 MachineRegisterInfo &MRI = MF.getRegInfo();
11452 // The 64 bit implementation of segmented stacks needs to clobber both r10
11453 // r11. This makes it impossible to use it along with nested parameters.
11454 const Function *F = MF.getFunction();
11456 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11458 if (I->hasNestAttr())
11459 report_fatal_error("Cannot use segmented stacks with functions that "
11460 "have nested arguments.");
11463 const TargetRegisterClass *AddrRegClass =
11464 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11465 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11466 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11467 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11468 DAG.getRegister(Vreg, SPTy));
11469 SDValue Ops1[2] = { Value, Chain };
11470 return DAG.getMergeValues(Ops1, dl);
11473 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11475 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11476 Flag = Chain.getValue(1);
11477 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11479 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11481 const X86RegisterInfo *RegInfo =
11482 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11483 unsigned SPReg = RegInfo->getStackRegister();
11484 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11485 Chain = SP.getValue(1);
11488 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11489 DAG.getConstant(-(uint64_t)Align, VT));
11490 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11493 SDValue Ops1[2] = { SP, Chain };
11494 return DAG.getMergeValues(Ops1, dl);
11498 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11499 MachineFunction &MF = DAG.getMachineFunction();
11500 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11502 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11505 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11506 // vastart just stores the address of the VarArgsFrameIndex slot into the
11507 // memory location argument.
11508 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11510 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11511 MachinePointerInfo(SV), false, false, 0);
11515 // gp_offset (0 - 6 * 8)
11516 // fp_offset (48 - 48 + 8 * 16)
11517 // overflow_arg_area (point to parameters coming in memory).
11519 SmallVector<SDValue, 8> MemOps;
11520 SDValue FIN = Op.getOperand(1);
11522 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11523 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11525 FIN, MachinePointerInfo(SV), false, false, 0);
11526 MemOps.push_back(Store);
11529 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11530 FIN, DAG.getIntPtrConstant(4));
11531 Store = DAG.getStore(Op.getOperand(0), DL,
11532 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11534 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11535 MemOps.push_back(Store);
11537 // Store ptr to overflow_arg_area
11538 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11539 FIN, DAG.getIntPtrConstant(4));
11540 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11542 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11543 MachinePointerInfo(SV, 8),
11545 MemOps.push_back(Store);
11547 // Store ptr to reg_save_area.
11548 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11549 FIN, DAG.getIntPtrConstant(8));
11550 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11552 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11553 MachinePointerInfo(SV, 16), false, false, 0);
11554 MemOps.push_back(Store);
11555 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11558 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11559 assert(Subtarget->is64Bit() &&
11560 "LowerVAARG only handles 64-bit va_arg!");
11561 assert((Subtarget->isTargetLinux() ||
11562 Subtarget->isTargetDarwin()) &&
11563 "Unhandled target in LowerVAARG");
11564 assert(Op.getNode()->getNumOperands() == 4);
11565 SDValue Chain = Op.getOperand(0);
11566 SDValue SrcPtr = Op.getOperand(1);
11567 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11568 unsigned Align = Op.getConstantOperandVal(3);
11571 EVT ArgVT = Op.getNode()->getValueType(0);
11572 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11573 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11576 // Decide which area this value should be read from.
11577 // TODO: Implement the AMD64 ABI in its entirety. This simple
11578 // selection mechanism works only for the basic types.
11579 if (ArgVT == MVT::f80) {
11580 llvm_unreachable("va_arg for f80 not yet implemented");
11581 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11582 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11583 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11584 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11586 llvm_unreachable("Unhandled argument type in LowerVAARG");
11589 if (ArgMode == 2) {
11590 // Sanity Check: Make sure using fp_offset makes sense.
11591 assert(!getTargetMachine().Options.UseSoftFloat &&
11592 !(DAG.getMachineFunction()
11593 .getFunction()->getAttributes()
11594 .hasAttribute(AttributeSet::FunctionIndex,
11595 Attribute::NoImplicitFloat)) &&
11596 Subtarget->hasSSE1());
11599 // Insert VAARG_64 node into the DAG
11600 // VAARG_64 returns two values: Variable Argument Address, Chain
11601 SmallVector<SDValue, 11> InstOps;
11602 InstOps.push_back(Chain);
11603 InstOps.push_back(SrcPtr);
11604 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11605 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11606 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11607 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11608 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11609 VTs, InstOps, MVT::i64,
11610 MachinePointerInfo(SV),
11612 /*Volatile=*/false,
11614 /*WriteMem=*/true);
11615 Chain = VAARG.getValue(1);
11617 // Load the next argument and return it
11618 return DAG.getLoad(ArgVT, dl,
11621 MachinePointerInfo(),
11622 false, false, false, 0);
11625 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11626 SelectionDAG &DAG) {
11627 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11628 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11629 SDValue Chain = Op.getOperand(0);
11630 SDValue DstPtr = Op.getOperand(1);
11631 SDValue SrcPtr = Op.getOperand(2);
11632 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11633 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11636 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11637 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11639 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11642 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11643 // amount is a constant. Takes immediate version of shift as input.
11644 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11645 SDValue SrcOp, uint64_t ShiftAmt,
11646 SelectionDAG &DAG) {
11647 MVT ElementType = VT.getVectorElementType();
11649 // Fold this packed shift into its first operand if ShiftAmt is 0.
11653 // Check for ShiftAmt >= element width
11654 if (ShiftAmt >= ElementType.getSizeInBits()) {
11655 if (Opc == X86ISD::VSRAI)
11656 ShiftAmt = ElementType.getSizeInBits() - 1;
11658 return DAG.getConstant(0, VT);
11661 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11662 && "Unknown target vector shift-by-constant node");
11664 // Fold this packed vector shift into a build vector if SrcOp is a
11665 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11666 if (VT == SrcOp.getSimpleValueType() &&
11667 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11668 SmallVector<SDValue, 8> Elts;
11669 unsigned NumElts = SrcOp->getNumOperands();
11670 ConstantSDNode *ND;
11673 default: llvm_unreachable(nullptr);
11674 case X86ISD::VSHLI:
11675 for (unsigned i=0; i!=NumElts; ++i) {
11676 SDValue CurrentOp = SrcOp->getOperand(i);
11677 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11678 Elts.push_back(CurrentOp);
11681 ND = cast<ConstantSDNode>(CurrentOp);
11682 const APInt &C = ND->getAPIntValue();
11683 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11686 case X86ISD::VSRLI:
11687 for (unsigned i=0; i!=NumElts; ++i) {
11688 SDValue CurrentOp = SrcOp->getOperand(i);
11689 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11690 Elts.push_back(CurrentOp);
11693 ND = cast<ConstantSDNode>(CurrentOp);
11694 const APInt &C = ND->getAPIntValue();
11695 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11698 case X86ISD::VSRAI:
11699 for (unsigned i=0; i!=NumElts; ++i) {
11700 SDValue CurrentOp = SrcOp->getOperand(i);
11701 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11702 Elts.push_back(CurrentOp);
11705 ND = cast<ConstantSDNode>(CurrentOp);
11706 const APInt &C = ND->getAPIntValue();
11707 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11712 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11715 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11718 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11719 // may or may not be a constant. Takes immediate version of shift as input.
11720 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11721 SDValue SrcOp, SDValue ShAmt,
11722 SelectionDAG &DAG) {
11723 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11725 // Catch shift-by-constant.
11726 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11727 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11728 CShAmt->getZExtValue(), DAG);
11730 // Change opcode to non-immediate version
11732 default: llvm_unreachable("Unknown target vector shift node");
11733 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11734 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11735 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11738 // Need to build a vector containing shift amount
11739 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11742 ShOps[1] = DAG.getConstant(0, MVT::i32);
11743 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11744 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11746 // The return type has to be a 128-bit type with the same element
11747 // type as the input type.
11748 MVT EltVT = VT.getVectorElementType();
11749 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11751 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11752 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11755 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11757 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11759 default: return SDValue(); // Don't custom lower most intrinsics.
11760 // Comparison intrinsics.
11761 case Intrinsic::x86_sse_comieq_ss:
11762 case Intrinsic::x86_sse_comilt_ss:
11763 case Intrinsic::x86_sse_comile_ss:
11764 case Intrinsic::x86_sse_comigt_ss:
11765 case Intrinsic::x86_sse_comige_ss:
11766 case Intrinsic::x86_sse_comineq_ss:
11767 case Intrinsic::x86_sse_ucomieq_ss:
11768 case Intrinsic::x86_sse_ucomilt_ss:
11769 case Intrinsic::x86_sse_ucomile_ss:
11770 case Intrinsic::x86_sse_ucomigt_ss:
11771 case Intrinsic::x86_sse_ucomige_ss:
11772 case Intrinsic::x86_sse_ucomineq_ss:
11773 case Intrinsic::x86_sse2_comieq_sd:
11774 case Intrinsic::x86_sse2_comilt_sd:
11775 case Intrinsic::x86_sse2_comile_sd:
11776 case Intrinsic::x86_sse2_comigt_sd:
11777 case Intrinsic::x86_sse2_comige_sd:
11778 case Intrinsic::x86_sse2_comineq_sd:
11779 case Intrinsic::x86_sse2_ucomieq_sd:
11780 case Intrinsic::x86_sse2_ucomilt_sd:
11781 case Intrinsic::x86_sse2_ucomile_sd:
11782 case Intrinsic::x86_sse2_ucomigt_sd:
11783 case Intrinsic::x86_sse2_ucomige_sd:
11784 case Intrinsic::x86_sse2_ucomineq_sd: {
11788 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11789 case Intrinsic::x86_sse_comieq_ss:
11790 case Intrinsic::x86_sse2_comieq_sd:
11791 Opc = X86ISD::COMI;
11794 case Intrinsic::x86_sse_comilt_ss:
11795 case Intrinsic::x86_sse2_comilt_sd:
11796 Opc = X86ISD::COMI;
11799 case Intrinsic::x86_sse_comile_ss:
11800 case Intrinsic::x86_sse2_comile_sd:
11801 Opc = X86ISD::COMI;
11804 case Intrinsic::x86_sse_comigt_ss:
11805 case Intrinsic::x86_sse2_comigt_sd:
11806 Opc = X86ISD::COMI;
11809 case Intrinsic::x86_sse_comige_ss:
11810 case Intrinsic::x86_sse2_comige_sd:
11811 Opc = X86ISD::COMI;
11814 case Intrinsic::x86_sse_comineq_ss:
11815 case Intrinsic::x86_sse2_comineq_sd:
11816 Opc = X86ISD::COMI;
11819 case Intrinsic::x86_sse_ucomieq_ss:
11820 case Intrinsic::x86_sse2_ucomieq_sd:
11821 Opc = X86ISD::UCOMI;
11824 case Intrinsic::x86_sse_ucomilt_ss:
11825 case Intrinsic::x86_sse2_ucomilt_sd:
11826 Opc = X86ISD::UCOMI;
11829 case Intrinsic::x86_sse_ucomile_ss:
11830 case Intrinsic::x86_sse2_ucomile_sd:
11831 Opc = X86ISD::UCOMI;
11834 case Intrinsic::x86_sse_ucomigt_ss:
11835 case Intrinsic::x86_sse2_ucomigt_sd:
11836 Opc = X86ISD::UCOMI;
11839 case Intrinsic::x86_sse_ucomige_ss:
11840 case Intrinsic::x86_sse2_ucomige_sd:
11841 Opc = X86ISD::UCOMI;
11844 case Intrinsic::x86_sse_ucomineq_ss:
11845 case Intrinsic::x86_sse2_ucomineq_sd:
11846 Opc = X86ISD::UCOMI;
11851 SDValue LHS = Op.getOperand(1);
11852 SDValue RHS = Op.getOperand(2);
11853 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11854 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11855 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11856 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11857 DAG.getConstant(X86CC, MVT::i8), Cond);
11858 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11861 // Arithmetic intrinsics.
11862 case Intrinsic::x86_sse2_pmulu_dq:
11863 case Intrinsic::x86_avx2_pmulu_dq:
11864 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11865 Op.getOperand(1), Op.getOperand(2));
11867 case Intrinsic::x86_sse41_pmuldq:
11868 case Intrinsic::x86_avx2_pmul_dq:
11869 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11870 Op.getOperand(1), Op.getOperand(2));
11872 case Intrinsic::x86_sse2_pmulhu_w:
11873 case Intrinsic::x86_avx2_pmulhu_w:
11874 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11875 Op.getOperand(1), Op.getOperand(2));
11877 case Intrinsic::x86_sse2_pmulh_w:
11878 case Intrinsic::x86_avx2_pmulh_w:
11879 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11880 Op.getOperand(1), Op.getOperand(2));
11882 // SSE2/AVX2 sub with unsigned saturation intrinsics
11883 case Intrinsic::x86_sse2_psubus_b:
11884 case Intrinsic::x86_sse2_psubus_w:
11885 case Intrinsic::x86_avx2_psubus_b:
11886 case Intrinsic::x86_avx2_psubus_w:
11887 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11888 Op.getOperand(1), Op.getOperand(2));
11890 // SSE3/AVX horizontal add/sub intrinsics
11891 case Intrinsic::x86_sse3_hadd_ps:
11892 case Intrinsic::x86_sse3_hadd_pd:
11893 case Intrinsic::x86_avx_hadd_ps_256:
11894 case Intrinsic::x86_avx_hadd_pd_256:
11895 case Intrinsic::x86_sse3_hsub_ps:
11896 case Intrinsic::x86_sse3_hsub_pd:
11897 case Intrinsic::x86_avx_hsub_ps_256:
11898 case Intrinsic::x86_avx_hsub_pd_256:
11899 case Intrinsic::x86_ssse3_phadd_w_128:
11900 case Intrinsic::x86_ssse3_phadd_d_128:
11901 case Intrinsic::x86_avx2_phadd_w:
11902 case Intrinsic::x86_avx2_phadd_d:
11903 case Intrinsic::x86_ssse3_phsub_w_128:
11904 case Intrinsic::x86_ssse3_phsub_d_128:
11905 case Intrinsic::x86_avx2_phsub_w:
11906 case Intrinsic::x86_avx2_phsub_d: {
11909 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11910 case Intrinsic::x86_sse3_hadd_ps:
11911 case Intrinsic::x86_sse3_hadd_pd:
11912 case Intrinsic::x86_avx_hadd_ps_256:
11913 case Intrinsic::x86_avx_hadd_pd_256:
11914 Opcode = X86ISD::FHADD;
11916 case Intrinsic::x86_sse3_hsub_ps:
11917 case Intrinsic::x86_sse3_hsub_pd:
11918 case Intrinsic::x86_avx_hsub_ps_256:
11919 case Intrinsic::x86_avx_hsub_pd_256:
11920 Opcode = X86ISD::FHSUB;
11922 case Intrinsic::x86_ssse3_phadd_w_128:
11923 case Intrinsic::x86_ssse3_phadd_d_128:
11924 case Intrinsic::x86_avx2_phadd_w:
11925 case Intrinsic::x86_avx2_phadd_d:
11926 Opcode = X86ISD::HADD;
11928 case Intrinsic::x86_ssse3_phsub_w_128:
11929 case Intrinsic::x86_ssse3_phsub_d_128:
11930 case Intrinsic::x86_avx2_phsub_w:
11931 case Intrinsic::x86_avx2_phsub_d:
11932 Opcode = X86ISD::HSUB;
11935 return DAG.getNode(Opcode, dl, Op.getValueType(),
11936 Op.getOperand(1), Op.getOperand(2));
11939 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11940 case Intrinsic::x86_sse2_pmaxu_b:
11941 case Intrinsic::x86_sse41_pmaxuw:
11942 case Intrinsic::x86_sse41_pmaxud:
11943 case Intrinsic::x86_avx2_pmaxu_b:
11944 case Intrinsic::x86_avx2_pmaxu_w:
11945 case Intrinsic::x86_avx2_pmaxu_d:
11946 case Intrinsic::x86_sse2_pminu_b:
11947 case Intrinsic::x86_sse41_pminuw:
11948 case Intrinsic::x86_sse41_pminud:
11949 case Intrinsic::x86_avx2_pminu_b:
11950 case Intrinsic::x86_avx2_pminu_w:
11951 case Intrinsic::x86_avx2_pminu_d:
11952 case Intrinsic::x86_sse41_pmaxsb:
11953 case Intrinsic::x86_sse2_pmaxs_w:
11954 case Intrinsic::x86_sse41_pmaxsd:
11955 case Intrinsic::x86_avx2_pmaxs_b:
11956 case Intrinsic::x86_avx2_pmaxs_w:
11957 case Intrinsic::x86_avx2_pmaxs_d:
11958 case Intrinsic::x86_sse41_pminsb:
11959 case Intrinsic::x86_sse2_pmins_w:
11960 case Intrinsic::x86_sse41_pminsd:
11961 case Intrinsic::x86_avx2_pmins_b:
11962 case Intrinsic::x86_avx2_pmins_w:
11963 case Intrinsic::x86_avx2_pmins_d: {
11966 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11967 case Intrinsic::x86_sse2_pmaxu_b:
11968 case Intrinsic::x86_sse41_pmaxuw:
11969 case Intrinsic::x86_sse41_pmaxud:
11970 case Intrinsic::x86_avx2_pmaxu_b:
11971 case Intrinsic::x86_avx2_pmaxu_w:
11972 case Intrinsic::x86_avx2_pmaxu_d:
11973 Opcode = X86ISD::UMAX;
11975 case Intrinsic::x86_sse2_pminu_b:
11976 case Intrinsic::x86_sse41_pminuw:
11977 case Intrinsic::x86_sse41_pminud:
11978 case Intrinsic::x86_avx2_pminu_b:
11979 case Intrinsic::x86_avx2_pminu_w:
11980 case Intrinsic::x86_avx2_pminu_d:
11981 Opcode = X86ISD::UMIN;
11983 case Intrinsic::x86_sse41_pmaxsb:
11984 case Intrinsic::x86_sse2_pmaxs_w:
11985 case Intrinsic::x86_sse41_pmaxsd:
11986 case Intrinsic::x86_avx2_pmaxs_b:
11987 case Intrinsic::x86_avx2_pmaxs_w:
11988 case Intrinsic::x86_avx2_pmaxs_d:
11989 Opcode = X86ISD::SMAX;
11991 case Intrinsic::x86_sse41_pminsb:
11992 case Intrinsic::x86_sse2_pmins_w:
11993 case Intrinsic::x86_sse41_pminsd:
11994 case Intrinsic::x86_avx2_pmins_b:
11995 case Intrinsic::x86_avx2_pmins_w:
11996 case Intrinsic::x86_avx2_pmins_d:
11997 Opcode = X86ISD::SMIN;
12000 return DAG.getNode(Opcode, dl, Op.getValueType(),
12001 Op.getOperand(1), Op.getOperand(2));
12004 // SSE/SSE2/AVX floating point max/min intrinsics.
12005 case Intrinsic::x86_sse_max_ps:
12006 case Intrinsic::x86_sse2_max_pd:
12007 case Intrinsic::x86_avx_max_ps_256:
12008 case Intrinsic::x86_avx_max_pd_256:
12009 case Intrinsic::x86_sse_min_ps:
12010 case Intrinsic::x86_sse2_min_pd:
12011 case Intrinsic::x86_avx_min_ps_256:
12012 case Intrinsic::x86_avx_min_pd_256: {
12015 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12016 case Intrinsic::x86_sse_max_ps:
12017 case Intrinsic::x86_sse2_max_pd:
12018 case Intrinsic::x86_avx_max_ps_256:
12019 case Intrinsic::x86_avx_max_pd_256:
12020 Opcode = X86ISD::FMAX;
12022 case Intrinsic::x86_sse_min_ps:
12023 case Intrinsic::x86_sse2_min_pd:
12024 case Intrinsic::x86_avx_min_ps_256:
12025 case Intrinsic::x86_avx_min_pd_256:
12026 Opcode = X86ISD::FMIN;
12029 return DAG.getNode(Opcode, dl, Op.getValueType(),
12030 Op.getOperand(1), Op.getOperand(2));
12033 // AVX2 variable shift intrinsics
12034 case Intrinsic::x86_avx2_psllv_d:
12035 case Intrinsic::x86_avx2_psllv_q:
12036 case Intrinsic::x86_avx2_psllv_d_256:
12037 case Intrinsic::x86_avx2_psllv_q_256:
12038 case Intrinsic::x86_avx2_psrlv_d:
12039 case Intrinsic::x86_avx2_psrlv_q:
12040 case Intrinsic::x86_avx2_psrlv_d_256:
12041 case Intrinsic::x86_avx2_psrlv_q_256:
12042 case Intrinsic::x86_avx2_psrav_d:
12043 case Intrinsic::x86_avx2_psrav_d_256: {
12046 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12047 case Intrinsic::x86_avx2_psllv_d:
12048 case Intrinsic::x86_avx2_psllv_q:
12049 case Intrinsic::x86_avx2_psllv_d_256:
12050 case Intrinsic::x86_avx2_psllv_q_256:
12053 case Intrinsic::x86_avx2_psrlv_d:
12054 case Intrinsic::x86_avx2_psrlv_q:
12055 case Intrinsic::x86_avx2_psrlv_d_256:
12056 case Intrinsic::x86_avx2_psrlv_q_256:
12059 case Intrinsic::x86_avx2_psrav_d:
12060 case Intrinsic::x86_avx2_psrav_d_256:
12064 return DAG.getNode(Opcode, dl, Op.getValueType(),
12065 Op.getOperand(1), Op.getOperand(2));
12068 case Intrinsic::x86_ssse3_pshuf_b_128:
12069 case Intrinsic::x86_avx2_pshuf_b:
12070 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12071 Op.getOperand(1), Op.getOperand(2));
12073 case Intrinsic::x86_ssse3_psign_b_128:
12074 case Intrinsic::x86_ssse3_psign_w_128:
12075 case Intrinsic::x86_ssse3_psign_d_128:
12076 case Intrinsic::x86_avx2_psign_b:
12077 case Intrinsic::x86_avx2_psign_w:
12078 case Intrinsic::x86_avx2_psign_d:
12079 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12080 Op.getOperand(1), Op.getOperand(2));
12082 case Intrinsic::x86_sse41_insertps:
12083 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12084 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12086 case Intrinsic::x86_avx_vperm2f128_ps_256:
12087 case Intrinsic::x86_avx_vperm2f128_pd_256:
12088 case Intrinsic::x86_avx_vperm2f128_si_256:
12089 case Intrinsic::x86_avx2_vperm2i128:
12090 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12091 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12093 case Intrinsic::x86_avx2_permd:
12094 case Intrinsic::x86_avx2_permps:
12095 // Operands intentionally swapped. Mask is last operand to intrinsic,
12096 // but second operand for node/instruction.
12097 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12098 Op.getOperand(2), Op.getOperand(1));
12100 case Intrinsic::x86_sse_sqrt_ps:
12101 case Intrinsic::x86_sse2_sqrt_pd:
12102 case Intrinsic::x86_avx_sqrt_ps_256:
12103 case Intrinsic::x86_avx_sqrt_pd_256:
12104 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12106 // ptest and testp intrinsics. The intrinsic these come from are designed to
12107 // return an integer value, not just an instruction so lower it to the ptest
12108 // or testp pattern and a setcc for the result.
12109 case Intrinsic::x86_sse41_ptestz:
12110 case Intrinsic::x86_sse41_ptestc:
12111 case Intrinsic::x86_sse41_ptestnzc:
12112 case Intrinsic::x86_avx_ptestz_256:
12113 case Intrinsic::x86_avx_ptestc_256:
12114 case Intrinsic::x86_avx_ptestnzc_256:
12115 case Intrinsic::x86_avx_vtestz_ps:
12116 case Intrinsic::x86_avx_vtestc_ps:
12117 case Intrinsic::x86_avx_vtestnzc_ps:
12118 case Intrinsic::x86_avx_vtestz_pd:
12119 case Intrinsic::x86_avx_vtestc_pd:
12120 case Intrinsic::x86_avx_vtestnzc_pd:
12121 case Intrinsic::x86_avx_vtestz_ps_256:
12122 case Intrinsic::x86_avx_vtestc_ps_256:
12123 case Intrinsic::x86_avx_vtestnzc_ps_256:
12124 case Intrinsic::x86_avx_vtestz_pd_256:
12125 case Intrinsic::x86_avx_vtestc_pd_256:
12126 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12127 bool IsTestPacked = false;
12130 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12131 case Intrinsic::x86_avx_vtestz_ps:
12132 case Intrinsic::x86_avx_vtestz_pd:
12133 case Intrinsic::x86_avx_vtestz_ps_256:
12134 case Intrinsic::x86_avx_vtestz_pd_256:
12135 IsTestPacked = true; // Fallthrough
12136 case Intrinsic::x86_sse41_ptestz:
12137 case Intrinsic::x86_avx_ptestz_256:
12139 X86CC = X86::COND_E;
12141 case Intrinsic::x86_avx_vtestc_ps:
12142 case Intrinsic::x86_avx_vtestc_pd:
12143 case Intrinsic::x86_avx_vtestc_ps_256:
12144 case Intrinsic::x86_avx_vtestc_pd_256:
12145 IsTestPacked = true; // Fallthrough
12146 case Intrinsic::x86_sse41_ptestc:
12147 case Intrinsic::x86_avx_ptestc_256:
12149 X86CC = X86::COND_B;
12151 case Intrinsic::x86_avx_vtestnzc_ps:
12152 case Intrinsic::x86_avx_vtestnzc_pd:
12153 case Intrinsic::x86_avx_vtestnzc_ps_256:
12154 case Intrinsic::x86_avx_vtestnzc_pd_256:
12155 IsTestPacked = true; // Fallthrough
12156 case Intrinsic::x86_sse41_ptestnzc:
12157 case Intrinsic::x86_avx_ptestnzc_256:
12159 X86CC = X86::COND_A;
12163 SDValue LHS = Op.getOperand(1);
12164 SDValue RHS = Op.getOperand(2);
12165 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12166 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12167 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12168 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12169 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12171 case Intrinsic::x86_avx512_kortestz_w:
12172 case Intrinsic::x86_avx512_kortestc_w: {
12173 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12174 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12175 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12176 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12177 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12178 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12179 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12182 // SSE/AVX shift intrinsics
12183 case Intrinsic::x86_sse2_psll_w:
12184 case Intrinsic::x86_sse2_psll_d:
12185 case Intrinsic::x86_sse2_psll_q:
12186 case Intrinsic::x86_avx2_psll_w:
12187 case Intrinsic::x86_avx2_psll_d:
12188 case Intrinsic::x86_avx2_psll_q:
12189 case Intrinsic::x86_sse2_psrl_w:
12190 case Intrinsic::x86_sse2_psrl_d:
12191 case Intrinsic::x86_sse2_psrl_q:
12192 case Intrinsic::x86_avx2_psrl_w:
12193 case Intrinsic::x86_avx2_psrl_d:
12194 case Intrinsic::x86_avx2_psrl_q:
12195 case Intrinsic::x86_sse2_psra_w:
12196 case Intrinsic::x86_sse2_psra_d:
12197 case Intrinsic::x86_avx2_psra_w:
12198 case Intrinsic::x86_avx2_psra_d: {
12201 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12202 case Intrinsic::x86_sse2_psll_w:
12203 case Intrinsic::x86_sse2_psll_d:
12204 case Intrinsic::x86_sse2_psll_q:
12205 case Intrinsic::x86_avx2_psll_w:
12206 case Intrinsic::x86_avx2_psll_d:
12207 case Intrinsic::x86_avx2_psll_q:
12208 Opcode = X86ISD::VSHL;
12210 case Intrinsic::x86_sse2_psrl_w:
12211 case Intrinsic::x86_sse2_psrl_d:
12212 case Intrinsic::x86_sse2_psrl_q:
12213 case Intrinsic::x86_avx2_psrl_w:
12214 case Intrinsic::x86_avx2_psrl_d:
12215 case Intrinsic::x86_avx2_psrl_q:
12216 Opcode = X86ISD::VSRL;
12218 case Intrinsic::x86_sse2_psra_w:
12219 case Intrinsic::x86_sse2_psra_d:
12220 case Intrinsic::x86_avx2_psra_w:
12221 case Intrinsic::x86_avx2_psra_d:
12222 Opcode = X86ISD::VSRA;
12225 return DAG.getNode(Opcode, dl, Op.getValueType(),
12226 Op.getOperand(1), Op.getOperand(2));
12229 // SSE/AVX immediate shift intrinsics
12230 case Intrinsic::x86_sse2_pslli_w:
12231 case Intrinsic::x86_sse2_pslli_d:
12232 case Intrinsic::x86_sse2_pslli_q:
12233 case Intrinsic::x86_avx2_pslli_w:
12234 case Intrinsic::x86_avx2_pslli_d:
12235 case Intrinsic::x86_avx2_pslli_q:
12236 case Intrinsic::x86_sse2_psrli_w:
12237 case Intrinsic::x86_sse2_psrli_d:
12238 case Intrinsic::x86_sse2_psrli_q:
12239 case Intrinsic::x86_avx2_psrli_w:
12240 case Intrinsic::x86_avx2_psrli_d:
12241 case Intrinsic::x86_avx2_psrli_q:
12242 case Intrinsic::x86_sse2_psrai_w:
12243 case Intrinsic::x86_sse2_psrai_d:
12244 case Intrinsic::x86_avx2_psrai_w:
12245 case Intrinsic::x86_avx2_psrai_d: {
12248 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12249 case Intrinsic::x86_sse2_pslli_w:
12250 case Intrinsic::x86_sse2_pslli_d:
12251 case Intrinsic::x86_sse2_pslli_q:
12252 case Intrinsic::x86_avx2_pslli_w:
12253 case Intrinsic::x86_avx2_pslli_d:
12254 case Intrinsic::x86_avx2_pslli_q:
12255 Opcode = X86ISD::VSHLI;
12257 case Intrinsic::x86_sse2_psrli_w:
12258 case Intrinsic::x86_sse2_psrli_d:
12259 case Intrinsic::x86_sse2_psrli_q:
12260 case Intrinsic::x86_avx2_psrli_w:
12261 case Intrinsic::x86_avx2_psrli_d:
12262 case Intrinsic::x86_avx2_psrli_q:
12263 Opcode = X86ISD::VSRLI;
12265 case Intrinsic::x86_sse2_psrai_w:
12266 case Intrinsic::x86_sse2_psrai_d:
12267 case Intrinsic::x86_avx2_psrai_w:
12268 case Intrinsic::x86_avx2_psrai_d:
12269 Opcode = X86ISD::VSRAI;
12272 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12273 Op.getOperand(1), Op.getOperand(2), DAG);
12276 case Intrinsic::x86_sse42_pcmpistria128:
12277 case Intrinsic::x86_sse42_pcmpestria128:
12278 case Intrinsic::x86_sse42_pcmpistric128:
12279 case Intrinsic::x86_sse42_pcmpestric128:
12280 case Intrinsic::x86_sse42_pcmpistrio128:
12281 case Intrinsic::x86_sse42_pcmpestrio128:
12282 case Intrinsic::x86_sse42_pcmpistris128:
12283 case Intrinsic::x86_sse42_pcmpestris128:
12284 case Intrinsic::x86_sse42_pcmpistriz128:
12285 case Intrinsic::x86_sse42_pcmpestriz128: {
12289 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12290 case Intrinsic::x86_sse42_pcmpistria128:
12291 Opcode = X86ISD::PCMPISTRI;
12292 X86CC = X86::COND_A;
12294 case Intrinsic::x86_sse42_pcmpestria128:
12295 Opcode = X86ISD::PCMPESTRI;
12296 X86CC = X86::COND_A;
12298 case Intrinsic::x86_sse42_pcmpistric128:
12299 Opcode = X86ISD::PCMPISTRI;
12300 X86CC = X86::COND_B;
12302 case Intrinsic::x86_sse42_pcmpestric128:
12303 Opcode = X86ISD::PCMPESTRI;
12304 X86CC = X86::COND_B;
12306 case Intrinsic::x86_sse42_pcmpistrio128:
12307 Opcode = X86ISD::PCMPISTRI;
12308 X86CC = X86::COND_O;
12310 case Intrinsic::x86_sse42_pcmpestrio128:
12311 Opcode = X86ISD::PCMPESTRI;
12312 X86CC = X86::COND_O;
12314 case Intrinsic::x86_sse42_pcmpistris128:
12315 Opcode = X86ISD::PCMPISTRI;
12316 X86CC = X86::COND_S;
12318 case Intrinsic::x86_sse42_pcmpestris128:
12319 Opcode = X86ISD::PCMPESTRI;
12320 X86CC = X86::COND_S;
12322 case Intrinsic::x86_sse42_pcmpistriz128:
12323 Opcode = X86ISD::PCMPISTRI;
12324 X86CC = X86::COND_E;
12326 case Intrinsic::x86_sse42_pcmpestriz128:
12327 Opcode = X86ISD::PCMPESTRI;
12328 X86CC = X86::COND_E;
12331 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12332 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12333 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12334 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12335 DAG.getConstant(X86CC, MVT::i8),
12336 SDValue(PCMP.getNode(), 1));
12337 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12340 case Intrinsic::x86_sse42_pcmpistri128:
12341 case Intrinsic::x86_sse42_pcmpestri128: {
12343 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12344 Opcode = X86ISD::PCMPISTRI;
12346 Opcode = X86ISD::PCMPESTRI;
12348 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12349 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12350 return DAG.getNode(Opcode, dl, VTs, NewOps);
12352 case Intrinsic::x86_fma_vfmadd_ps:
12353 case Intrinsic::x86_fma_vfmadd_pd:
12354 case Intrinsic::x86_fma_vfmsub_ps:
12355 case Intrinsic::x86_fma_vfmsub_pd:
12356 case Intrinsic::x86_fma_vfnmadd_ps:
12357 case Intrinsic::x86_fma_vfnmadd_pd:
12358 case Intrinsic::x86_fma_vfnmsub_ps:
12359 case Intrinsic::x86_fma_vfnmsub_pd:
12360 case Intrinsic::x86_fma_vfmaddsub_ps:
12361 case Intrinsic::x86_fma_vfmaddsub_pd:
12362 case Intrinsic::x86_fma_vfmsubadd_ps:
12363 case Intrinsic::x86_fma_vfmsubadd_pd:
12364 case Intrinsic::x86_fma_vfmadd_ps_256:
12365 case Intrinsic::x86_fma_vfmadd_pd_256:
12366 case Intrinsic::x86_fma_vfmsub_ps_256:
12367 case Intrinsic::x86_fma_vfmsub_pd_256:
12368 case Intrinsic::x86_fma_vfnmadd_ps_256:
12369 case Intrinsic::x86_fma_vfnmadd_pd_256:
12370 case Intrinsic::x86_fma_vfnmsub_ps_256:
12371 case Intrinsic::x86_fma_vfnmsub_pd_256:
12372 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12373 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12374 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12375 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12376 case Intrinsic::x86_fma_vfmadd_ps_512:
12377 case Intrinsic::x86_fma_vfmadd_pd_512:
12378 case Intrinsic::x86_fma_vfmsub_ps_512:
12379 case Intrinsic::x86_fma_vfmsub_pd_512:
12380 case Intrinsic::x86_fma_vfnmadd_ps_512:
12381 case Intrinsic::x86_fma_vfnmadd_pd_512:
12382 case Intrinsic::x86_fma_vfnmsub_ps_512:
12383 case Intrinsic::x86_fma_vfnmsub_pd_512:
12384 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12385 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12386 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12387 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12390 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12391 case Intrinsic::x86_fma_vfmadd_ps:
12392 case Intrinsic::x86_fma_vfmadd_pd:
12393 case Intrinsic::x86_fma_vfmadd_ps_256:
12394 case Intrinsic::x86_fma_vfmadd_pd_256:
12395 case Intrinsic::x86_fma_vfmadd_ps_512:
12396 case Intrinsic::x86_fma_vfmadd_pd_512:
12397 Opc = X86ISD::FMADD;
12399 case Intrinsic::x86_fma_vfmsub_ps:
12400 case Intrinsic::x86_fma_vfmsub_pd:
12401 case Intrinsic::x86_fma_vfmsub_ps_256:
12402 case Intrinsic::x86_fma_vfmsub_pd_256:
12403 case Intrinsic::x86_fma_vfmsub_ps_512:
12404 case Intrinsic::x86_fma_vfmsub_pd_512:
12405 Opc = X86ISD::FMSUB;
12407 case Intrinsic::x86_fma_vfnmadd_ps:
12408 case Intrinsic::x86_fma_vfnmadd_pd:
12409 case Intrinsic::x86_fma_vfnmadd_ps_256:
12410 case Intrinsic::x86_fma_vfnmadd_pd_256:
12411 case Intrinsic::x86_fma_vfnmadd_ps_512:
12412 case Intrinsic::x86_fma_vfnmadd_pd_512:
12413 Opc = X86ISD::FNMADD;
12415 case Intrinsic::x86_fma_vfnmsub_ps:
12416 case Intrinsic::x86_fma_vfnmsub_pd:
12417 case Intrinsic::x86_fma_vfnmsub_ps_256:
12418 case Intrinsic::x86_fma_vfnmsub_pd_256:
12419 case Intrinsic::x86_fma_vfnmsub_ps_512:
12420 case Intrinsic::x86_fma_vfnmsub_pd_512:
12421 Opc = X86ISD::FNMSUB;
12423 case Intrinsic::x86_fma_vfmaddsub_ps:
12424 case Intrinsic::x86_fma_vfmaddsub_pd:
12425 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12426 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12427 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12428 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12429 Opc = X86ISD::FMADDSUB;
12431 case Intrinsic::x86_fma_vfmsubadd_ps:
12432 case Intrinsic::x86_fma_vfmsubadd_pd:
12433 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12434 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12435 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12436 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12437 Opc = X86ISD::FMSUBADD;
12441 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12442 Op.getOperand(2), Op.getOperand(3));
12447 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12448 SDValue Src, SDValue Mask, SDValue Base,
12449 SDValue Index, SDValue ScaleOp, SDValue Chain,
12450 const X86Subtarget * Subtarget) {
12452 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12453 assert(C && "Invalid scale type");
12454 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12455 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12456 Index.getSimpleValueType().getVectorNumElements());
12458 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12460 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12462 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12463 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12464 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12465 SDValue Segment = DAG.getRegister(0, MVT::i32);
12466 if (Src.getOpcode() == ISD::UNDEF)
12467 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12468 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12469 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12470 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12471 return DAG.getMergeValues(RetOps, dl);
12474 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12475 SDValue Src, SDValue Mask, SDValue Base,
12476 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12478 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12479 assert(C && "Invalid scale type");
12480 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12481 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12482 SDValue Segment = DAG.getRegister(0, MVT::i32);
12483 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12484 Index.getSimpleValueType().getVectorNumElements());
12486 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12488 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12490 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12491 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12492 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12493 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12494 return SDValue(Res, 1);
12497 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12498 SDValue Mask, SDValue Base, SDValue Index,
12499 SDValue ScaleOp, SDValue Chain) {
12501 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12502 assert(C && "Invalid scale type");
12503 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12504 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12505 SDValue Segment = DAG.getRegister(0, MVT::i32);
12507 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12509 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12511 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12513 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12514 //SDVTList VTs = DAG.getVTList(MVT::Other);
12515 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12516 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12517 return SDValue(Res, 0);
12520 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12521 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12522 // also used to custom lower READCYCLECOUNTER nodes.
12523 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12524 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12525 SmallVectorImpl<SDValue> &Results) {
12526 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12527 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12530 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12531 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12532 // and the EAX register is loaded with the low-order 32 bits.
12533 if (Subtarget->is64Bit()) {
12534 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12535 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12538 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12539 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12542 SDValue Chain = HI.getValue(1);
12544 if (Opcode == X86ISD::RDTSCP_DAG) {
12545 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12547 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12548 // the ECX register. Add 'ecx' explicitly to the chain.
12549 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12551 // Explicitly store the content of ECX at the location passed in input
12552 // to the 'rdtscp' intrinsic.
12553 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12554 MachinePointerInfo(), false, false, 0);
12557 if (Subtarget->is64Bit()) {
12558 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12559 // the EAX register is loaded with the low-order 32 bits.
12560 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12561 DAG.getConstant(32, MVT::i8));
12562 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12563 Results.push_back(Chain);
12567 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12568 SDValue Ops[] = { LO, HI };
12569 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12570 Results.push_back(Pair);
12571 Results.push_back(Chain);
12574 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12575 SelectionDAG &DAG) {
12576 SmallVector<SDValue, 2> Results;
12578 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12580 return DAG.getMergeValues(Results, DL);
12583 enum IntrinsicType {
12584 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12587 struct IntrinsicData {
12588 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12589 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12590 IntrinsicType Type;
12595 std::map < unsigned, IntrinsicData> IntrMap;
12596 static void InitIntinsicsMap() {
12597 static bool Initialized = false;
12600 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12601 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12602 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12603 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12604 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12605 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12606 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12607 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12608 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12609 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12610 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
12611 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12612 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
12613 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12614 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
12615 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12616 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
12617 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12619 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12620 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12621 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
12622 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12623 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
12624 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12625 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
12626 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12627 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
12628 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12629 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
12630 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12631 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
12632 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12633 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
12634 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12636 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
12637 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12638 X86::VGATHERPF1QPSm)));
12639 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
12640 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12641 X86::VGATHERPF1QPDm)));
12642 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
12643 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12644 X86::VGATHERPF1DPDm)));
12645 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
12646 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12647 X86::VGATHERPF1DPSm)));
12648 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
12649 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12650 X86::VSCATTERPF1QPSm)));
12651 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
12652 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12653 X86::VSCATTERPF1QPDm)));
12654 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
12655 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12656 X86::VSCATTERPF1DPDm)));
12657 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
12658 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12659 X86::VSCATTERPF1DPSm)));
12660 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12661 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12662 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12663 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12664 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12665 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12666 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12667 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12668 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12669 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12670 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12671 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12672 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12673 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
12674 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12675 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
12676 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12677 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
12678 Initialized = true;
12681 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12682 SelectionDAG &DAG) {
12683 InitIntinsicsMap();
12684 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12685 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12686 if (itr == IntrMap.end())
12690 IntrinsicData Intr = itr->second;
12691 switch(Intr.Type) {
12694 // Emit the node with the right value type.
12695 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12696 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12698 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12699 // Otherwise return the value from Rand, which is always 0, casted to i32.
12700 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12701 DAG.getConstant(1, Op->getValueType(1)),
12702 DAG.getConstant(X86::COND_B, MVT::i32),
12703 SDValue(Result.getNode(), 1) };
12704 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12705 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12708 // Return { result, isValid, chain }.
12709 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12710 SDValue(Result.getNode(), 2));
12713 //gather(v1, mask, index, base, scale);
12714 SDValue Chain = Op.getOperand(0);
12715 SDValue Src = Op.getOperand(2);
12716 SDValue Base = Op.getOperand(3);
12717 SDValue Index = Op.getOperand(4);
12718 SDValue Mask = Op.getOperand(5);
12719 SDValue Scale = Op.getOperand(6);
12720 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12724 //scatter(base, mask, index, v1, scale);
12725 SDValue Chain = Op.getOperand(0);
12726 SDValue Base = Op.getOperand(2);
12727 SDValue Mask = Op.getOperand(3);
12728 SDValue Index = Op.getOperand(4);
12729 SDValue Src = Op.getOperand(5);
12730 SDValue Scale = Op.getOperand(6);
12731 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12734 SDValue Hint = Op.getOperand(6);
12736 if (dyn_cast<ConstantSDNode> (Hint) == 0 ||
12737 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12738 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12739 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12740 SDValue Chain = Op.getOperand(0);
12741 SDValue Mask = Op.getOperand(2);
12742 SDValue Index = Op.getOperand(3);
12743 SDValue Base = Op.getOperand(4);
12744 SDValue Scale = Op.getOperand(5);
12745 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12747 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12749 SmallVector<SDValue, 2> Results;
12750 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12751 return DAG.getMergeValues(Results, dl);
12753 // XTEST intrinsics.
12755 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12756 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12757 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12758 DAG.getConstant(X86::COND_NE, MVT::i8),
12760 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12761 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12762 Ret, SDValue(InTrans.getNode(), 1));
12765 llvm_unreachable("Unknown Intrinsic Type");
12768 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12769 SelectionDAG &DAG) const {
12770 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12771 MFI->setReturnAddressIsTaken(true);
12773 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12776 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12778 EVT PtrVT = getPointerTy();
12781 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12782 const X86RegisterInfo *RegInfo =
12783 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12784 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12785 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12786 DAG.getNode(ISD::ADD, dl, PtrVT,
12787 FrameAddr, Offset),
12788 MachinePointerInfo(), false, false, false, 0);
12791 // Just load the return address.
12792 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12793 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12794 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12797 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12798 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12799 MFI->setFrameAddressIsTaken(true);
12801 EVT VT = Op.getValueType();
12802 SDLoc dl(Op); // FIXME probably not meaningful
12803 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12804 const X86RegisterInfo *RegInfo =
12805 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12806 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12807 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12808 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12809 "Invalid Frame Register!");
12810 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12812 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12813 MachinePointerInfo(),
12814 false, false, false, 0);
12818 // FIXME? Maybe this could be a TableGen attribute on some registers and
12819 // this table could be generated automatically from RegInfo.
12820 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12822 unsigned Reg = StringSwitch<unsigned>(RegName)
12823 .Case("esp", X86::ESP)
12824 .Case("rsp", X86::RSP)
12828 report_fatal_error("Invalid register name global variable");
12831 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12832 SelectionDAG &DAG) const {
12833 const X86RegisterInfo *RegInfo =
12834 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12835 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12838 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12839 SDValue Chain = Op.getOperand(0);
12840 SDValue Offset = Op.getOperand(1);
12841 SDValue Handler = Op.getOperand(2);
12844 EVT PtrVT = getPointerTy();
12845 const X86RegisterInfo *RegInfo =
12846 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12847 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12848 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12849 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12850 "Invalid Frame Register!");
12851 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12852 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12854 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12855 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12856 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12857 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12859 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12861 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12862 DAG.getRegister(StoreAddrReg, PtrVT));
12865 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12866 SelectionDAG &DAG) const {
12868 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12869 DAG.getVTList(MVT::i32, MVT::Other),
12870 Op.getOperand(0), Op.getOperand(1));
12873 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12874 SelectionDAG &DAG) const {
12876 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12877 Op.getOperand(0), Op.getOperand(1));
12880 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12881 return Op.getOperand(0);
12884 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12885 SelectionDAG &DAG) const {
12886 SDValue Root = Op.getOperand(0);
12887 SDValue Trmp = Op.getOperand(1); // trampoline
12888 SDValue FPtr = Op.getOperand(2); // nested function
12889 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12892 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12893 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12895 if (Subtarget->is64Bit()) {
12896 SDValue OutChains[6];
12898 // Large code-model.
12899 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12900 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12902 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12903 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12905 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12907 // Load the pointer to the nested function into R11.
12908 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12909 SDValue Addr = Trmp;
12910 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12911 Addr, MachinePointerInfo(TrmpAddr),
12914 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12915 DAG.getConstant(2, MVT::i64));
12916 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12917 MachinePointerInfo(TrmpAddr, 2),
12920 // Load the 'nest' parameter value into R10.
12921 // R10 is specified in X86CallingConv.td
12922 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12923 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12924 DAG.getConstant(10, MVT::i64));
12925 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12926 Addr, MachinePointerInfo(TrmpAddr, 10),
12929 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12930 DAG.getConstant(12, MVT::i64));
12931 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12932 MachinePointerInfo(TrmpAddr, 12),
12935 // Jump to the nested function.
12936 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12937 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12938 DAG.getConstant(20, MVT::i64));
12939 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12940 Addr, MachinePointerInfo(TrmpAddr, 20),
12943 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12944 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12945 DAG.getConstant(22, MVT::i64));
12946 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12947 MachinePointerInfo(TrmpAddr, 22),
12950 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12952 const Function *Func =
12953 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12954 CallingConv::ID CC = Func->getCallingConv();
12959 llvm_unreachable("Unsupported calling convention");
12960 case CallingConv::C:
12961 case CallingConv::X86_StdCall: {
12962 // Pass 'nest' parameter in ECX.
12963 // Must be kept in sync with X86CallingConv.td
12964 NestReg = X86::ECX;
12966 // Check that ECX wasn't needed by an 'inreg' parameter.
12967 FunctionType *FTy = Func->getFunctionType();
12968 const AttributeSet &Attrs = Func->getAttributes();
12970 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12971 unsigned InRegCount = 0;
12974 for (FunctionType::param_iterator I = FTy->param_begin(),
12975 E = FTy->param_end(); I != E; ++I, ++Idx)
12976 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12977 // FIXME: should only count parameters that are lowered to integers.
12978 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12980 if (InRegCount > 2) {
12981 report_fatal_error("Nest register in use - reduce number of inreg"
12987 case CallingConv::X86_FastCall:
12988 case CallingConv::X86_ThisCall:
12989 case CallingConv::Fast:
12990 // Pass 'nest' parameter in EAX.
12991 // Must be kept in sync with X86CallingConv.td
12992 NestReg = X86::EAX;
12996 SDValue OutChains[4];
12997 SDValue Addr, Disp;
12999 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13000 DAG.getConstant(10, MVT::i32));
13001 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13003 // This is storing the opcode for MOV32ri.
13004 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13005 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13006 OutChains[0] = DAG.getStore(Root, dl,
13007 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13008 Trmp, MachinePointerInfo(TrmpAddr),
13011 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13012 DAG.getConstant(1, MVT::i32));
13013 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13014 MachinePointerInfo(TrmpAddr, 1),
13017 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13018 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13019 DAG.getConstant(5, MVT::i32));
13020 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13021 MachinePointerInfo(TrmpAddr, 5),
13024 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13025 DAG.getConstant(6, MVT::i32));
13026 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13027 MachinePointerInfo(TrmpAddr, 6),
13030 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13034 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13035 SelectionDAG &DAG) const {
13037 The rounding mode is in bits 11:10 of FPSR, and has the following
13039 00 Round to nearest
13044 FLT_ROUNDS, on the other hand, expects the following:
13051 To perform the conversion, we do:
13052 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13055 MachineFunction &MF = DAG.getMachineFunction();
13056 const TargetMachine &TM = MF.getTarget();
13057 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13058 unsigned StackAlignment = TFI.getStackAlignment();
13059 MVT VT = Op.getSimpleValueType();
13062 // Save FP Control Word to stack slot
13063 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13064 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13066 MachineMemOperand *MMO =
13067 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13068 MachineMemOperand::MOStore, 2, 2);
13070 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13071 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13072 DAG.getVTList(MVT::Other),
13073 Ops, MVT::i16, MMO);
13075 // Load FP Control Word from stack slot
13076 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13077 MachinePointerInfo(), false, false, false, 0);
13079 // Transform as necessary
13081 DAG.getNode(ISD::SRL, DL, MVT::i16,
13082 DAG.getNode(ISD::AND, DL, MVT::i16,
13083 CWD, DAG.getConstant(0x800, MVT::i16)),
13084 DAG.getConstant(11, MVT::i8));
13086 DAG.getNode(ISD::SRL, DL, MVT::i16,
13087 DAG.getNode(ISD::AND, DL, MVT::i16,
13088 CWD, DAG.getConstant(0x400, MVT::i16)),
13089 DAG.getConstant(9, MVT::i8));
13092 DAG.getNode(ISD::AND, DL, MVT::i16,
13093 DAG.getNode(ISD::ADD, DL, MVT::i16,
13094 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13095 DAG.getConstant(1, MVT::i16)),
13096 DAG.getConstant(3, MVT::i16));
13098 return DAG.getNode((VT.getSizeInBits() < 16 ?
13099 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13102 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13103 MVT VT = Op.getSimpleValueType();
13105 unsigned NumBits = VT.getSizeInBits();
13108 Op = Op.getOperand(0);
13109 if (VT == MVT::i8) {
13110 // Zero extend to i32 since there is not an i8 bsr.
13112 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13115 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13116 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13117 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13119 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13122 DAG.getConstant(NumBits+NumBits-1, OpVT),
13123 DAG.getConstant(X86::COND_E, MVT::i8),
13126 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13128 // Finally xor with NumBits-1.
13129 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13132 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13136 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13137 MVT VT = Op.getSimpleValueType();
13139 unsigned NumBits = VT.getSizeInBits();
13142 Op = Op.getOperand(0);
13143 if (VT == MVT::i8) {
13144 // Zero extend to i32 since there is not an i8 bsr.
13146 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13149 // Issue a bsr (scan bits in reverse).
13150 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13151 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13153 // And xor with NumBits-1.
13154 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13157 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13161 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13162 MVT VT = Op.getSimpleValueType();
13163 unsigned NumBits = VT.getSizeInBits();
13165 Op = Op.getOperand(0);
13167 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13168 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13169 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13171 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13174 DAG.getConstant(NumBits, VT),
13175 DAG.getConstant(X86::COND_E, MVT::i8),
13178 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13181 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13182 // ones, and then concatenate the result back.
13183 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13184 MVT VT = Op.getSimpleValueType();
13186 assert(VT.is256BitVector() && VT.isInteger() &&
13187 "Unsupported value type for operation");
13189 unsigned NumElems = VT.getVectorNumElements();
13192 // Extract the LHS vectors
13193 SDValue LHS = Op.getOperand(0);
13194 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13195 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13197 // Extract the RHS vectors
13198 SDValue RHS = Op.getOperand(1);
13199 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13200 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13202 MVT EltVT = VT.getVectorElementType();
13203 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13205 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13206 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13207 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13210 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13211 assert(Op.getSimpleValueType().is256BitVector() &&
13212 Op.getSimpleValueType().isInteger() &&
13213 "Only handle AVX 256-bit vector integer operation");
13214 return Lower256IntArith(Op, DAG);
13217 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13218 assert(Op.getSimpleValueType().is256BitVector() &&
13219 Op.getSimpleValueType().isInteger() &&
13220 "Only handle AVX 256-bit vector integer operation");
13221 return Lower256IntArith(Op, DAG);
13224 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13225 SelectionDAG &DAG) {
13227 MVT VT = Op.getSimpleValueType();
13229 // Decompose 256-bit ops into smaller 128-bit ops.
13230 if (VT.is256BitVector() && !Subtarget->hasInt256())
13231 return Lower256IntArith(Op, DAG);
13233 SDValue A = Op.getOperand(0);
13234 SDValue B = Op.getOperand(1);
13236 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13237 if (VT == MVT::v4i32) {
13238 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13239 "Should not custom lower when pmuldq is available!");
13241 // Extract the odd parts.
13242 static const int UnpackMask[] = { 1, -1, 3, -1 };
13243 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13244 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13246 // Multiply the even parts.
13247 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13248 // Now multiply odd parts.
13249 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13251 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13252 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13254 // Merge the two vectors back together with a shuffle. This expands into 2
13256 static const int ShufMask[] = { 0, 4, 2, 6 };
13257 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13260 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13261 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13263 // Ahi = psrlqi(a, 32);
13264 // Bhi = psrlqi(b, 32);
13266 // AloBlo = pmuludq(a, b);
13267 // AloBhi = pmuludq(a, Bhi);
13268 // AhiBlo = pmuludq(Ahi, b);
13270 // AloBhi = psllqi(AloBhi, 32);
13271 // AhiBlo = psllqi(AhiBlo, 32);
13272 // return AloBlo + AloBhi + AhiBlo;
13274 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13275 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13277 // Bit cast to 32-bit vectors for MULUDQ
13278 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13279 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13280 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13281 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13282 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13283 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13285 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13286 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13287 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13289 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13290 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13292 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13293 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13296 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13297 assert(Subtarget->isTargetWin64() && "Unexpected target");
13298 EVT VT = Op.getValueType();
13299 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13300 "Unexpected return type for lowering");
13304 switch (Op->getOpcode()) {
13305 default: llvm_unreachable("Unexpected request for libcall!");
13306 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13307 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13308 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13309 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13310 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13311 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13315 SDValue InChain = DAG.getEntryNode();
13317 TargetLowering::ArgListTy Args;
13318 TargetLowering::ArgListEntry Entry;
13319 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13320 EVT ArgVT = Op->getOperand(i).getValueType();
13321 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13322 "Unexpected argument type for lowering");
13323 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13324 Entry.Node = StackPtr;
13325 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13327 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13328 Entry.Ty = PointerType::get(ArgTy,0);
13329 Entry.isSExt = false;
13330 Entry.isZExt = false;
13331 Args.push_back(Entry);
13334 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13337 TargetLowering::CallLoweringInfo CLI(
13338 InChain, static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13339 isSigned, !isSigned, false, true, 0, getLibcallCallingConv(LC),
13340 /*isTailCall=*/false,
13341 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, Callee, Args, DAG,
13343 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13345 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13348 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13349 SelectionDAG &DAG) {
13350 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13351 EVT VT = Op0.getValueType();
13354 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13355 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13357 // Get the high parts.
13358 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13359 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13360 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13362 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13364 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13365 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13367 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13368 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13369 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13370 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13371 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13373 // Shuffle it back into the right order.
13374 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13375 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13376 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13377 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13379 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13380 // unsigned multiply.
13381 if (IsSigned && !Subtarget->hasSSE41()) {
13383 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13384 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13385 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13386 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13387 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13389 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13390 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13393 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13396 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13397 const X86Subtarget *Subtarget) {
13398 MVT VT = Op.getSimpleValueType();
13400 SDValue R = Op.getOperand(0);
13401 SDValue Amt = Op.getOperand(1);
13403 // Optimize shl/srl/sra with constant shift amount.
13404 if (isSplatVector(Amt.getNode())) {
13405 SDValue SclrAmt = Amt->getOperand(0);
13406 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13407 uint64_t ShiftAmt = C->getZExtValue();
13409 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13410 (Subtarget->hasInt256() &&
13411 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13412 (Subtarget->hasAVX512() &&
13413 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13414 if (Op.getOpcode() == ISD::SHL)
13415 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13417 if (Op.getOpcode() == ISD::SRL)
13418 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13420 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13421 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13425 if (VT == MVT::v16i8) {
13426 if (Op.getOpcode() == ISD::SHL) {
13427 // Make a large shift.
13428 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13429 MVT::v8i16, R, ShiftAmt,
13431 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13432 // Zero out the rightmost bits.
13433 SmallVector<SDValue, 16> V(16,
13434 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13436 return DAG.getNode(ISD::AND, dl, VT, SHL,
13437 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13439 if (Op.getOpcode() == ISD::SRL) {
13440 // Make a large shift.
13441 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13442 MVT::v8i16, R, ShiftAmt,
13444 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13445 // Zero out the leftmost bits.
13446 SmallVector<SDValue, 16> V(16,
13447 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13449 return DAG.getNode(ISD::AND, dl, VT, SRL,
13450 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13452 if (Op.getOpcode() == ISD::SRA) {
13453 if (ShiftAmt == 7) {
13454 // R s>> 7 === R s< 0
13455 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13456 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13459 // R s>> a === ((R u>> a) ^ m) - m
13460 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13461 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13463 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13464 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13465 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13468 llvm_unreachable("Unknown shift opcode.");
13471 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13472 if (Op.getOpcode() == ISD::SHL) {
13473 // Make a large shift.
13474 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13475 MVT::v16i16, R, ShiftAmt,
13477 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13478 // Zero out the rightmost bits.
13479 SmallVector<SDValue, 32> V(32,
13480 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13482 return DAG.getNode(ISD::AND, dl, VT, SHL,
13483 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13485 if (Op.getOpcode() == ISD::SRL) {
13486 // Make a large shift.
13487 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13488 MVT::v16i16, R, ShiftAmt,
13490 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13491 // Zero out the leftmost bits.
13492 SmallVector<SDValue, 32> V(32,
13493 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13495 return DAG.getNode(ISD::AND, dl, VT, SRL,
13496 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13498 if (Op.getOpcode() == ISD::SRA) {
13499 if (ShiftAmt == 7) {
13500 // R s>> 7 === R s< 0
13501 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13502 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13505 // R s>> a === ((R u>> a) ^ m) - m
13506 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13507 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13509 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13510 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13511 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13514 llvm_unreachable("Unknown shift opcode.");
13519 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13520 if (!Subtarget->is64Bit() &&
13521 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13522 Amt.getOpcode() == ISD::BITCAST &&
13523 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13524 Amt = Amt.getOperand(0);
13525 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13526 VT.getVectorNumElements();
13527 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13528 uint64_t ShiftAmt = 0;
13529 for (unsigned i = 0; i != Ratio; ++i) {
13530 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13534 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13536 // Check remaining shift amounts.
13537 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13538 uint64_t ShAmt = 0;
13539 for (unsigned j = 0; j != Ratio; ++j) {
13540 ConstantSDNode *C =
13541 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13545 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13547 if (ShAmt != ShiftAmt)
13550 switch (Op.getOpcode()) {
13552 llvm_unreachable("Unknown shift opcode!");
13554 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13557 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13560 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13568 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13569 const X86Subtarget* Subtarget) {
13570 MVT VT = Op.getSimpleValueType();
13572 SDValue R = Op.getOperand(0);
13573 SDValue Amt = Op.getOperand(1);
13575 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13576 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13577 (Subtarget->hasInt256() &&
13578 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13579 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13580 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13582 EVT EltVT = VT.getVectorElementType();
13584 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13585 unsigned NumElts = VT.getVectorNumElements();
13587 for (i = 0; i != NumElts; ++i) {
13588 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13592 for (j = i; j != NumElts; ++j) {
13593 SDValue Arg = Amt.getOperand(j);
13594 if (Arg.getOpcode() == ISD::UNDEF) continue;
13595 if (Arg != Amt.getOperand(i))
13598 if (i != NumElts && j == NumElts)
13599 BaseShAmt = Amt.getOperand(i);
13601 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13602 Amt = Amt.getOperand(0);
13603 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13604 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13605 SDValue InVec = Amt.getOperand(0);
13606 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13607 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13609 for (; i != NumElts; ++i) {
13610 SDValue Arg = InVec.getOperand(i);
13611 if (Arg.getOpcode() == ISD::UNDEF) continue;
13615 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13616 if (ConstantSDNode *C =
13617 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13618 unsigned SplatIdx =
13619 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13620 if (C->getZExtValue() == SplatIdx)
13621 BaseShAmt = InVec.getOperand(1);
13624 if (!BaseShAmt.getNode())
13625 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13626 DAG.getIntPtrConstant(0));
13630 if (BaseShAmt.getNode()) {
13631 if (EltVT.bitsGT(MVT::i32))
13632 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13633 else if (EltVT.bitsLT(MVT::i32))
13634 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13636 switch (Op.getOpcode()) {
13638 llvm_unreachable("Unknown shift opcode!");
13640 switch (VT.SimpleTy) {
13641 default: return SDValue();
13650 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13653 switch (VT.SimpleTy) {
13654 default: return SDValue();
13661 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13664 switch (VT.SimpleTy) {
13665 default: return SDValue();
13674 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13680 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13681 if (!Subtarget->is64Bit() &&
13682 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13683 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13684 Amt.getOpcode() == ISD::BITCAST &&
13685 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13686 Amt = Amt.getOperand(0);
13687 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13688 VT.getVectorNumElements();
13689 std::vector<SDValue> Vals(Ratio);
13690 for (unsigned i = 0; i != Ratio; ++i)
13691 Vals[i] = Amt.getOperand(i);
13692 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13693 for (unsigned j = 0; j != Ratio; ++j)
13694 if (Vals[j] != Amt.getOperand(i + j))
13697 switch (Op.getOpcode()) {
13699 llvm_unreachable("Unknown shift opcode!");
13701 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13703 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13705 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13712 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13713 SelectionDAG &DAG) {
13715 MVT VT = Op.getSimpleValueType();
13717 SDValue R = Op.getOperand(0);
13718 SDValue Amt = Op.getOperand(1);
13721 if (!Subtarget->hasSSE2())
13724 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13728 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13732 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13734 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13735 if (Subtarget->hasInt256()) {
13736 if (Op.getOpcode() == ISD::SRL &&
13737 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13738 VT == MVT::v4i64 || VT == MVT::v8i32))
13740 if (Op.getOpcode() == ISD::SHL &&
13741 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13742 VT == MVT::v4i64 || VT == MVT::v8i32))
13744 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13748 // If possible, lower this packed shift into a vector multiply instead of
13749 // expanding it into a sequence of scalar shifts.
13750 // Do this only if the vector shift count is a constant build_vector.
13751 if (Op.getOpcode() == ISD::SHL &&
13752 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13753 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13754 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13755 SmallVector<SDValue, 8> Elts;
13756 EVT SVT = VT.getScalarType();
13757 unsigned SVTBits = SVT.getSizeInBits();
13758 const APInt &One = APInt(SVTBits, 1);
13759 unsigned NumElems = VT.getVectorNumElements();
13761 for (unsigned i=0; i !=NumElems; ++i) {
13762 SDValue Op = Amt->getOperand(i);
13763 if (Op->getOpcode() == ISD::UNDEF) {
13764 Elts.push_back(Op);
13768 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13769 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13770 uint64_t ShAmt = C.getZExtValue();
13771 if (ShAmt >= SVTBits) {
13772 Elts.push_back(DAG.getUNDEF(SVT));
13775 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13777 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13778 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13781 // Lower SHL with variable shift amount.
13782 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13783 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13785 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13786 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13787 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13788 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13791 // If possible, lower this shift as a sequence of two shifts by
13792 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13794 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13796 // Could be rewritten as:
13797 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13799 // The advantage is that the two shifts from the example would be
13800 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13801 // the vector shift into four scalar shifts plus four pairs of vector
13803 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13804 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13805 unsigned TargetOpcode = X86ISD::MOVSS;
13806 bool CanBeSimplified;
13807 // The splat value for the first packed shift (the 'X' from the example).
13808 SDValue Amt1 = Amt->getOperand(0);
13809 // The splat value for the second packed shift (the 'Y' from the example).
13810 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13811 Amt->getOperand(2);
13813 // See if it is possible to replace this node with a sequence of
13814 // two shifts followed by a MOVSS/MOVSD
13815 if (VT == MVT::v4i32) {
13816 // Check if it is legal to use a MOVSS.
13817 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13818 Amt2 == Amt->getOperand(3);
13819 if (!CanBeSimplified) {
13820 // Otherwise, check if we can still simplify this node using a MOVSD.
13821 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13822 Amt->getOperand(2) == Amt->getOperand(3);
13823 TargetOpcode = X86ISD::MOVSD;
13824 Amt2 = Amt->getOperand(2);
13827 // Do similar checks for the case where the machine value type
13829 CanBeSimplified = Amt1 == Amt->getOperand(1);
13830 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13831 CanBeSimplified = Amt2 == Amt->getOperand(i);
13833 if (!CanBeSimplified) {
13834 TargetOpcode = X86ISD::MOVSD;
13835 CanBeSimplified = true;
13836 Amt2 = Amt->getOperand(4);
13837 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13838 CanBeSimplified = Amt1 == Amt->getOperand(i);
13839 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13840 CanBeSimplified = Amt2 == Amt->getOperand(j);
13844 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13845 isa<ConstantSDNode>(Amt2)) {
13846 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13847 EVT CastVT = MVT::v4i32;
13849 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13850 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13852 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13853 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13854 if (TargetOpcode == X86ISD::MOVSD)
13855 CastVT = MVT::v2i64;
13856 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13857 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13858 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13860 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13864 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13865 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13868 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13869 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13871 // Turn 'a' into a mask suitable for VSELECT
13872 SDValue VSelM = DAG.getConstant(0x80, VT);
13873 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13874 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13876 SDValue CM1 = DAG.getConstant(0x0f, VT);
13877 SDValue CM2 = DAG.getConstant(0x3f, VT);
13879 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13880 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13881 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13882 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13883 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13886 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13887 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13888 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13890 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13891 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13892 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13893 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13894 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13897 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13898 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13899 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13901 // return VSELECT(r, r+r, a);
13902 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13903 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13907 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13908 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13909 // solution better.
13910 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13911 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13913 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13914 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13915 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13916 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13917 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13920 // Decompose 256-bit shifts into smaller 128-bit shifts.
13921 if (VT.is256BitVector()) {
13922 unsigned NumElems = VT.getVectorNumElements();
13923 MVT EltVT = VT.getVectorElementType();
13924 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13926 // Extract the two vectors
13927 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13928 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13930 // Recreate the shift amount vectors
13931 SDValue Amt1, Amt2;
13932 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13933 // Constant shift amount
13934 SmallVector<SDValue, 4> Amt1Csts;
13935 SmallVector<SDValue, 4> Amt2Csts;
13936 for (unsigned i = 0; i != NumElems/2; ++i)
13937 Amt1Csts.push_back(Amt->getOperand(i));
13938 for (unsigned i = NumElems/2; i != NumElems; ++i)
13939 Amt2Csts.push_back(Amt->getOperand(i));
13941 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13942 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13944 // Variable shift amount
13945 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13946 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13949 // Issue new vector shifts for the smaller types
13950 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13951 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13953 // Concatenate the result back
13954 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13960 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13961 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13962 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13963 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13964 // has only one use.
13965 SDNode *N = Op.getNode();
13966 SDValue LHS = N->getOperand(0);
13967 SDValue RHS = N->getOperand(1);
13968 unsigned BaseOp = 0;
13971 switch (Op.getOpcode()) {
13972 default: llvm_unreachable("Unknown ovf instruction!");
13974 // A subtract of one will be selected as a INC. Note that INC doesn't
13975 // set CF, so we can't do this for UADDO.
13976 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13978 BaseOp = X86ISD::INC;
13979 Cond = X86::COND_O;
13982 BaseOp = X86ISD::ADD;
13983 Cond = X86::COND_O;
13986 BaseOp = X86ISD::ADD;
13987 Cond = X86::COND_B;
13990 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13991 // set CF, so we can't do this for USUBO.
13992 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13994 BaseOp = X86ISD::DEC;
13995 Cond = X86::COND_O;
13998 BaseOp = X86ISD::SUB;
13999 Cond = X86::COND_O;
14002 BaseOp = X86ISD::SUB;
14003 Cond = X86::COND_B;
14006 BaseOp = X86ISD::SMUL;
14007 Cond = X86::COND_O;
14009 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14010 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14012 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14015 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14016 DAG.getConstant(X86::COND_O, MVT::i32),
14017 SDValue(Sum.getNode(), 2));
14019 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14023 // Also sets EFLAGS.
14024 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14025 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14028 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14029 DAG.getConstant(Cond, MVT::i32),
14030 SDValue(Sum.getNode(), 1));
14032 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14035 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14036 SelectionDAG &DAG) const {
14038 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14039 MVT VT = Op.getSimpleValueType();
14041 if (!Subtarget->hasSSE2() || !VT.isVector())
14044 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14045 ExtraVT.getScalarType().getSizeInBits();
14047 switch (VT.SimpleTy) {
14048 default: return SDValue();
14051 if (!Subtarget->hasFp256())
14053 if (!Subtarget->hasInt256()) {
14054 // needs to be split
14055 unsigned NumElems = VT.getVectorNumElements();
14057 // Extract the LHS vectors
14058 SDValue LHS = Op.getOperand(0);
14059 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14060 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14062 MVT EltVT = VT.getVectorElementType();
14063 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14065 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14066 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14067 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14069 SDValue Extra = DAG.getValueType(ExtraVT);
14071 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14072 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14074 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14079 SDValue Op0 = Op.getOperand(0);
14080 SDValue Op00 = Op0.getOperand(0);
14082 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14083 if (Op0.getOpcode() == ISD::BITCAST &&
14084 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14085 // (sext (vzext x)) -> (vsext x)
14086 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14087 if (Tmp1.getNode()) {
14088 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14089 // This folding is only valid when the in-reg type is a vector of i8,
14091 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14092 ExtraEltVT == MVT::i32) {
14093 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14094 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14095 "This optimization is invalid without a VZEXT.");
14096 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14102 // If the above didn't work, then just use Shift-Left + Shift-Right.
14103 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14105 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14111 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14112 SelectionDAG &DAG) {
14114 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14115 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14116 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14117 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14119 // The only fence that needs an instruction is a sequentially-consistent
14120 // cross-thread fence.
14121 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14122 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14123 // no-sse2). There isn't any reason to disable it if the target processor
14125 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14126 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14128 SDValue Chain = Op.getOperand(0);
14129 SDValue Zero = DAG.getConstant(0, MVT::i32);
14131 DAG.getRegister(X86::ESP, MVT::i32), // Base
14132 DAG.getTargetConstant(1, MVT::i8), // Scale
14133 DAG.getRegister(0, MVT::i32), // Index
14134 DAG.getTargetConstant(0, MVT::i32), // Disp
14135 DAG.getRegister(0, MVT::i32), // Segment.
14139 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14140 return SDValue(Res, 0);
14143 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14144 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14147 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14148 SelectionDAG &DAG) {
14149 MVT T = Op.getSimpleValueType();
14153 switch(T.SimpleTy) {
14154 default: llvm_unreachable("Invalid value type!");
14155 case MVT::i8: Reg = X86::AL; size = 1; break;
14156 case MVT::i16: Reg = X86::AX; size = 2; break;
14157 case MVT::i32: Reg = X86::EAX; size = 4; break;
14159 assert(Subtarget->is64Bit() && "Node not type legal!");
14160 Reg = X86::RAX; size = 8;
14163 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14164 Op.getOperand(2), SDValue());
14165 SDValue Ops[] = { cpIn.getValue(0),
14168 DAG.getTargetConstant(size, MVT::i8),
14169 cpIn.getValue(1) };
14170 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14171 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14172 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14175 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14179 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14180 SelectionDAG &DAG) {
14181 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14182 MVT DstVT = Op.getSimpleValueType();
14184 if (SrcVT == MVT::v2i32) {
14185 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14186 if (DstVT != MVT::f64)
14187 // This conversion needs to be expanded.
14191 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14192 Op->getOperand(0), DAG.getIntPtrConstant(0));
14193 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14194 Op->getOperand(0), DAG.getIntPtrConstant(1));
14195 SDValue Elts[] = {Elt0, Elt1, Elt0, Elt0};
14196 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Elts);
14197 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14198 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14199 DAG.getIntPtrConstant(0));
14202 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14203 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14204 assert((DstVT == MVT::i64 ||
14205 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14206 "Unexpected custom BITCAST");
14207 // i64 <=> MMX conversions are Legal.
14208 if (SrcVT==MVT::i64 && DstVT.isVector())
14210 if (DstVT==MVT::i64 && SrcVT.isVector())
14212 // MMX <=> MMX conversions are Legal.
14213 if (SrcVT.isVector() && DstVT.isVector())
14215 // All other conversions need to be expanded.
14219 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14220 SDNode *Node = Op.getNode();
14222 EVT T = Node->getValueType(0);
14223 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14224 DAG.getConstant(0, T), Node->getOperand(2));
14225 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14226 cast<AtomicSDNode>(Node)->getMemoryVT(),
14227 Node->getOperand(0),
14228 Node->getOperand(1), negOp,
14229 cast<AtomicSDNode>(Node)->getMemOperand(),
14230 cast<AtomicSDNode>(Node)->getOrdering(),
14231 cast<AtomicSDNode>(Node)->getSynchScope());
14234 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14235 SDNode *Node = Op.getNode();
14237 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14239 // Convert seq_cst store -> xchg
14240 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14241 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14242 // (The only way to get a 16-byte store is cmpxchg16b)
14243 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14244 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14245 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14246 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14247 cast<AtomicSDNode>(Node)->getMemoryVT(),
14248 Node->getOperand(0),
14249 Node->getOperand(1), Node->getOperand(2),
14250 cast<AtomicSDNode>(Node)->getMemOperand(),
14251 cast<AtomicSDNode>(Node)->getOrdering(),
14252 cast<AtomicSDNode>(Node)->getSynchScope());
14253 return Swap.getValue(1);
14255 // Other atomic stores have a simple pattern.
14259 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14260 EVT VT = Op.getNode()->getSimpleValueType(0);
14262 // Let legalize expand this if it isn't a legal type yet.
14263 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14266 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14269 bool ExtraOp = false;
14270 switch (Op.getOpcode()) {
14271 default: llvm_unreachable("Invalid code");
14272 case ISD::ADDC: Opc = X86ISD::ADD; break;
14273 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14274 case ISD::SUBC: Opc = X86ISD::SUB; break;
14275 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14279 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14281 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14282 Op.getOperand(1), Op.getOperand(2));
14285 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14286 SelectionDAG &DAG) {
14287 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14289 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14290 // which returns the values as { float, float } (in XMM0) or
14291 // { double, double } (which is returned in XMM0, XMM1).
14293 SDValue Arg = Op.getOperand(0);
14294 EVT ArgVT = Arg.getValueType();
14295 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14297 TargetLowering::ArgListTy Args;
14298 TargetLowering::ArgListEntry Entry;
14302 Entry.isSExt = false;
14303 Entry.isZExt = false;
14304 Args.push_back(Entry);
14306 bool isF64 = ArgVT == MVT::f64;
14307 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14308 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14309 // the results are returned via SRet in memory.
14310 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14311 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14312 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14314 Type *RetTy = isF64
14315 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14316 : (Type*)VectorType::get(ArgTy, 4);
14318 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14319 false, false, false, false, 0,
14320 CallingConv::C, /*isTaillCall=*/false,
14321 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14322 Callee, Args, DAG, dl);
14323 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14326 // Returned in xmm0 and xmm1.
14327 return CallResult.first;
14329 // Returned in bits 0:31 and 32:64 xmm0.
14330 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14331 CallResult.first, DAG.getIntPtrConstant(0));
14332 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14333 CallResult.first, DAG.getIntPtrConstant(1));
14334 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14335 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14338 /// LowerOperation - Provide custom lowering hooks for some operations.
14340 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14341 switch (Op.getOpcode()) {
14342 default: llvm_unreachable("Should not custom lower this!");
14343 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14344 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14345 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14346 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14347 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14348 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14349 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14350 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14351 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14352 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14353 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14354 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14355 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14356 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14357 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14358 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14359 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14360 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14361 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14362 case ISD::SHL_PARTS:
14363 case ISD::SRA_PARTS:
14364 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14365 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14366 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14367 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14368 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14369 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14370 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14371 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14372 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14373 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14374 case ISD::FABS: return LowerFABS(Op, DAG);
14375 case ISD::FNEG: return LowerFNEG(Op, DAG);
14376 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14377 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14378 case ISD::SETCC: return LowerSETCC(Op, DAG);
14379 case ISD::SELECT: return LowerSELECT(Op, DAG);
14380 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14381 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14382 case ISD::VASTART: return LowerVASTART(Op, DAG);
14383 case ISD::VAARG: return LowerVAARG(Op, DAG);
14384 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14385 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14386 case ISD::INTRINSIC_VOID:
14387 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14388 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14389 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14390 case ISD::FRAME_TO_ARGS_OFFSET:
14391 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14392 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14393 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14394 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14395 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14396 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14397 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14398 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14399 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14400 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14401 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14402 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14403 case ISD::UMUL_LOHI:
14404 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14407 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14413 case ISD::UMULO: return LowerXALUO(Op, DAG);
14414 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14415 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14419 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14420 case ISD::ADD: return LowerADD(Op, DAG);
14421 case ISD::SUB: return LowerSUB(Op, DAG);
14422 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14426 static void ReplaceATOMIC_LOAD(SDNode *Node,
14427 SmallVectorImpl<SDValue> &Results,
14428 SelectionDAG &DAG) {
14430 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14432 // Convert wide load -> cmpxchg8b/cmpxchg16b
14433 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14434 // (The only way to get a 16-byte load is cmpxchg16b)
14435 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14436 SDValue Zero = DAG.getConstant(0, VT);
14437 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14438 Node->getOperand(0),
14439 Node->getOperand(1), Zero, Zero,
14440 cast<AtomicSDNode>(Node)->getMemOperand(),
14441 cast<AtomicSDNode>(Node)->getOrdering(),
14442 cast<AtomicSDNode>(Node)->getOrdering(),
14443 cast<AtomicSDNode>(Node)->getSynchScope());
14444 Results.push_back(Swap.getValue(0));
14445 Results.push_back(Swap.getValue(1));
14449 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14450 SelectionDAG &DAG, unsigned NewOp) {
14452 assert (Node->getValueType(0) == MVT::i64 &&
14453 "Only know how to expand i64 atomics");
14455 SDValue Chain = Node->getOperand(0);
14456 SDValue In1 = Node->getOperand(1);
14457 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14458 Node->getOperand(2), DAG.getIntPtrConstant(0));
14459 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14460 Node->getOperand(2), DAG.getIntPtrConstant(1));
14461 SDValue Ops[] = { Chain, In1, In2L, In2H };
14462 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14464 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14465 cast<MemSDNode>(Node)->getMemOperand());
14466 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14467 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14468 Results.push_back(Result.getValue(2));
14471 /// ReplaceNodeResults - Replace a node with an illegal result type
14472 /// with a new node built out of custom code.
14473 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14474 SmallVectorImpl<SDValue>&Results,
14475 SelectionDAG &DAG) const {
14477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14478 switch (N->getOpcode()) {
14480 llvm_unreachable("Do not know how to custom type legalize this operation!");
14481 case ISD::SIGN_EXTEND_INREG:
14486 // We don't want to expand or promote these.
14493 case ISD::UDIVREM: {
14494 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14495 Results.push_back(V);
14498 case ISD::FP_TO_SINT:
14499 case ISD::FP_TO_UINT: {
14500 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14502 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14505 std::pair<SDValue,SDValue> Vals =
14506 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14507 SDValue FIST = Vals.first, StackSlot = Vals.second;
14508 if (FIST.getNode()) {
14509 EVT VT = N->getValueType(0);
14510 // Return a load from the stack slot.
14511 if (StackSlot.getNode())
14512 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14513 MachinePointerInfo(),
14514 false, false, false, 0));
14516 Results.push_back(FIST);
14520 case ISD::UINT_TO_FP: {
14521 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14522 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14523 N->getValueType(0) != MVT::v2f32)
14525 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14527 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14529 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14530 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14531 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14532 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14533 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14534 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14537 case ISD::FP_ROUND: {
14538 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14540 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14541 Results.push_back(V);
14544 case ISD::INTRINSIC_W_CHAIN: {
14545 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14547 default : llvm_unreachable("Do not know how to custom type "
14548 "legalize this intrinsic operation!");
14549 case Intrinsic::x86_rdtsc:
14550 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14552 case Intrinsic::x86_rdtscp:
14553 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14557 case ISD::READCYCLECOUNTER: {
14558 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14561 case ISD::ATOMIC_CMP_SWAP: {
14562 EVT T = N->getValueType(0);
14563 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14564 bool Regs64bit = T == MVT::i128;
14565 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14566 SDValue cpInL, cpInH;
14567 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14568 DAG.getConstant(0, HalfT));
14569 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14570 DAG.getConstant(1, HalfT));
14571 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14572 Regs64bit ? X86::RAX : X86::EAX,
14574 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14575 Regs64bit ? X86::RDX : X86::EDX,
14576 cpInH, cpInL.getValue(1));
14577 SDValue swapInL, swapInH;
14578 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14579 DAG.getConstant(0, HalfT));
14580 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14581 DAG.getConstant(1, HalfT));
14582 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14583 Regs64bit ? X86::RBX : X86::EBX,
14584 swapInL, cpInH.getValue(1));
14585 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14586 Regs64bit ? X86::RCX : X86::ECX,
14587 swapInH, swapInL.getValue(1));
14588 SDValue Ops[] = { swapInH.getValue(0),
14590 swapInH.getValue(1) };
14591 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14592 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14593 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14594 X86ISD::LCMPXCHG8_DAG;
14595 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14596 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14597 Regs64bit ? X86::RAX : X86::EAX,
14598 HalfT, Result.getValue(1));
14599 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14600 Regs64bit ? X86::RDX : X86::EDX,
14601 HalfT, cpOutL.getValue(2));
14602 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14603 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14604 Results.push_back(cpOutH.getValue(1));
14607 case ISD::ATOMIC_LOAD_ADD:
14608 case ISD::ATOMIC_LOAD_AND:
14609 case ISD::ATOMIC_LOAD_NAND:
14610 case ISD::ATOMIC_LOAD_OR:
14611 case ISD::ATOMIC_LOAD_SUB:
14612 case ISD::ATOMIC_LOAD_XOR:
14613 case ISD::ATOMIC_LOAD_MAX:
14614 case ISD::ATOMIC_LOAD_MIN:
14615 case ISD::ATOMIC_LOAD_UMAX:
14616 case ISD::ATOMIC_LOAD_UMIN:
14617 case ISD::ATOMIC_SWAP: {
14619 switch (N->getOpcode()) {
14620 default: llvm_unreachable("Unexpected opcode");
14621 case ISD::ATOMIC_LOAD_ADD:
14622 Opc = X86ISD::ATOMADD64_DAG;
14624 case ISD::ATOMIC_LOAD_AND:
14625 Opc = X86ISD::ATOMAND64_DAG;
14627 case ISD::ATOMIC_LOAD_NAND:
14628 Opc = X86ISD::ATOMNAND64_DAG;
14630 case ISD::ATOMIC_LOAD_OR:
14631 Opc = X86ISD::ATOMOR64_DAG;
14633 case ISD::ATOMIC_LOAD_SUB:
14634 Opc = X86ISD::ATOMSUB64_DAG;
14636 case ISD::ATOMIC_LOAD_XOR:
14637 Opc = X86ISD::ATOMXOR64_DAG;
14639 case ISD::ATOMIC_LOAD_MAX:
14640 Opc = X86ISD::ATOMMAX64_DAG;
14642 case ISD::ATOMIC_LOAD_MIN:
14643 Opc = X86ISD::ATOMMIN64_DAG;
14645 case ISD::ATOMIC_LOAD_UMAX:
14646 Opc = X86ISD::ATOMUMAX64_DAG;
14648 case ISD::ATOMIC_LOAD_UMIN:
14649 Opc = X86ISD::ATOMUMIN64_DAG;
14651 case ISD::ATOMIC_SWAP:
14652 Opc = X86ISD::ATOMSWAP64_DAG;
14655 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14658 case ISD::ATOMIC_LOAD: {
14659 ReplaceATOMIC_LOAD(N, Results, DAG);
14662 case ISD::BITCAST: {
14663 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14664 EVT DstVT = N->getValueType(0);
14665 EVT SrcVT = N->getOperand(0)->getValueType(0);
14667 if (SrcVT == MVT::f64 && DstVT == MVT::v2i32) {
14668 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14669 MVT::v2f64, N->getOperand(0));
14670 SDValue ToV4I32 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Expanded);
14671 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14672 ToV4I32, DAG.getIntPtrConstant(0));
14673 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14674 ToV4I32, DAG.getIntPtrConstant(1));
14675 SDValue Elts[] = {Elt0, Elt1};
14676 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Elts));
14682 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14684 default: return nullptr;
14685 case X86ISD::BSF: return "X86ISD::BSF";
14686 case X86ISD::BSR: return "X86ISD::BSR";
14687 case X86ISD::SHLD: return "X86ISD::SHLD";
14688 case X86ISD::SHRD: return "X86ISD::SHRD";
14689 case X86ISD::FAND: return "X86ISD::FAND";
14690 case X86ISD::FANDN: return "X86ISD::FANDN";
14691 case X86ISD::FOR: return "X86ISD::FOR";
14692 case X86ISD::FXOR: return "X86ISD::FXOR";
14693 case X86ISD::FSRL: return "X86ISD::FSRL";
14694 case X86ISD::FILD: return "X86ISD::FILD";
14695 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14696 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14697 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14698 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14699 case X86ISD::FLD: return "X86ISD::FLD";
14700 case X86ISD::FST: return "X86ISD::FST";
14701 case X86ISD::CALL: return "X86ISD::CALL";
14702 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14703 case X86ISD::BT: return "X86ISD::BT";
14704 case X86ISD::CMP: return "X86ISD::CMP";
14705 case X86ISD::COMI: return "X86ISD::COMI";
14706 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14707 case X86ISD::CMPM: return "X86ISD::CMPM";
14708 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14709 case X86ISD::SETCC: return "X86ISD::SETCC";
14710 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14711 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14712 case X86ISD::CMOV: return "X86ISD::CMOV";
14713 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14714 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14715 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14716 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14717 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14718 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14719 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14720 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14721 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14722 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14723 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14724 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14725 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14726 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14727 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14728 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14729 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14730 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14731 case X86ISD::HADD: return "X86ISD::HADD";
14732 case X86ISD::HSUB: return "X86ISD::HSUB";
14733 case X86ISD::FHADD: return "X86ISD::FHADD";
14734 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14735 case X86ISD::UMAX: return "X86ISD::UMAX";
14736 case X86ISD::UMIN: return "X86ISD::UMIN";
14737 case X86ISD::SMAX: return "X86ISD::SMAX";
14738 case X86ISD::SMIN: return "X86ISD::SMIN";
14739 case X86ISD::FMAX: return "X86ISD::FMAX";
14740 case X86ISD::FMIN: return "X86ISD::FMIN";
14741 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14742 case X86ISD::FMINC: return "X86ISD::FMINC";
14743 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14744 case X86ISD::FRCP: return "X86ISD::FRCP";
14745 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14746 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14747 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14748 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14749 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14750 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14751 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14752 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14753 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14754 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14755 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14756 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14757 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14758 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14759 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14760 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14761 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14762 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14763 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14764 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14765 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14766 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14767 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14768 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14769 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14770 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14771 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14772 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14773 case X86ISD::VSHL: return "X86ISD::VSHL";
14774 case X86ISD::VSRL: return "X86ISD::VSRL";
14775 case X86ISD::VSRA: return "X86ISD::VSRA";
14776 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14777 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14778 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14779 case X86ISD::CMPP: return "X86ISD::CMPP";
14780 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14781 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14782 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14783 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14784 case X86ISD::ADD: return "X86ISD::ADD";
14785 case X86ISD::SUB: return "X86ISD::SUB";
14786 case X86ISD::ADC: return "X86ISD::ADC";
14787 case X86ISD::SBB: return "X86ISD::SBB";
14788 case X86ISD::SMUL: return "X86ISD::SMUL";
14789 case X86ISD::UMUL: return "X86ISD::UMUL";
14790 case X86ISD::INC: return "X86ISD::INC";
14791 case X86ISD::DEC: return "X86ISD::DEC";
14792 case X86ISD::OR: return "X86ISD::OR";
14793 case X86ISD::XOR: return "X86ISD::XOR";
14794 case X86ISD::AND: return "X86ISD::AND";
14795 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14796 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14797 case X86ISD::PTEST: return "X86ISD::PTEST";
14798 case X86ISD::TESTP: return "X86ISD::TESTP";
14799 case X86ISD::TESTM: return "X86ISD::TESTM";
14800 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14801 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14802 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14803 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14804 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14805 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14806 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14807 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14808 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14809 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14810 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14811 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14812 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14813 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14814 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14815 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14816 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14817 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14818 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14819 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14820 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14821 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14822 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14823 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14824 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14825 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14826 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14827 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14828 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14829 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14830 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14831 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14832 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14833 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14834 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14835 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14836 case X86ISD::SAHF: return "X86ISD::SAHF";
14837 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14838 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14839 case X86ISD::FMADD: return "X86ISD::FMADD";
14840 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14841 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14842 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14843 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14844 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14845 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14846 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14847 case X86ISD::XTEST: return "X86ISD::XTEST";
14851 // isLegalAddressingMode - Return true if the addressing mode represented
14852 // by AM is legal for this target, for a load/store of the specified type.
14853 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14855 // X86 supports extremely general addressing modes.
14856 CodeModel::Model M = getTargetMachine().getCodeModel();
14857 Reloc::Model R = getTargetMachine().getRelocationModel();
14859 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14860 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14865 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14867 // If a reference to this global requires an extra load, we can't fold it.
14868 if (isGlobalStubReference(GVFlags))
14871 // If BaseGV requires a register for the PIC base, we cannot also have a
14872 // BaseReg specified.
14873 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14876 // If lower 4G is not available, then we must use rip-relative addressing.
14877 if ((M != CodeModel::Small || R != Reloc::Static) &&
14878 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14882 switch (AM.Scale) {
14888 // These scales always work.
14893 // These scales are formed with basereg+scalereg. Only accept if there is
14898 default: // Other stuff never works.
14905 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14906 unsigned Bits = Ty->getScalarSizeInBits();
14908 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14909 // particularly cheaper than those without.
14913 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14914 // variable shifts just as cheap as scalar ones.
14915 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14918 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14919 // fully general vector.
14923 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14924 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14926 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14927 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14928 return NumBits1 > NumBits2;
14931 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14932 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14935 if (!isTypeLegal(EVT::getEVT(Ty1)))
14938 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14940 // Assuming the caller doesn't have a zeroext or signext return parameter,
14941 // truncation all the way down to i1 is valid.
14945 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14946 return isInt<32>(Imm);
14949 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14950 // Can also use sub to handle negated immediates.
14951 return isInt<32>(Imm);
14954 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14955 if (!VT1.isInteger() || !VT2.isInteger())
14957 unsigned NumBits1 = VT1.getSizeInBits();
14958 unsigned NumBits2 = VT2.getSizeInBits();
14959 return NumBits1 > NumBits2;
14962 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14963 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14964 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14967 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14968 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14969 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14972 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14973 EVT VT1 = Val.getValueType();
14974 if (isZExtFree(VT1, VT2))
14977 if (Val.getOpcode() != ISD::LOAD)
14980 if (!VT1.isSimple() || !VT1.isInteger() ||
14981 !VT2.isSimple() || !VT2.isInteger())
14984 switch (VT1.getSimpleVT().SimpleTy) {
14989 // X86 has 8, 16, and 32-bit zero-extending loads.
14997 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14998 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15001 VT = VT.getScalarType();
15003 if (!VT.isSimple())
15006 switch (VT.getSimpleVT().SimpleTy) {
15017 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15018 // i16 instructions are longer (0x66 prefix) and potentially slower.
15019 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15022 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15023 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15024 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15025 /// are assumed to be legal.
15027 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15029 if (!VT.isSimple())
15032 MVT SVT = VT.getSimpleVT();
15034 // Very little shuffling can be done for 64-bit vectors right now.
15035 if (VT.getSizeInBits() == 64)
15038 // FIXME: pshufb, blends, shifts.
15039 return (SVT.getVectorNumElements() == 2 ||
15040 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15041 isMOVLMask(M, SVT) ||
15042 isSHUFPMask(M, SVT) ||
15043 isPSHUFDMask(M, SVT) ||
15044 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15045 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15046 isPALIGNRMask(M, SVT, Subtarget) ||
15047 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15048 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15049 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15050 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
15054 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15056 if (!VT.isSimple())
15059 MVT SVT = VT.getSimpleVT();
15060 unsigned NumElts = SVT.getVectorNumElements();
15061 // FIXME: This collection of masks seems suspect.
15064 if (NumElts == 4 && SVT.is128BitVector()) {
15065 return (isMOVLMask(Mask, SVT) ||
15066 isCommutedMOVLMask(Mask, SVT, true) ||
15067 isSHUFPMask(Mask, SVT) ||
15068 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15073 //===----------------------------------------------------------------------===//
15074 // X86 Scheduler Hooks
15075 //===----------------------------------------------------------------------===//
15077 /// Utility function to emit xbegin specifying the start of an RTM region.
15078 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15079 const TargetInstrInfo *TII) {
15080 DebugLoc DL = MI->getDebugLoc();
15082 const BasicBlock *BB = MBB->getBasicBlock();
15083 MachineFunction::iterator I = MBB;
15086 // For the v = xbegin(), we generate
15097 MachineBasicBlock *thisMBB = MBB;
15098 MachineFunction *MF = MBB->getParent();
15099 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15100 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15101 MF->insert(I, mainMBB);
15102 MF->insert(I, sinkMBB);
15104 // Transfer the remainder of BB and its successor edges to sinkMBB.
15105 sinkMBB->splice(sinkMBB->begin(), MBB,
15106 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15107 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15111 // # fallthrough to mainMBB
15112 // # abortion to sinkMBB
15113 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15114 thisMBB->addSuccessor(mainMBB);
15115 thisMBB->addSuccessor(sinkMBB);
15119 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15120 mainMBB->addSuccessor(sinkMBB);
15123 // EAX is live into the sinkMBB
15124 sinkMBB->addLiveIn(X86::EAX);
15125 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15126 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15129 MI->eraseFromParent();
15133 // Get CMPXCHG opcode for the specified data type.
15134 static unsigned getCmpXChgOpcode(EVT VT) {
15135 switch (VT.getSimpleVT().SimpleTy) {
15136 case MVT::i8: return X86::LCMPXCHG8;
15137 case MVT::i16: return X86::LCMPXCHG16;
15138 case MVT::i32: return X86::LCMPXCHG32;
15139 case MVT::i64: return X86::LCMPXCHG64;
15143 llvm_unreachable("Invalid operand size!");
15146 // Get LOAD opcode for the specified data type.
15147 static unsigned getLoadOpcode(EVT VT) {
15148 switch (VT.getSimpleVT().SimpleTy) {
15149 case MVT::i8: return X86::MOV8rm;
15150 case MVT::i16: return X86::MOV16rm;
15151 case MVT::i32: return X86::MOV32rm;
15152 case MVT::i64: return X86::MOV64rm;
15156 llvm_unreachable("Invalid operand size!");
15159 // Get opcode of the non-atomic one from the specified atomic instruction.
15160 static unsigned getNonAtomicOpcode(unsigned Opc) {
15162 case X86::ATOMAND8: return X86::AND8rr;
15163 case X86::ATOMAND16: return X86::AND16rr;
15164 case X86::ATOMAND32: return X86::AND32rr;
15165 case X86::ATOMAND64: return X86::AND64rr;
15166 case X86::ATOMOR8: return X86::OR8rr;
15167 case X86::ATOMOR16: return X86::OR16rr;
15168 case X86::ATOMOR32: return X86::OR32rr;
15169 case X86::ATOMOR64: return X86::OR64rr;
15170 case X86::ATOMXOR8: return X86::XOR8rr;
15171 case X86::ATOMXOR16: return X86::XOR16rr;
15172 case X86::ATOMXOR32: return X86::XOR32rr;
15173 case X86::ATOMXOR64: return X86::XOR64rr;
15175 llvm_unreachable("Unhandled atomic-load-op opcode!");
15178 // Get opcode of the non-atomic one from the specified atomic instruction with
15180 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15181 unsigned &ExtraOpc) {
15183 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15184 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15185 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15186 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15187 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15188 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15189 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15190 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15191 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15192 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15193 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15194 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15195 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15196 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15197 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15198 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15199 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15200 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15201 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15202 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15204 llvm_unreachable("Unhandled atomic-load-op opcode!");
15207 // Get opcode of the non-atomic one from the specified atomic instruction for
15208 // 64-bit data type on 32-bit target.
15209 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15211 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15212 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15213 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15214 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15215 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15216 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15217 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15218 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15219 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15220 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15222 llvm_unreachable("Unhandled atomic-load-op opcode!");
15225 // Get opcode of the non-atomic one from the specified atomic instruction for
15226 // 64-bit data type on 32-bit target with extra opcode.
15227 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15229 unsigned &ExtraOpc) {
15231 case X86::ATOMNAND6432:
15232 ExtraOpc = X86::NOT32r;
15233 HiOpc = X86::AND32rr;
15234 return X86::AND32rr;
15236 llvm_unreachable("Unhandled atomic-load-op opcode!");
15239 // Get pseudo CMOV opcode from the specified data type.
15240 static unsigned getPseudoCMOVOpc(EVT VT) {
15241 switch (VT.getSimpleVT().SimpleTy) {
15242 case MVT::i8: return X86::CMOV_GR8;
15243 case MVT::i16: return X86::CMOV_GR16;
15244 case MVT::i32: return X86::CMOV_GR32;
15248 llvm_unreachable("Unknown CMOV opcode!");
15251 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15252 // They will be translated into a spin-loop or compare-exchange loop from
15255 // dst = atomic-fetch-op MI.addr, MI.val
15261 // t1 = LOAD MI.addr
15263 // t4 = phi(t1, t3 / loop)
15264 // t2 = OP MI.val, t4
15266 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15272 MachineBasicBlock *
15273 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15274 MachineBasicBlock *MBB) const {
15275 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15276 DebugLoc DL = MI->getDebugLoc();
15278 MachineFunction *MF = MBB->getParent();
15279 MachineRegisterInfo &MRI = MF->getRegInfo();
15281 const BasicBlock *BB = MBB->getBasicBlock();
15282 MachineFunction::iterator I = MBB;
15285 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15286 "Unexpected number of operands");
15288 assert(MI->hasOneMemOperand() &&
15289 "Expected atomic-load-op to have one memoperand");
15291 // Memory Reference
15292 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15293 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15295 unsigned DstReg, SrcReg;
15296 unsigned MemOpndSlot;
15298 unsigned CurOp = 0;
15300 DstReg = MI->getOperand(CurOp++).getReg();
15301 MemOpndSlot = CurOp;
15302 CurOp += X86::AddrNumOperands;
15303 SrcReg = MI->getOperand(CurOp++).getReg();
15305 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15306 MVT::SimpleValueType VT = *RC->vt_begin();
15307 unsigned t1 = MRI.createVirtualRegister(RC);
15308 unsigned t2 = MRI.createVirtualRegister(RC);
15309 unsigned t3 = MRI.createVirtualRegister(RC);
15310 unsigned t4 = MRI.createVirtualRegister(RC);
15311 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15313 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15314 unsigned LOADOpc = getLoadOpcode(VT);
15316 // For the atomic load-arith operator, we generate
15319 // t1 = LOAD [MI.addr]
15321 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15322 // t1 = OP MI.val, EAX
15324 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15330 MachineBasicBlock *thisMBB = MBB;
15331 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15332 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15333 MF->insert(I, mainMBB);
15334 MF->insert(I, sinkMBB);
15336 MachineInstrBuilder MIB;
15338 // Transfer the remainder of BB and its successor edges to sinkMBB.
15339 sinkMBB->splice(sinkMBB->begin(), MBB,
15340 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15341 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15344 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15345 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15346 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15348 NewMO.setIsKill(false);
15349 MIB.addOperand(NewMO);
15351 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15352 unsigned flags = (*MMOI)->getFlags();
15353 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15354 MachineMemOperand *MMO =
15355 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15356 (*MMOI)->getSize(),
15357 (*MMOI)->getBaseAlignment(),
15358 (*MMOI)->getTBAAInfo(),
15359 (*MMOI)->getRanges());
15360 MIB.addMemOperand(MMO);
15363 thisMBB->addSuccessor(mainMBB);
15366 MachineBasicBlock *origMainMBB = mainMBB;
15369 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15370 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15372 unsigned Opc = MI->getOpcode();
15375 llvm_unreachable("Unhandled atomic-load-op opcode!");
15376 case X86::ATOMAND8:
15377 case X86::ATOMAND16:
15378 case X86::ATOMAND32:
15379 case X86::ATOMAND64:
15381 case X86::ATOMOR16:
15382 case X86::ATOMOR32:
15383 case X86::ATOMOR64:
15384 case X86::ATOMXOR8:
15385 case X86::ATOMXOR16:
15386 case X86::ATOMXOR32:
15387 case X86::ATOMXOR64: {
15388 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15389 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15393 case X86::ATOMNAND8:
15394 case X86::ATOMNAND16:
15395 case X86::ATOMNAND32:
15396 case X86::ATOMNAND64: {
15397 unsigned Tmp = MRI.createVirtualRegister(RC);
15399 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15400 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15402 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15405 case X86::ATOMMAX8:
15406 case X86::ATOMMAX16:
15407 case X86::ATOMMAX32:
15408 case X86::ATOMMAX64:
15409 case X86::ATOMMIN8:
15410 case X86::ATOMMIN16:
15411 case X86::ATOMMIN32:
15412 case X86::ATOMMIN64:
15413 case X86::ATOMUMAX8:
15414 case X86::ATOMUMAX16:
15415 case X86::ATOMUMAX32:
15416 case X86::ATOMUMAX64:
15417 case X86::ATOMUMIN8:
15418 case X86::ATOMUMIN16:
15419 case X86::ATOMUMIN32:
15420 case X86::ATOMUMIN64: {
15422 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15424 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15428 if (Subtarget->hasCMov()) {
15429 if (VT != MVT::i8) {
15431 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15435 // Promote i8 to i32 to use CMOV32
15436 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15437 const TargetRegisterClass *RC32 =
15438 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15439 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15440 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15441 unsigned Tmp = MRI.createVirtualRegister(RC32);
15443 unsigned Undef = MRI.createVirtualRegister(RC32);
15444 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15446 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15449 .addImm(X86::sub_8bit);
15450 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15453 .addImm(X86::sub_8bit);
15455 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15459 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15460 .addReg(Tmp, 0, X86::sub_8bit);
15463 // Use pseudo select and lower them.
15464 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15465 "Invalid atomic-load-op transformation!");
15466 unsigned SelOpc = getPseudoCMOVOpc(VT);
15467 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15468 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15469 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15470 .addReg(SrcReg).addReg(t4)
15472 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15473 // Replace the original PHI node as mainMBB is changed after CMOV
15475 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15476 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15477 Phi->eraseFromParent();
15483 // Copy PhyReg back from virtual register.
15484 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15487 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15488 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15489 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15491 NewMO.setIsKill(false);
15492 MIB.addOperand(NewMO);
15495 MIB.setMemRefs(MMOBegin, MMOEnd);
15497 // Copy PhyReg back to virtual register.
15498 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15501 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15503 mainMBB->addSuccessor(origMainMBB);
15504 mainMBB->addSuccessor(sinkMBB);
15507 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15508 TII->get(TargetOpcode::COPY), DstReg)
15511 MI->eraseFromParent();
15515 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15516 // instructions. They will be translated into a spin-loop or compare-exchange
15520 // dst = atomic-fetch-op MI.addr, MI.val
15526 // t1L = LOAD [MI.addr + 0]
15527 // t1H = LOAD [MI.addr + 4]
15529 // t4L = phi(t1L, t3L / loop)
15530 // t4H = phi(t1H, t3H / loop)
15531 // t2L = OP MI.val.lo, t4L
15532 // t2H = OP MI.val.hi, t4H
15537 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15545 MachineBasicBlock *
15546 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15547 MachineBasicBlock *MBB) const {
15548 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15549 DebugLoc DL = MI->getDebugLoc();
15551 MachineFunction *MF = MBB->getParent();
15552 MachineRegisterInfo &MRI = MF->getRegInfo();
15554 const BasicBlock *BB = MBB->getBasicBlock();
15555 MachineFunction::iterator I = MBB;
15558 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15559 "Unexpected number of operands");
15561 assert(MI->hasOneMemOperand() &&
15562 "Expected atomic-load-op32 to have one memoperand");
15564 // Memory Reference
15565 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15566 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15568 unsigned DstLoReg, DstHiReg;
15569 unsigned SrcLoReg, SrcHiReg;
15570 unsigned MemOpndSlot;
15572 unsigned CurOp = 0;
15574 DstLoReg = MI->getOperand(CurOp++).getReg();
15575 DstHiReg = MI->getOperand(CurOp++).getReg();
15576 MemOpndSlot = CurOp;
15577 CurOp += X86::AddrNumOperands;
15578 SrcLoReg = MI->getOperand(CurOp++).getReg();
15579 SrcHiReg = MI->getOperand(CurOp++).getReg();
15581 const TargetRegisterClass *RC = &X86::GR32RegClass;
15582 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15584 unsigned t1L = MRI.createVirtualRegister(RC);
15585 unsigned t1H = MRI.createVirtualRegister(RC);
15586 unsigned t2L = MRI.createVirtualRegister(RC);
15587 unsigned t2H = MRI.createVirtualRegister(RC);
15588 unsigned t3L = MRI.createVirtualRegister(RC);
15589 unsigned t3H = MRI.createVirtualRegister(RC);
15590 unsigned t4L = MRI.createVirtualRegister(RC);
15591 unsigned t4H = MRI.createVirtualRegister(RC);
15593 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15594 unsigned LOADOpc = X86::MOV32rm;
15596 // For the atomic load-arith operator, we generate
15599 // t1L = LOAD [MI.addr + 0]
15600 // t1H = LOAD [MI.addr + 4]
15602 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15603 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15604 // t2L = OP MI.val.lo, t4L
15605 // t2H = OP MI.val.hi, t4H
15608 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15616 MachineBasicBlock *thisMBB = MBB;
15617 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15618 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15619 MF->insert(I, mainMBB);
15620 MF->insert(I, sinkMBB);
15622 MachineInstrBuilder MIB;
15624 // Transfer the remainder of BB and its successor edges to sinkMBB.
15625 sinkMBB->splice(sinkMBB->begin(), MBB,
15626 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15627 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15631 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15632 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15633 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15635 NewMO.setIsKill(false);
15636 MIB.addOperand(NewMO);
15638 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15639 unsigned flags = (*MMOI)->getFlags();
15640 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15641 MachineMemOperand *MMO =
15642 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15643 (*MMOI)->getSize(),
15644 (*MMOI)->getBaseAlignment(),
15645 (*MMOI)->getTBAAInfo(),
15646 (*MMOI)->getRanges());
15647 MIB.addMemOperand(MMO);
15649 MachineInstr *LowMI = MIB;
15652 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15653 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15654 if (i == X86::AddrDisp) {
15655 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15657 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15659 NewMO.setIsKill(false);
15660 MIB.addOperand(NewMO);
15663 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15665 thisMBB->addSuccessor(mainMBB);
15668 MachineBasicBlock *origMainMBB = mainMBB;
15671 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15672 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15673 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15674 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15676 unsigned Opc = MI->getOpcode();
15679 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15680 case X86::ATOMAND6432:
15681 case X86::ATOMOR6432:
15682 case X86::ATOMXOR6432:
15683 case X86::ATOMADD6432:
15684 case X86::ATOMSUB6432: {
15686 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15687 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15689 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15693 case X86::ATOMNAND6432: {
15694 unsigned HiOpc, NOTOpc;
15695 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15696 unsigned TmpL = MRI.createVirtualRegister(RC);
15697 unsigned TmpH = MRI.createVirtualRegister(RC);
15698 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15700 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15702 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15703 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15706 case X86::ATOMMAX6432:
15707 case X86::ATOMMIN6432:
15708 case X86::ATOMUMAX6432:
15709 case X86::ATOMUMIN6432: {
15711 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15712 unsigned cL = MRI.createVirtualRegister(RC8);
15713 unsigned cH = MRI.createVirtualRegister(RC8);
15714 unsigned cL32 = MRI.createVirtualRegister(RC);
15715 unsigned cH32 = MRI.createVirtualRegister(RC);
15716 unsigned cc = MRI.createVirtualRegister(RC);
15717 // cl := cmp src_lo, lo
15718 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15719 .addReg(SrcLoReg).addReg(t4L);
15720 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15721 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15722 // ch := cmp src_hi, hi
15723 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15724 .addReg(SrcHiReg).addReg(t4H);
15725 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15726 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15727 // cc := if (src_hi == hi) ? cl : ch;
15728 if (Subtarget->hasCMov()) {
15729 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15730 .addReg(cH32).addReg(cL32);
15732 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15733 .addReg(cH32).addReg(cL32)
15734 .addImm(X86::COND_E);
15735 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15737 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15738 if (Subtarget->hasCMov()) {
15739 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15740 .addReg(SrcLoReg).addReg(t4L);
15741 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15742 .addReg(SrcHiReg).addReg(t4H);
15744 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15745 .addReg(SrcLoReg).addReg(t4L)
15746 .addImm(X86::COND_NE);
15747 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15748 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15749 // 2nd CMOV lowering.
15750 mainMBB->addLiveIn(X86::EFLAGS);
15751 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15752 .addReg(SrcHiReg).addReg(t4H)
15753 .addImm(X86::COND_NE);
15754 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15755 // Replace the original PHI node as mainMBB is changed after CMOV
15757 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15758 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15759 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15760 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15761 PhiL->eraseFromParent();
15762 PhiH->eraseFromParent();
15766 case X86::ATOMSWAP6432: {
15768 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15769 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15770 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15775 // Copy EDX:EAX back from HiReg:LoReg
15776 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15777 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15778 // Copy ECX:EBX from t1H:t1L
15779 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15780 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15782 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15783 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15784 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15786 NewMO.setIsKill(false);
15787 MIB.addOperand(NewMO);
15789 MIB.setMemRefs(MMOBegin, MMOEnd);
15791 // Copy EDX:EAX back to t3H:t3L
15792 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15793 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15795 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15797 mainMBB->addSuccessor(origMainMBB);
15798 mainMBB->addSuccessor(sinkMBB);
15801 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15802 TII->get(TargetOpcode::COPY), DstLoReg)
15804 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15805 TII->get(TargetOpcode::COPY), DstHiReg)
15808 MI->eraseFromParent();
15812 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15813 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15814 // in the .td file.
15815 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15816 const TargetInstrInfo *TII) {
15818 switch (MI->getOpcode()) {
15819 default: llvm_unreachable("illegal opcode!");
15820 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15821 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15822 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15823 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15824 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15825 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15826 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15827 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15830 DebugLoc dl = MI->getDebugLoc();
15831 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15833 unsigned NumArgs = MI->getNumOperands();
15834 for (unsigned i = 1; i < NumArgs; ++i) {
15835 MachineOperand &Op = MI->getOperand(i);
15836 if (!(Op.isReg() && Op.isImplicit()))
15837 MIB.addOperand(Op);
15839 if (MI->hasOneMemOperand())
15840 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15842 BuildMI(*BB, MI, dl,
15843 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15844 .addReg(X86::XMM0);
15846 MI->eraseFromParent();
15850 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15851 // defs in an instruction pattern
15852 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15853 const TargetInstrInfo *TII) {
15855 switch (MI->getOpcode()) {
15856 default: llvm_unreachable("illegal opcode!");
15857 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15858 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15859 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15860 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15861 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15862 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15863 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15864 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15867 DebugLoc dl = MI->getDebugLoc();
15868 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15870 unsigned NumArgs = MI->getNumOperands(); // remove the results
15871 for (unsigned i = 1; i < NumArgs; ++i) {
15872 MachineOperand &Op = MI->getOperand(i);
15873 if (!(Op.isReg() && Op.isImplicit()))
15874 MIB.addOperand(Op);
15876 if (MI->hasOneMemOperand())
15877 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15879 BuildMI(*BB, MI, dl,
15880 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15883 MI->eraseFromParent();
15887 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15888 const TargetInstrInfo *TII,
15889 const X86Subtarget* Subtarget) {
15890 DebugLoc dl = MI->getDebugLoc();
15892 // Address into RAX/EAX, other two args into ECX, EDX.
15893 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15894 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15895 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15896 for (int i = 0; i < X86::AddrNumOperands; ++i)
15897 MIB.addOperand(MI->getOperand(i));
15899 unsigned ValOps = X86::AddrNumOperands;
15900 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15901 .addReg(MI->getOperand(ValOps).getReg());
15902 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15903 .addReg(MI->getOperand(ValOps+1).getReg());
15905 // The instruction doesn't actually take any operands though.
15906 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15908 MI->eraseFromParent(); // The pseudo is gone now.
15912 MachineBasicBlock *
15913 X86TargetLowering::EmitVAARG64WithCustomInserter(
15915 MachineBasicBlock *MBB) const {
15916 // Emit va_arg instruction on X86-64.
15918 // Operands to this pseudo-instruction:
15919 // 0 ) Output : destination address (reg)
15920 // 1-5) Input : va_list address (addr, i64mem)
15921 // 6 ) ArgSize : Size (in bytes) of vararg type
15922 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15923 // 8 ) Align : Alignment of type
15924 // 9 ) EFLAGS (implicit-def)
15926 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15927 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15929 unsigned DestReg = MI->getOperand(0).getReg();
15930 MachineOperand &Base = MI->getOperand(1);
15931 MachineOperand &Scale = MI->getOperand(2);
15932 MachineOperand &Index = MI->getOperand(3);
15933 MachineOperand &Disp = MI->getOperand(4);
15934 MachineOperand &Segment = MI->getOperand(5);
15935 unsigned ArgSize = MI->getOperand(6).getImm();
15936 unsigned ArgMode = MI->getOperand(7).getImm();
15937 unsigned Align = MI->getOperand(8).getImm();
15939 // Memory Reference
15940 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15941 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15942 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15944 // Machine Information
15945 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15946 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15947 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15948 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15949 DebugLoc DL = MI->getDebugLoc();
15951 // struct va_list {
15954 // i64 overflow_area (address)
15955 // i64 reg_save_area (address)
15957 // sizeof(va_list) = 24
15958 // alignment(va_list) = 8
15960 unsigned TotalNumIntRegs = 6;
15961 unsigned TotalNumXMMRegs = 8;
15962 bool UseGPOffset = (ArgMode == 1);
15963 bool UseFPOffset = (ArgMode == 2);
15964 unsigned MaxOffset = TotalNumIntRegs * 8 +
15965 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15967 /* Align ArgSize to a multiple of 8 */
15968 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15969 bool NeedsAlign = (Align > 8);
15971 MachineBasicBlock *thisMBB = MBB;
15972 MachineBasicBlock *overflowMBB;
15973 MachineBasicBlock *offsetMBB;
15974 MachineBasicBlock *endMBB;
15976 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15977 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15978 unsigned OffsetReg = 0;
15980 if (!UseGPOffset && !UseFPOffset) {
15981 // If we only pull from the overflow region, we don't create a branch.
15982 // We don't need to alter control flow.
15983 OffsetDestReg = 0; // unused
15984 OverflowDestReg = DestReg;
15986 offsetMBB = nullptr;
15987 overflowMBB = thisMBB;
15990 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15991 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15992 // If not, pull from overflow_area. (branch to overflowMBB)
15997 // offsetMBB overflowMBB
16002 // Registers for the PHI in endMBB
16003 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16004 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16006 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16007 MachineFunction *MF = MBB->getParent();
16008 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16009 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16010 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16012 MachineFunction::iterator MBBIter = MBB;
16015 // Insert the new basic blocks
16016 MF->insert(MBBIter, offsetMBB);
16017 MF->insert(MBBIter, overflowMBB);
16018 MF->insert(MBBIter, endMBB);
16020 // Transfer the remainder of MBB and its successor edges to endMBB.
16021 endMBB->splice(endMBB->begin(), thisMBB,
16022 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16023 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16025 // Make offsetMBB and overflowMBB successors of thisMBB
16026 thisMBB->addSuccessor(offsetMBB);
16027 thisMBB->addSuccessor(overflowMBB);
16029 // endMBB is a successor of both offsetMBB and overflowMBB
16030 offsetMBB->addSuccessor(endMBB);
16031 overflowMBB->addSuccessor(endMBB);
16033 // Load the offset value into a register
16034 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16035 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16039 .addDisp(Disp, UseFPOffset ? 4 : 0)
16040 .addOperand(Segment)
16041 .setMemRefs(MMOBegin, MMOEnd);
16043 // Check if there is enough room left to pull this argument.
16044 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16046 .addImm(MaxOffset + 8 - ArgSizeA8);
16048 // Branch to "overflowMBB" if offset >= max
16049 // Fall through to "offsetMBB" otherwise
16050 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16051 .addMBB(overflowMBB);
16054 // In offsetMBB, emit code to use the reg_save_area.
16056 assert(OffsetReg != 0);
16058 // Read the reg_save_area address.
16059 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16060 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16065 .addOperand(Segment)
16066 .setMemRefs(MMOBegin, MMOEnd);
16068 // Zero-extend the offset
16069 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16070 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16073 .addImm(X86::sub_32bit);
16075 // Add the offset to the reg_save_area to get the final address.
16076 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16077 .addReg(OffsetReg64)
16078 .addReg(RegSaveReg);
16080 // Compute the offset for the next argument
16081 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16082 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16084 .addImm(UseFPOffset ? 16 : 8);
16086 // Store it back into the va_list.
16087 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16091 .addDisp(Disp, UseFPOffset ? 4 : 0)
16092 .addOperand(Segment)
16093 .addReg(NextOffsetReg)
16094 .setMemRefs(MMOBegin, MMOEnd);
16097 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16102 // Emit code to use overflow area
16105 // Load the overflow_area address into a register.
16106 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16107 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16112 .addOperand(Segment)
16113 .setMemRefs(MMOBegin, MMOEnd);
16115 // If we need to align it, do so. Otherwise, just copy the address
16116 // to OverflowDestReg.
16118 // Align the overflow address
16119 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16120 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16122 // aligned_addr = (addr + (align-1)) & ~(align-1)
16123 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16124 .addReg(OverflowAddrReg)
16127 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16129 .addImm(~(uint64_t)(Align-1));
16131 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16132 .addReg(OverflowAddrReg);
16135 // Compute the next overflow address after this argument.
16136 // (the overflow address should be kept 8-byte aligned)
16137 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16138 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16139 .addReg(OverflowDestReg)
16140 .addImm(ArgSizeA8);
16142 // Store the new overflow address.
16143 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16148 .addOperand(Segment)
16149 .addReg(NextAddrReg)
16150 .setMemRefs(MMOBegin, MMOEnd);
16152 // If we branched, emit the PHI to the front of endMBB.
16154 BuildMI(*endMBB, endMBB->begin(), DL,
16155 TII->get(X86::PHI), DestReg)
16156 .addReg(OffsetDestReg).addMBB(offsetMBB)
16157 .addReg(OverflowDestReg).addMBB(overflowMBB);
16160 // Erase the pseudo instruction
16161 MI->eraseFromParent();
16166 MachineBasicBlock *
16167 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16169 MachineBasicBlock *MBB) const {
16170 // Emit code to save XMM registers to the stack. The ABI says that the
16171 // number of registers to save is given in %al, so it's theoretically
16172 // possible to do an indirect jump trick to avoid saving all of them,
16173 // however this code takes a simpler approach and just executes all
16174 // of the stores if %al is non-zero. It's less code, and it's probably
16175 // easier on the hardware branch predictor, and stores aren't all that
16176 // expensive anyway.
16178 // Create the new basic blocks. One block contains all the XMM stores,
16179 // and one block is the final destination regardless of whether any
16180 // stores were performed.
16181 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16182 MachineFunction *F = MBB->getParent();
16183 MachineFunction::iterator MBBIter = MBB;
16185 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16186 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16187 F->insert(MBBIter, XMMSaveMBB);
16188 F->insert(MBBIter, EndMBB);
16190 // Transfer the remainder of MBB and its successor edges to EndMBB.
16191 EndMBB->splice(EndMBB->begin(), MBB,
16192 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16193 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16195 // The original block will now fall through to the XMM save block.
16196 MBB->addSuccessor(XMMSaveMBB);
16197 // The XMMSaveMBB will fall through to the end block.
16198 XMMSaveMBB->addSuccessor(EndMBB);
16200 // Now add the instructions.
16201 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16202 DebugLoc DL = MI->getDebugLoc();
16204 unsigned CountReg = MI->getOperand(0).getReg();
16205 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16206 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16208 if (!Subtarget->isTargetWin64()) {
16209 // If %al is 0, branch around the XMM save block.
16210 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16211 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16212 MBB->addSuccessor(EndMBB);
16215 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16216 // that was just emitted, but clearly shouldn't be "saved".
16217 assert((MI->getNumOperands() <= 3 ||
16218 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16219 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16220 && "Expected last argument to be EFLAGS");
16221 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16222 // In the XMM save block, save all the XMM argument registers.
16223 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16224 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16225 MachineMemOperand *MMO =
16226 F->getMachineMemOperand(
16227 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16228 MachineMemOperand::MOStore,
16229 /*Size=*/16, /*Align=*/16);
16230 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16231 .addFrameIndex(RegSaveFrameIndex)
16232 .addImm(/*Scale=*/1)
16233 .addReg(/*IndexReg=*/0)
16234 .addImm(/*Disp=*/Offset)
16235 .addReg(/*Segment=*/0)
16236 .addReg(MI->getOperand(i).getReg())
16237 .addMemOperand(MMO);
16240 MI->eraseFromParent(); // The pseudo instruction is gone now.
16245 // The EFLAGS operand of SelectItr might be missing a kill marker
16246 // because there were multiple uses of EFLAGS, and ISel didn't know
16247 // which to mark. Figure out whether SelectItr should have had a
16248 // kill marker, and set it if it should. Returns the correct kill
16250 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16251 MachineBasicBlock* BB,
16252 const TargetRegisterInfo* TRI) {
16253 // Scan forward through BB for a use/def of EFLAGS.
16254 MachineBasicBlock::iterator miI(std::next(SelectItr));
16255 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16256 const MachineInstr& mi = *miI;
16257 if (mi.readsRegister(X86::EFLAGS))
16259 if (mi.definesRegister(X86::EFLAGS))
16260 break; // Should have kill-flag - update below.
16263 // If we hit the end of the block, check whether EFLAGS is live into a
16265 if (miI == BB->end()) {
16266 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16267 sEnd = BB->succ_end();
16268 sItr != sEnd; ++sItr) {
16269 MachineBasicBlock* succ = *sItr;
16270 if (succ->isLiveIn(X86::EFLAGS))
16275 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16276 // out. SelectMI should have a kill flag on EFLAGS.
16277 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16281 MachineBasicBlock *
16282 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16283 MachineBasicBlock *BB) const {
16284 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16285 DebugLoc DL = MI->getDebugLoc();
16287 // To "insert" a SELECT_CC instruction, we actually have to insert the
16288 // diamond control-flow pattern. The incoming instruction knows the
16289 // destination vreg to set, the condition code register to branch on, the
16290 // true/false values to select between, and a branch opcode to use.
16291 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16292 MachineFunction::iterator It = BB;
16298 // cmpTY ccX, r1, r2
16300 // fallthrough --> copy0MBB
16301 MachineBasicBlock *thisMBB = BB;
16302 MachineFunction *F = BB->getParent();
16303 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16304 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16305 F->insert(It, copy0MBB);
16306 F->insert(It, sinkMBB);
16308 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16309 // live into the sink and copy blocks.
16310 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16311 if (!MI->killsRegister(X86::EFLAGS) &&
16312 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16313 copy0MBB->addLiveIn(X86::EFLAGS);
16314 sinkMBB->addLiveIn(X86::EFLAGS);
16317 // Transfer the remainder of BB and its successor edges to sinkMBB.
16318 sinkMBB->splice(sinkMBB->begin(), BB,
16319 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16320 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16322 // Add the true and fallthrough blocks as its successors.
16323 BB->addSuccessor(copy0MBB);
16324 BB->addSuccessor(sinkMBB);
16326 // Create the conditional branch instruction.
16328 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16329 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16332 // %FalseValue = ...
16333 // # fallthrough to sinkMBB
16334 copy0MBB->addSuccessor(sinkMBB);
16337 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16339 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16340 TII->get(X86::PHI), MI->getOperand(0).getReg())
16341 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16342 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16344 MI->eraseFromParent(); // The pseudo instruction is gone now.
16348 MachineBasicBlock *
16349 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16350 bool Is64Bit) const {
16351 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16352 DebugLoc DL = MI->getDebugLoc();
16353 MachineFunction *MF = BB->getParent();
16354 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16356 assert(MF->shouldSplitStack());
16358 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16359 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16362 // ... [Till the alloca]
16363 // If stacklet is not large enough, jump to mallocMBB
16366 // Allocate by subtracting from RSP
16367 // Jump to continueMBB
16370 // Allocate by call to runtime
16374 // [rest of original BB]
16377 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16378 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16379 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16381 MachineRegisterInfo &MRI = MF->getRegInfo();
16382 const TargetRegisterClass *AddrRegClass =
16383 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16385 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16386 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16387 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16388 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16389 sizeVReg = MI->getOperand(1).getReg(),
16390 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16392 MachineFunction::iterator MBBIter = BB;
16395 MF->insert(MBBIter, bumpMBB);
16396 MF->insert(MBBIter, mallocMBB);
16397 MF->insert(MBBIter, continueMBB);
16399 continueMBB->splice(continueMBB->begin(), BB,
16400 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16401 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16403 // Add code to the main basic block to check if the stack limit has been hit,
16404 // and if so, jump to mallocMBB otherwise to bumpMBB.
16405 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16406 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16407 .addReg(tmpSPVReg).addReg(sizeVReg);
16408 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16409 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16410 .addReg(SPLimitVReg);
16411 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16413 // bumpMBB simply decreases the stack pointer, since we know the current
16414 // stacklet has enough space.
16415 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16416 .addReg(SPLimitVReg);
16417 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16418 .addReg(SPLimitVReg);
16419 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16421 // Calls into a routine in libgcc to allocate more space from the heap.
16422 const uint32_t *RegMask =
16423 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16425 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16427 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16428 .addExternalSymbol("__morestack_allocate_stack_space")
16429 .addRegMask(RegMask)
16430 .addReg(X86::RDI, RegState::Implicit)
16431 .addReg(X86::RAX, RegState::ImplicitDefine);
16433 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16435 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16436 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16437 .addExternalSymbol("__morestack_allocate_stack_space")
16438 .addRegMask(RegMask)
16439 .addReg(X86::EAX, RegState::ImplicitDefine);
16443 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16446 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16447 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16448 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16450 // Set up the CFG correctly.
16451 BB->addSuccessor(bumpMBB);
16452 BB->addSuccessor(mallocMBB);
16453 mallocMBB->addSuccessor(continueMBB);
16454 bumpMBB->addSuccessor(continueMBB);
16456 // Take care of the PHI nodes.
16457 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16458 MI->getOperand(0).getReg())
16459 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16460 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16462 // Delete the original pseudo instruction.
16463 MI->eraseFromParent();
16466 return continueMBB;
16469 MachineBasicBlock *
16470 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16471 MachineBasicBlock *BB) const {
16472 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16473 DebugLoc DL = MI->getDebugLoc();
16475 assert(!Subtarget->isTargetMacho());
16477 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16478 // non-trivial part is impdef of ESP.
16480 if (Subtarget->isTargetWin64()) {
16481 if (Subtarget->isTargetCygMing()) {
16482 // ___chkstk(Mingw64):
16483 // Clobbers R10, R11, RAX and EFLAGS.
16485 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16486 .addExternalSymbol("___chkstk")
16487 .addReg(X86::RAX, RegState::Implicit)
16488 .addReg(X86::RSP, RegState::Implicit)
16489 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16490 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16491 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16493 // __chkstk(MSVCRT): does not update stack pointer.
16494 // Clobbers R10, R11 and EFLAGS.
16495 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16496 .addExternalSymbol("__chkstk")
16497 .addReg(X86::RAX, RegState::Implicit)
16498 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16499 // RAX has the offset to be subtracted from RSP.
16500 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16505 const char *StackProbeSymbol =
16506 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16508 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16509 .addExternalSymbol(StackProbeSymbol)
16510 .addReg(X86::EAX, RegState::Implicit)
16511 .addReg(X86::ESP, RegState::Implicit)
16512 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16513 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16514 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16517 MI->eraseFromParent(); // The pseudo instruction is gone now.
16521 MachineBasicBlock *
16522 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16523 MachineBasicBlock *BB) const {
16524 // This is pretty easy. We're taking the value that we received from
16525 // our load from the relocation, sticking it in either RDI (x86-64)
16526 // or EAX and doing an indirect call. The return value will then
16527 // be in the normal return register.
16528 const X86InstrInfo *TII
16529 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16530 DebugLoc DL = MI->getDebugLoc();
16531 MachineFunction *F = BB->getParent();
16533 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16534 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16536 // Get a register mask for the lowered call.
16537 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16538 // proper register mask.
16539 const uint32_t *RegMask =
16540 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16541 if (Subtarget->is64Bit()) {
16542 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16543 TII->get(X86::MOV64rm), X86::RDI)
16545 .addImm(0).addReg(0)
16546 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16547 MI->getOperand(3).getTargetFlags())
16549 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16550 addDirectMem(MIB, X86::RDI);
16551 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16552 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16553 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16554 TII->get(X86::MOV32rm), X86::EAX)
16556 .addImm(0).addReg(0)
16557 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16558 MI->getOperand(3).getTargetFlags())
16560 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16561 addDirectMem(MIB, X86::EAX);
16562 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16564 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16565 TII->get(X86::MOV32rm), X86::EAX)
16566 .addReg(TII->getGlobalBaseReg(F))
16567 .addImm(0).addReg(0)
16568 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16569 MI->getOperand(3).getTargetFlags())
16571 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16572 addDirectMem(MIB, X86::EAX);
16573 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16576 MI->eraseFromParent(); // The pseudo instruction is gone now.
16580 MachineBasicBlock *
16581 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16582 MachineBasicBlock *MBB) const {
16583 DebugLoc DL = MI->getDebugLoc();
16584 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16586 MachineFunction *MF = MBB->getParent();
16587 MachineRegisterInfo &MRI = MF->getRegInfo();
16589 const BasicBlock *BB = MBB->getBasicBlock();
16590 MachineFunction::iterator I = MBB;
16593 // Memory Reference
16594 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16595 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16598 unsigned MemOpndSlot = 0;
16600 unsigned CurOp = 0;
16602 DstReg = MI->getOperand(CurOp++).getReg();
16603 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16604 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16605 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16606 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16608 MemOpndSlot = CurOp;
16610 MVT PVT = getPointerTy();
16611 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16612 "Invalid Pointer Size!");
16614 // For v = setjmp(buf), we generate
16617 // buf[LabelOffset] = restoreMBB
16618 // SjLjSetup restoreMBB
16624 // v = phi(main, restore)
16629 MachineBasicBlock *thisMBB = MBB;
16630 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16631 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16632 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16633 MF->insert(I, mainMBB);
16634 MF->insert(I, sinkMBB);
16635 MF->push_back(restoreMBB);
16637 MachineInstrBuilder MIB;
16639 // Transfer the remainder of BB and its successor edges to sinkMBB.
16640 sinkMBB->splice(sinkMBB->begin(), MBB,
16641 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16642 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16645 unsigned PtrStoreOpc = 0;
16646 unsigned LabelReg = 0;
16647 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16648 Reloc::Model RM = getTargetMachine().getRelocationModel();
16649 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16650 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16652 // Prepare IP either in reg or imm.
16653 if (!UseImmLabel) {
16654 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16655 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16656 LabelReg = MRI.createVirtualRegister(PtrRC);
16657 if (Subtarget->is64Bit()) {
16658 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16662 .addMBB(restoreMBB)
16665 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16666 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16667 .addReg(XII->getGlobalBaseReg(MF))
16670 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16674 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16676 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16677 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16678 if (i == X86::AddrDisp)
16679 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16681 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16684 MIB.addReg(LabelReg);
16686 MIB.addMBB(restoreMBB);
16687 MIB.setMemRefs(MMOBegin, MMOEnd);
16689 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16690 .addMBB(restoreMBB);
16692 const X86RegisterInfo *RegInfo =
16693 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16694 MIB.addRegMask(RegInfo->getNoPreservedMask());
16695 thisMBB->addSuccessor(mainMBB);
16696 thisMBB->addSuccessor(restoreMBB);
16700 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16701 mainMBB->addSuccessor(sinkMBB);
16704 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16705 TII->get(X86::PHI), DstReg)
16706 .addReg(mainDstReg).addMBB(mainMBB)
16707 .addReg(restoreDstReg).addMBB(restoreMBB);
16710 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16711 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16712 restoreMBB->addSuccessor(sinkMBB);
16714 MI->eraseFromParent();
16718 MachineBasicBlock *
16719 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16720 MachineBasicBlock *MBB) const {
16721 DebugLoc DL = MI->getDebugLoc();
16722 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16724 MachineFunction *MF = MBB->getParent();
16725 MachineRegisterInfo &MRI = MF->getRegInfo();
16727 // Memory Reference
16728 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16729 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16731 MVT PVT = getPointerTy();
16732 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16733 "Invalid Pointer Size!");
16735 const TargetRegisterClass *RC =
16736 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16737 unsigned Tmp = MRI.createVirtualRegister(RC);
16738 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16739 const X86RegisterInfo *RegInfo =
16740 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16741 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16742 unsigned SP = RegInfo->getStackRegister();
16744 MachineInstrBuilder MIB;
16746 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16747 const int64_t SPOffset = 2 * PVT.getStoreSize();
16749 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16750 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16753 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16754 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16755 MIB.addOperand(MI->getOperand(i));
16756 MIB.setMemRefs(MMOBegin, MMOEnd);
16758 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16759 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16760 if (i == X86::AddrDisp)
16761 MIB.addDisp(MI->getOperand(i), LabelOffset);
16763 MIB.addOperand(MI->getOperand(i));
16765 MIB.setMemRefs(MMOBegin, MMOEnd);
16767 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16768 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16769 if (i == X86::AddrDisp)
16770 MIB.addDisp(MI->getOperand(i), SPOffset);
16772 MIB.addOperand(MI->getOperand(i));
16774 MIB.setMemRefs(MMOBegin, MMOEnd);
16776 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16778 MI->eraseFromParent();
16782 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16783 // accumulator loops. Writing back to the accumulator allows the coalescer
16784 // to remove extra copies in the loop.
16785 MachineBasicBlock *
16786 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16787 MachineBasicBlock *MBB) const {
16788 MachineOperand &AddendOp = MI->getOperand(3);
16790 // Bail out early if the addend isn't a register - we can't switch these.
16791 if (!AddendOp.isReg())
16794 MachineFunction &MF = *MBB->getParent();
16795 MachineRegisterInfo &MRI = MF.getRegInfo();
16797 // Check whether the addend is defined by a PHI:
16798 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16799 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16800 if (!AddendDef.isPHI())
16803 // Look for the following pattern:
16805 // %addend = phi [%entry, 0], [%loop, %result]
16807 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16811 // %addend = phi [%entry, 0], [%loop, %result]
16813 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16815 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16816 assert(AddendDef.getOperand(i).isReg());
16817 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16818 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16819 if (&PHISrcInst == MI) {
16820 // Found a matching instruction.
16821 unsigned NewFMAOpc = 0;
16822 switch (MI->getOpcode()) {
16823 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16824 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16825 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16826 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16827 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16828 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16829 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16830 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16831 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16832 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16833 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16834 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16835 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16836 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16837 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16838 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16839 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16840 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16841 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16842 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16843 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16844 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16845 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16846 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16847 default: llvm_unreachable("Unrecognized FMA variant.");
16850 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16851 MachineInstrBuilder MIB =
16852 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16853 .addOperand(MI->getOperand(0))
16854 .addOperand(MI->getOperand(3))
16855 .addOperand(MI->getOperand(2))
16856 .addOperand(MI->getOperand(1));
16857 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16858 MI->eraseFromParent();
16865 MachineBasicBlock *
16866 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16867 MachineBasicBlock *BB) const {
16868 switch (MI->getOpcode()) {
16869 default: llvm_unreachable("Unexpected instr type to insert");
16870 case X86::TAILJMPd64:
16871 case X86::TAILJMPr64:
16872 case X86::TAILJMPm64:
16873 llvm_unreachable("TAILJMP64 would not be touched here.");
16874 case X86::TCRETURNdi64:
16875 case X86::TCRETURNri64:
16876 case X86::TCRETURNmi64:
16878 case X86::WIN_ALLOCA:
16879 return EmitLoweredWinAlloca(MI, BB);
16880 case X86::SEG_ALLOCA_32:
16881 return EmitLoweredSegAlloca(MI, BB, false);
16882 case X86::SEG_ALLOCA_64:
16883 return EmitLoweredSegAlloca(MI, BB, true);
16884 case X86::TLSCall_32:
16885 case X86::TLSCall_64:
16886 return EmitLoweredTLSCall(MI, BB);
16887 case X86::CMOV_GR8:
16888 case X86::CMOV_FR32:
16889 case X86::CMOV_FR64:
16890 case X86::CMOV_V4F32:
16891 case X86::CMOV_V2F64:
16892 case X86::CMOV_V2I64:
16893 case X86::CMOV_V8F32:
16894 case X86::CMOV_V4F64:
16895 case X86::CMOV_V4I64:
16896 case X86::CMOV_V16F32:
16897 case X86::CMOV_V8F64:
16898 case X86::CMOV_V8I64:
16899 case X86::CMOV_GR16:
16900 case X86::CMOV_GR32:
16901 case X86::CMOV_RFP32:
16902 case X86::CMOV_RFP64:
16903 case X86::CMOV_RFP80:
16904 return EmitLoweredSelect(MI, BB);
16906 case X86::FP32_TO_INT16_IN_MEM:
16907 case X86::FP32_TO_INT32_IN_MEM:
16908 case X86::FP32_TO_INT64_IN_MEM:
16909 case X86::FP64_TO_INT16_IN_MEM:
16910 case X86::FP64_TO_INT32_IN_MEM:
16911 case X86::FP64_TO_INT64_IN_MEM:
16912 case X86::FP80_TO_INT16_IN_MEM:
16913 case X86::FP80_TO_INT32_IN_MEM:
16914 case X86::FP80_TO_INT64_IN_MEM: {
16915 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16916 DebugLoc DL = MI->getDebugLoc();
16918 // Change the floating point control register to use "round towards zero"
16919 // mode when truncating to an integer value.
16920 MachineFunction *F = BB->getParent();
16921 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16922 addFrameReference(BuildMI(*BB, MI, DL,
16923 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16925 // Load the old value of the high byte of the control word...
16927 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16928 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16931 // Set the high part to be round to zero...
16932 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16935 // Reload the modified control word now...
16936 addFrameReference(BuildMI(*BB, MI, DL,
16937 TII->get(X86::FLDCW16m)), CWFrameIdx);
16939 // Restore the memory image of control word to original value
16940 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16943 // Get the X86 opcode to use.
16945 switch (MI->getOpcode()) {
16946 default: llvm_unreachable("illegal opcode!");
16947 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16948 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16949 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16950 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16951 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16952 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16953 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16954 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16955 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16959 MachineOperand &Op = MI->getOperand(0);
16961 AM.BaseType = X86AddressMode::RegBase;
16962 AM.Base.Reg = Op.getReg();
16964 AM.BaseType = X86AddressMode::FrameIndexBase;
16965 AM.Base.FrameIndex = Op.getIndex();
16967 Op = MI->getOperand(1);
16969 AM.Scale = Op.getImm();
16970 Op = MI->getOperand(2);
16972 AM.IndexReg = Op.getImm();
16973 Op = MI->getOperand(3);
16974 if (Op.isGlobal()) {
16975 AM.GV = Op.getGlobal();
16977 AM.Disp = Op.getImm();
16979 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16980 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16982 // Reload the original control word now.
16983 addFrameReference(BuildMI(*BB, MI, DL,
16984 TII->get(X86::FLDCW16m)), CWFrameIdx);
16986 MI->eraseFromParent(); // The pseudo instruction is gone now.
16989 // String/text processing lowering.
16990 case X86::PCMPISTRM128REG:
16991 case X86::VPCMPISTRM128REG:
16992 case X86::PCMPISTRM128MEM:
16993 case X86::VPCMPISTRM128MEM:
16994 case X86::PCMPESTRM128REG:
16995 case X86::VPCMPESTRM128REG:
16996 case X86::PCMPESTRM128MEM:
16997 case X86::VPCMPESTRM128MEM:
16998 assert(Subtarget->hasSSE42() &&
16999 "Target must have SSE4.2 or AVX features enabled");
17000 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17002 // String/text processing lowering.
17003 case X86::PCMPISTRIREG:
17004 case X86::VPCMPISTRIREG:
17005 case X86::PCMPISTRIMEM:
17006 case X86::VPCMPISTRIMEM:
17007 case X86::PCMPESTRIREG:
17008 case X86::VPCMPESTRIREG:
17009 case X86::PCMPESTRIMEM:
17010 case X86::VPCMPESTRIMEM:
17011 assert(Subtarget->hasSSE42() &&
17012 "Target must have SSE4.2 or AVX features enabled");
17013 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17015 // Thread synchronization.
17017 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17021 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17023 // Atomic Lowering.
17024 case X86::ATOMAND8:
17025 case X86::ATOMAND16:
17026 case X86::ATOMAND32:
17027 case X86::ATOMAND64:
17030 case X86::ATOMOR16:
17031 case X86::ATOMOR32:
17032 case X86::ATOMOR64:
17034 case X86::ATOMXOR16:
17035 case X86::ATOMXOR8:
17036 case X86::ATOMXOR32:
17037 case X86::ATOMXOR64:
17039 case X86::ATOMNAND8:
17040 case X86::ATOMNAND16:
17041 case X86::ATOMNAND32:
17042 case X86::ATOMNAND64:
17044 case X86::ATOMMAX8:
17045 case X86::ATOMMAX16:
17046 case X86::ATOMMAX32:
17047 case X86::ATOMMAX64:
17049 case X86::ATOMMIN8:
17050 case X86::ATOMMIN16:
17051 case X86::ATOMMIN32:
17052 case X86::ATOMMIN64:
17054 case X86::ATOMUMAX8:
17055 case X86::ATOMUMAX16:
17056 case X86::ATOMUMAX32:
17057 case X86::ATOMUMAX64:
17059 case X86::ATOMUMIN8:
17060 case X86::ATOMUMIN16:
17061 case X86::ATOMUMIN32:
17062 case X86::ATOMUMIN64:
17063 return EmitAtomicLoadArith(MI, BB);
17065 // This group does 64-bit operations on a 32-bit host.
17066 case X86::ATOMAND6432:
17067 case X86::ATOMOR6432:
17068 case X86::ATOMXOR6432:
17069 case X86::ATOMNAND6432:
17070 case X86::ATOMADD6432:
17071 case X86::ATOMSUB6432:
17072 case X86::ATOMMAX6432:
17073 case X86::ATOMMIN6432:
17074 case X86::ATOMUMAX6432:
17075 case X86::ATOMUMIN6432:
17076 case X86::ATOMSWAP6432:
17077 return EmitAtomicLoadArith6432(MI, BB);
17079 case X86::VASTART_SAVE_XMM_REGS:
17080 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17082 case X86::VAARG_64:
17083 return EmitVAARG64WithCustomInserter(MI, BB);
17085 case X86::EH_SjLj_SetJmp32:
17086 case X86::EH_SjLj_SetJmp64:
17087 return emitEHSjLjSetJmp(MI, BB);
17089 case X86::EH_SjLj_LongJmp32:
17090 case X86::EH_SjLj_LongJmp64:
17091 return emitEHSjLjLongJmp(MI, BB);
17093 case TargetOpcode::STACKMAP:
17094 case TargetOpcode::PATCHPOINT:
17095 return emitPatchPoint(MI, BB);
17097 case X86::VFMADDPDr213r:
17098 case X86::VFMADDPSr213r:
17099 case X86::VFMADDSDr213r:
17100 case X86::VFMADDSSr213r:
17101 case X86::VFMSUBPDr213r:
17102 case X86::VFMSUBPSr213r:
17103 case X86::VFMSUBSDr213r:
17104 case X86::VFMSUBSSr213r:
17105 case X86::VFNMADDPDr213r:
17106 case X86::VFNMADDPSr213r:
17107 case X86::VFNMADDSDr213r:
17108 case X86::VFNMADDSSr213r:
17109 case X86::VFNMSUBPDr213r:
17110 case X86::VFNMSUBPSr213r:
17111 case X86::VFNMSUBSDr213r:
17112 case X86::VFNMSUBSSr213r:
17113 case X86::VFMADDPDr213rY:
17114 case X86::VFMADDPSr213rY:
17115 case X86::VFMSUBPDr213rY:
17116 case X86::VFMSUBPSr213rY:
17117 case X86::VFNMADDPDr213rY:
17118 case X86::VFNMADDPSr213rY:
17119 case X86::VFNMSUBPDr213rY:
17120 case X86::VFNMSUBPSr213rY:
17121 return emitFMA3Instr(MI, BB);
17125 //===----------------------------------------------------------------------===//
17126 // X86 Optimization Hooks
17127 //===----------------------------------------------------------------------===//
17129 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17132 const SelectionDAG &DAG,
17133 unsigned Depth) const {
17134 unsigned BitWidth = KnownZero.getBitWidth();
17135 unsigned Opc = Op.getOpcode();
17136 assert((Opc >= ISD::BUILTIN_OP_END ||
17137 Opc == ISD::INTRINSIC_WO_CHAIN ||
17138 Opc == ISD::INTRINSIC_W_CHAIN ||
17139 Opc == ISD::INTRINSIC_VOID) &&
17140 "Should use MaskedValueIsZero if you don't know whether Op"
17141 " is a target node!");
17143 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17157 // These nodes' second result is a boolean.
17158 if (Op.getResNo() == 0)
17161 case X86ISD::SETCC:
17162 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17164 case ISD::INTRINSIC_WO_CHAIN: {
17165 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17166 unsigned NumLoBits = 0;
17169 case Intrinsic::x86_sse_movmsk_ps:
17170 case Intrinsic::x86_avx_movmsk_ps_256:
17171 case Intrinsic::x86_sse2_movmsk_pd:
17172 case Intrinsic::x86_avx_movmsk_pd_256:
17173 case Intrinsic::x86_mmx_pmovmskb:
17174 case Intrinsic::x86_sse2_pmovmskb_128:
17175 case Intrinsic::x86_avx2_pmovmskb: {
17176 // High bits of movmskp{s|d}, pmovmskb are known zero.
17178 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17179 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17180 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17181 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17182 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17183 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17184 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17185 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17187 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17196 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17198 const SelectionDAG &,
17199 unsigned Depth) const {
17200 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17201 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17202 return Op.getValueType().getScalarType().getSizeInBits();
17208 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17209 /// node is a GlobalAddress + offset.
17210 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17211 const GlobalValue* &GA,
17212 int64_t &Offset) const {
17213 if (N->getOpcode() == X86ISD::Wrapper) {
17214 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17215 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17216 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17220 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17223 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17224 /// same as extracting the high 128-bit part of 256-bit vector and then
17225 /// inserting the result into the low part of a new 256-bit vector
17226 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17227 EVT VT = SVOp->getValueType(0);
17228 unsigned NumElems = VT.getVectorNumElements();
17230 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17231 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17232 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17233 SVOp->getMaskElt(j) >= 0)
17239 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17240 /// same as extracting the low 128-bit part of 256-bit vector and then
17241 /// inserting the result into the high part of a new 256-bit vector
17242 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17243 EVT VT = SVOp->getValueType(0);
17244 unsigned NumElems = VT.getVectorNumElements();
17246 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17247 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17248 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17249 SVOp->getMaskElt(j) >= 0)
17255 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17256 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17257 TargetLowering::DAGCombinerInfo &DCI,
17258 const X86Subtarget* Subtarget) {
17260 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17261 SDValue V1 = SVOp->getOperand(0);
17262 SDValue V2 = SVOp->getOperand(1);
17263 EVT VT = SVOp->getValueType(0);
17264 unsigned NumElems = VT.getVectorNumElements();
17266 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17267 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17271 // V UNDEF BUILD_VECTOR UNDEF
17273 // CONCAT_VECTOR CONCAT_VECTOR
17276 // RESULT: V + zero extended
17278 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17279 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17280 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17283 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17286 // To match the shuffle mask, the first half of the mask should
17287 // be exactly the first vector, and all the rest a splat with the
17288 // first element of the second one.
17289 for (unsigned i = 0; i != NumElems/2; ++i)
17290 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17291 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17294 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17295 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17296 if (Ld->hasNUsesOfValue(1, 0)) {
17297 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17298 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17300 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17302 Ld->getPointerInfo(),
17303 Ld->getAlignment(),
17304 false/*isVolatile*/, true/*ReadMem*/,
17305 false/*WriteMem*/);
17307 // Make sure the newly-created LOAD is in the same position as Ld in
17308 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17309 // and update uses of Ld's output chain to use the TokenFactor.
17310 if (Ld->hasAnyUseOfValue(1)) {
17311 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17312 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17313 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17314 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17315 SDValue(ResNode.getNode(), 1));
17318 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17322 // Emit a zeroed vector and insert the desired subvector on its
17324 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17325 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17326 return DCI.CombineTo(N, InsV);
17329 //===--------------------------------------------------------------------===//
17330 // Combine some shuffles into subvector extracts and inserts:
17333 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17334 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17335 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17336 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17337 return DCI.CombineTo(N, InsV);
17340 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17341 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17342 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17343 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17344 return DCI.CombineTo(N, InsV);
17350 /// PerformShuffleCombine - Performs several different shuffle combines.
17351 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17352 TargetLowering::DAGCombinerInfo &DCI,
17353 const X86Subtarget *Subtarget) {
17355 EVT VT = N->getValueType(0);
17357 // Don't create instructions with illegal types after legalize types has run.
17358 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17359 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17362 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17363 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17364 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17365 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17367 // Only handle 128 wide vector from here on.
17368 if (!VT.is128BitVector())
17371 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17372 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17373 // consecutive, non-overlapping, and in the right order.
17374 SmallVector<SDValue, 16> Elts;
17375 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17376 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17378 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17381 /// PerformTruncateCombine - Converts truncate operation to
17382 /// a sequence of vector shuffle operations.
17383 /// It is possible when we truncate 256-bit vector to 128-bit vector
17384 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17385 TargetLowering::DAGCombinerInfo &DCI,
17386 const X86Subtarget *Subtarget) {
17390 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17391 /// specific shuffle of a load can be folded into a single element load.
17392 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17393 /// shuffles have been customed lowered so we need to handle those here.
17394 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17395 TargetLowering::DAGCombinerInfo &DCI) {
17396 if (DCI.isBeforeLegalizeOps())
17399 SDValue InVec = N->getOperand(0);
17400 SDValue EltNo = N->getOperand(1);
17402 if (!isa<ConstantSDNode>(EltNo))
17405 EVT VT = InVec.getValueType();
17407 bool HasShuffleIntoBitcast = false;
17408 if (InVec.getOpcode() == ISD::BITCAST) {
17409 // Don't duplicate a load with other uses.
17410 if (!InVec.hasOneUse())
17412 EVT BCVT = InVec.getOperand(0).getValueType();
17413 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17415 InVec = InVec.getOperand(0);
17416 HasShuffleIntoBitcast = true;
17419 if (!isTargetShuffle(InVec.getOpcode()))
17422 // Don't duplicate a load with other uses.
17423 if (!InVec.hasOneUse())
17426 SmallVector<int, 16> ShuffleMask;
17428 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17432 // Select the input vector, guarding against out of range extract vector.
17433 unsigned NumElems = VT.getVectorNumElements();
17434 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17435 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17436 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17437 : InVec.getOperand(1);
17439 // If inputs to shuffle are the same for both ops, then allow 2 uses
17440 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17442 if (LdNode.getOpcode() == ISD::BITCAST) {
17443 // Don't duplicate a load with other uses.
17444 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17447 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17448 LdNode = LdNode.getOperand(0);
17451 if (!ISD::isNormalLoad(LdNode.getNode()))
17454 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17456 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17459 if (HasShuffleIntoBitcast) {
17460 // If there's a bitcast before the shuffle, check if the load type and
17461 // alignment is valid.
17462 unsigned Align = LN0->getAlignment();
17463 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17464 unsigned NewAlign = TLI.getDataLayout()->
17465 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17467 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17471 // All checks match so transform back to vector_shuffle so that DAG combiner
17472 // can finish the job
17475 // Create shuffle node taking into account the case that its a unary shuffle
17476 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17477 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17478 InVec.getOperand(0), Shuffle,
17480 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17481 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17485 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17486 /// generation and convert it from being a bunch of shuffles and extracts
17487 /// to a simple store and scalar loads to extract the elements.
17488 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17489 TargetLowering::DAGCombinerInfo &DCI) {
17490 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17491 if (NewOp.getNode())
17494 SDValue InputVector = N->getOperand(0);
17496 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17497 // from mmx to v2i32 has a single usage.
17498 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17499 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17500 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17501 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17502 N->getValueType(0),
17503 InputVector.getNode()->getOperand(0));
17505 // Only operate on vectors of 4 elements, where the alternative shuffling
17506 // gets to be more expensive.
17507 if (InputVector.getValueType() != MVT::v4i32)
17510 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17511 // single use which is a sign-extend or zero-extend, and all elements are
17513 SmallVector<SDNode *, 4> Uses;
17514 unsigned ExtractedElements = 0;
17515 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17516 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17517 if (UI.getUse().getResNo() != InputVector.getResNo())
17520 SDNode *Extract = *UI;
17521 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17524 if (Extract->getValueType(0) != MVT::i32)
17526 if (!Extract->hasOneUse())
17528 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17529 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17531 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17534 // Record which element was extracted.
17535 ExtractedElements |=
17536 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17538 Uses.push_back(Extract);
17541 // If not all the elements were used, this may not be worthwhile.
17542 if (ExtractedElements != 15)
17545 // Ok, we've now decided to do the transformation.
17546 SDLoc dl(InputVector);
17548 // Store the value to a temporary stack slot.
17549 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17550 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17551 MachinePointerInfo(), false, false, 0);
17553 // Replace each use (extract) with a load of the appropriate element.
17554 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17555 UE = Uses.end(); UI != UE; ++UI) {
17556 SDNode *Extract = *UI;
17558 // cOMpute the element's address.
17559 SDValue Idx = Extract->getOperand(1);
17561 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17562 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17563 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17564 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17566 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17567 StackPtr, OffsetVal);
17569 // Load the scalar.
17570 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17571 ScalarAddr, MachinePointerInfo(),
17572 false, false, false, 0);
17574 // Replace the exact with the load.
17575 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17578 // The replacement was made in place; don't return anything.
17582 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17583 static std::pair<unsigned, bool>
17584 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17585 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17586 if (!VT.isVector())
17587 return std::make_pair(0, false);
17589 bool NeedSplit = false;
17590 switch (VT.getSimpleVT().SimpleTy) {
17591 default: return std::make_pair(0, false);
17595 if (!Subtarget->hasAVX2())
17597 if (!Subtarget->hasAVX())
17598 return std::make_pair(0, false);
17603 if (!Subtarget->hasSSE2())
17604 return std::make_pair(0, false);
17607 // SSE2 has only a small subset of the operations.
17608 bool hasUnsigned = Subtarget->hasSSE41() ||
17609 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17610 bool hasSigned = Subtarget->hasSSE41() ||
17611 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17613 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17616 // Check for x CC y ? x : y.
17617 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17618 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17623 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17626 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17629 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17632 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17634 // Check for x CC y ? y : x -- a min/max with reversed arms.
17635 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17636 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17641 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17644 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17647 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17650 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17654 return std::make_pair(Opc, NeedSplit);
17657 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17659 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17660 TargetLowering::DAGCombinerInfo &DCI,
17661 const X86Subtarget *Subtarget) {
17663 SDValue Cond = N->getOperand(0);
17664 // Get the LHS/RHS of the select.
17665 SDValue LHS = N->getOperand(1);
17666 SDValue RHS = N->getOperand(2);
17667 EVT VT = LHS.getValueType();
17668 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17670 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17671 // instructions match the semantics of the common C idiom x<y?x:y but not
17672 // x<=y?x:y, because of how they handle negative zero (which can be
17673 // ignored in unsafe-math mode).
17674 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17675 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17676 (Subtarget->hasSSE2() ||
17677 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17678 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17680 unsigned Opcode = 0;
17681 // Check for x CC y ? x : y.
17682 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17683 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17687 // Converting this to a min would handle NaNs incorrectly, and swapping
17688 // the operands would cause it to handle comparisons between positive
17689 // and negative zero incorrectly.
17690 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17691 if (!DAG.getTarget().Options.UnsafeFPMath &&
17692 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17694 std::swap(LHS, RHS);
17696 Opcode = X86ISD::FMIN;
17699 // Converting this to a min would handle comparisons between positive
17700 // and negative zero incorrectly.
17701 if (!DAG.getTarget().Options.UnsafeFPMath &&
17702 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17704 Opcode = X86ISD::FMIN;
17707 // Converting this to a min would handle both negative zeros and NaNs
17708 // incorrectly, but we can swap the operands to fix both.
17709 std::swap(LHS, RHS);
17713 Opcode = X86ISD::FMIN;
17717 // Converting this to a max would handle comparisons between positive
17718 // and negative zero incorrectly.
17719 if (!DAG.getTarget().Options.UnsafeFPMath &&
17720 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17722 Opcode = X86ISD::FMAX;
17725 // Converting this to a max would handle NaNs incorrectly, and swapping
17726 // the operands would cause it to handle comparisons between positive
17727 // and negative zero incorrectly.
17728 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17729 if (!DAG.getTarget().Options.UnsafeFPMath &&
17730 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17732 std::swap(LHS, RHS);
17734 Opcode = X86ISD::FMAX;
17737 // Converting this to a max would handle both negative zeros and NaNs
17738 // incorrectly, but we can swap the operands to fix both.
17739 std::swap(LHS, RHS);
17743 Opcode = X86ISD::FMAX;
17746 // Check for x CC y ? y : x -- a min/max with reversed arms.
17747 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17748 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17752 // Converting this to a min would handle comparisons between positive
17753 // and negative zero incorrectly, and swapping the operands would
17754 // cause it to handle NaNs incorrectly.
17755 if (!DAG.getTarget().Options.UnsafeFPMath &&
17756 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17757 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17759 std::swap(LHS, RHS);
17761 Opcode = X86ISD::FMIN;
17764 // Converting this to a min would handle NaNs incorrectly.
17765 if (!DAG.getTarget().Options.UnsafeFPMath &&
17766 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17768 Opcode = X86ISD::FMIN;
17771 // Converting this to a min would handle both negative zeros and NaNs
17772 // incorrectly, but we can swap the operands to fix both.
17773 std::swap(LHS, RHS);
17777 Opcode = X86ISD::FMIN;
17781 // Converting this to a max would handle NaNs incorrectly.
17782 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17784 Opcode = X86ISD::FMAX;
17787 // Converting this to a max would handle comparisons between positive
17788 // and negative zero incorrectly, and swapping the operands would
17789 // cause it to handle NaNs incorrectly.
17790 if (!DAG.getTarget().Options.UnsafeFPMath &&
17791 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17792 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17794 std::swap(LHS, RHS);
17796 Opcode = X86ISD::FMAX;
17799 // Converting this to a max would handle both negative zeros and NaNs
17800 // incorrectly, but we can swap the operands to fix both.
17801 std::swap(LHS, RHS);
17805 Opcode = X86ISD::FMAX;
17811 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17814 EVT CondVT = Cond.getValueType();
17815 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17816 CondVT.getVectorElementType() == MVT::i1) {
17817 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17818 // lowering on AVX-512. In this case we convert it to
17819 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17820 // The same situation for all 128 and 256-bit vectors of i8 and i16
17821 EVT OpVT = LHS.getValueType();
17822 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17823 (OpVT.getVectorElementType() == MVT::i8 ||
17824 OpVT.getVectorElementType() == MVT::i16)) {
17825 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17826 DCI.AddToWorklist(Cond.getNode());
17827 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17830 // If this is a select between two integer constants, try to do some
17832 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17833 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17834 // Don't do this for crazy integer types.
17835 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17836 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17837 // so that TrueC (the true value) is larger than FalseC.
17838 bool NeedsCondInvert = false;
17840 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17841 // Efficiently invertible.
17842 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17843 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17844 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17845 NeedsCondInvert = true;
17846 std::swap(TrueC, FalseC);
17849 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17850 if (FalseC->getAPIntValue() == 0 &&
17851 TrueC->getAPIntValue().isPowerOf2()) {
17852 if (NeedsCondInvert) // Invert the condition if needed.
17853 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17854 DAG.getConstant(1, Cond.getValueType()));
17856 // Zero extend the condition if needed.
17857 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17859 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17860 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17861 DAG.getConstant(ShAmt, MVT::i8));
17864 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17865 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17866 if (NeedsCondInvert) // Invert the condition if needed.
17867 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17868 DAG.getConstant(1, Cond.getValueType()));
17870 // Zero extend the condition if needed.
17871 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17872 FalseC->getValueType(0), Cond);
17873 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17874 SDValue(FalseC, 0));
17877 // Optimize cases that will turn into an LEA instruction. This requires
17878 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17879 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17880 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17881 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17883 bool isFastMultiplier = false;
17885 switch ((unsigned char)Diff) {
17887 case 1: // result = add base, cond
17888 case 2: // result = lea base( , cond*2)
17889 case 3: // result = lea base(cond, cond*2)
17890 case 4: // result = lea base( , cond*4)
17891 case 5: // result = lea base(cond, cond*4)
17892 case 8: // result = lea base( , cond*8)
17893 case 9: // result = lea base(cond, cond*8)
17894 isFastMultiplier = true;
17899 if (isFastMultiplier) {
17900 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17901 if (NeedsCondInvert) // Invert the condition if needed.
17902 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17903 DAG.getConstant(1, Cond.getValueType()));
17905 // Zero extend the condition if needed.
17906 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17908 // Scale the condition by the difference.
17910 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17911 DAG.getConstant(Diff, Cond.getValueType()));
17913 // Add the base if non-zero.
17914 if (FalseC->getAPIntValue() != 0)
17915 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17916 SDValue(FalseC, 0));
17923 // Canonicalize max and min:
17924 // (x > y) ? x : y -> (x >= y) ? x : y
17925 // (x < y) ? x : y -> (x <= y) ? x : y
17926 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17927 // the need for an extra compare
17928 // against zero. e.g.
17929 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17931 // testl %edi, %edi
17933 // cmovgl %edi, %eax
17937 // cmovsl %eax, %edi
17938 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17939 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17940 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17941 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17946 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17947 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17948 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17949 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17954 // Early exit check
17955 if (!TLI.isTypeLegal(VT))
17958 // Match VSELECTs into subs with unsigned saturation.
17959 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17960 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17961 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17962 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17963 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17965 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17966 // left side invert the predicate to simplify logic below.
17968 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17970 CC = ISD::getSetCCInverse(CC, true);
17971 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17975 if (Other.getNode() && Other->getNumOperands() == 2 &&
17976 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17977 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17978 SDValue CondRHS = Cond->getOperand(1);
17980 // Look for a general sub with unsigned saturation first.
17981 // x >= y ? x-y : 0 --> subus x, y
17982 // x > y ? x-y : 0 --> subus x, y
17983 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17984 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17985 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17987 // If the RHS is a constant we have to reverse the const canonicalization.
17988 // x > C-1 ? x+-C : 0 --> subus x, C
17989 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17990 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17991 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17992 if (CondRHS.getConstantOperandVal(0) == -A-1)
17993 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17994 DAG.getConstant(-A, VT));
17997 // Another special case: If C was a sign bit, the sub has been
17998 // canonicalized into a xor.
17999 // FIXME: Would it be better to use computeKnownBits to determine whether
18000 // it's safe to decanonicalize the xor?
18001 // x s< 0 ? x^C : 0 --> subus x, C
18002 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18003 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18004 isSplatVector(OpRHS.getNode())) {
18005 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18007 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18012 // Try to match a min/max vector operation.
18013 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18014 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18015 unsigned Opc = ret.first;
18016 bool NeedSplit = ret.second;
18018 if (Opc && NeedSplit) {
18019 unsigned NumElems = VT.getVectorNumElements();
18020 // Extract the LHS vectors
18021 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18022 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18024 // Extract the RHS vectors
18025 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18026 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18028 // Create min/max for each subvector
18029 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18030 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18032 // Merge the result
18033 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18035 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18038 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18039 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18040 // Check if SETCC has already been promoted
18041 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18042 // Check that condition value type matches vselect operand type
18045 assert(Cond.getValueType().isVector() &&
18046 "vector select expects a vector selector!");
18048 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18049 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18051 if (!TValIsAllOnes && !FValIsAllZeros) {
18052 // Try invert the condition if true value is not all 1s and false value
18054 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18055 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18057 if (TValIsAllZeros || FValIsAllOnes) {
18058 SDValue CC = Cond.getOperand(2);
18059 ISD::CondCode NewCC =
18060 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18061 Cond.getOperand(0).getValueType().isInteger());
18062 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18063 std::swap(LHS, RHS);
18064 TValIsAllOnes = FValIsAllOnes;
18065 FValIsAllZeros = TValIsAllZeros;
18069 if (TValIsAllOnes || FValIsAllZeros) {
18072 if (TValIsAllOnes && FValIsAllZeros)
18074 else if (TValIsAllOnes)
18075 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18076 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18077 else if (FValIsAllZeros)
18078 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18079 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18081 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18085 // Try to fold this VSELECT into a MOVSS/MOVSD
18086 if (N->getOpcode() == ISD::VSELECT &&
18087 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18088 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18089 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18090 bool CanFold = false;
18091 unsigned NumElems = Cond.getNumOperands();
18095 if (isZero(Cond.getOperand(0))) {
18098 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18099 // fold (vselect <0,-1> -> (movsd A, B)
18100 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18101 CanFold = isAllOnes(Cond.getOperand(i));
18102 } else if (isAllOnes(Cond.getOperand(0))) {
18106 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18107 // fold (vselect <-1,0> -> (movsd B, A)
18108 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18109 CanFold = isZero(Cond.getOperand(i));
18113 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18114 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18115 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18118 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18119 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18120 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18121 // (v2i64 (bitcast B)))))
18123 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18124 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18125 // (v2f64 (bitcast B)))))
18127 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18128 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18129 // (v2i64 (bitcast A)))))
18131 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18132 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18133 // (v2f64 (bitcast A)))))
18135 CanFold = (isZero(Cond.getOperand(0)) &&
18136 isZero(Cond.getOperand(1)) &&
18137 isAllOnes(Cond.getOperand(2)) &&
18138 isAllOnes(Cond.getOperand(3)));
18140 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18141 isAllOnes(Cond.getOperand(1)) &&
18142 isZero(Cond.getOperand(2)) &&
18143 isZero(Cond.getOperand(3))) {
18145 std::swap(LHS, RHS);
18149 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18150 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18151 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18152 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18154 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18160 // If we know that this node is legal then we know that it is going to be
18161 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18162 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18163 // to simplify previous instructions.
18164 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18165 !DCI.isBeforeLegalize() &&
18166 // We explicitly check against v8i16 and v16i16 because, although
18167 // they're marked as Custom, they might only be legal when Cond is a
18168 // build_vector of constants. This will be taken care in a later
18170 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18171 VT != MVT::v8i16)) {
18172 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18174 // Don't optimize vector selects that map to mask-registers.
18178 // Check all uses of that condition operand to check whether it will be
18179 // consumed by non-BLEND instructions, which may depend on all bits are set
18181 for (SDNode::use_iterator I = Cond->use_begin(),
18182 E = Cond->use_end(); I != E; ++I)
18183 if (I->getOpcode() != ISD::VSELECT)
18184 // TODO: Add other opcodes eventually lowered into BLEND.
18187 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18188 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18190 APInt KnownZero, KnownOne;
18191 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18192 DCI.isBeforeLegalizeOps());
18193 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18194 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18195 DCI.CommitTargetLoweringOpt(TLO);
18201 // Check whether a boolean test is testing a boolean value generated by
18202 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18205 // Simplify the following patterns:
18206 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18207 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18208 // to (Op EFLAGS Cond)
18210 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18211 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18212 // to (Op EFLAGS !Cond)
18214 // where Op could be BRCOND or CMOV.
18216 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18217 // Quit if not CMP and SUB with its value result used.
18218 if (Cmp.getOpcode() != X86ISD::CMP &&
18219 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18222 // Quit if not used as a boolean value.
18223 if (CC != X86::COND_E && CC != X86::COND_NE)
18226 // Check CMP operands. One of them should be 0 or 1 and the other should be
18227 // an SetCC or extended from it.
18228 SDValue Op1 = Cmp.getOperand(0);
18229 SDValue Op2 = Cmp.getOperand(1);
18232 const ConstantSDNode* C = nullptr;
18233 bool needOppositeCond = (CC == X86::COND_E);
18234 bool checkAgainstTrue = false; // Is it a comparison against 1?
18236 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18238 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18240 else // Quit if all operands are not constants.
18243 if (C->getZExtValue() == 1) {
18244 needOppositeCond = !needOppositeCond;
18245 checkAgainstTrue = true;
18246 } else if (C->getZExtValue() != 0)
18247 // Quit if the constant is neither 0 or 1.
18250 bool truncatedToBoolWithAnd = false;
18251 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18252 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18253 SetCC.getOpcode() == ISD::TRUNCATE ||
18254 SetCC.getOpcode() == ISD::AND) {
18255 if (SetCC.getOpcode() == ISD::AND) {
18257 ConstantSDNode *CS;
18258 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18259 CS->getZExtValue() == 1)
18261 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18262 CS->getZExtValue() == 1)
18266 SetCC = SetCC.getOperand(OpIdx);
18267 truncatedToBoolWithAnd = true;
18269 SetCC = SetCC.getOperand(0);
18272 switch (SetCC.getOpcode()) {
18273 case X86ISD::SETCC_CARRY:
18274 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18275 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18276 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18277 // truncated to i1 using 'and'.
18278 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18280 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18281 "Invalid use of SETCC_CARRY!");
18283 case X86ISD::SETCC:
18284 // Set the condition code or opposite one if necessary.
18285 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18286 if (needOppositeCond)
18287 CC = X86::GetOppositeBranchCondition(CC);
18288 return SetCC.getOperand(1);
18289 case X86ISD::CMOV: {
18290 // Check whether false/true value has canonical one, i.e. 0 or 1.
18291 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18292 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18293 // Quit if true value is not a constant.
18296 // Quit if false value is not a constant.
18298 SDValue Op = SetCC.getOperand(0);
18299 // Skip 'zext' or 'trunc' node.
18300 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18301 Op.getOpcode() == ISD::TRUNCATE)
18302 Op = Op.getOperand(0);
18303 // A special case for rdrand/rdseed, where 0 is set if false cond is
18305 if ((Op.getOpcode() != X86ISD::RDRAND &&
18306 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18309 // Quit if false value is not the constant 0 or 1.
18310 bool FValIsFalse = true;
18311 if (FVal && FVal->getZExtValue() != 0) {
18312 if (FVal->getZExtValue() != 1)
18314 // If FVal is 1, opposite cond is needed.
18315 needOppositeCond = !needOppositeCond;
18316 FValIsFalse = false;
18318 // Quit if TVal is not the constant opposite of FVal.
18319 if (FValIsFalse && TVal->getZExtValue() != 1)
18321 if (!FValIsFalse && TVal->getZExtValue() != 0)
18323 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18324 if (needOppositeCond)
18325 CC = X86::GetOppositeBranchCondition(CC);
18326 return SetCC.getOperand(3);
18333 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18334 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18335 TargetLowering::DAGCombinerInfo &DCI,
18336 const X86Subtarget *Subtarget) {
18339 // If the flag operand isn't dead, don't touch this CMOV.
18340 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18343 SDValue FalseOp = N->getOperand(0);
18344 SDValue TrueOp = N->getOperand(1);
18345 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18346 SDValue Cond = N->getOperand(3);
18348 if (CC == X86::COND_E || CC == X86::COND_NE) {
18349 switch (Cond.getOpcode()) {
18353 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18354 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18355 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18361 Flags = checkBoolTestSetCCCombine(Cond, CC);
18362 if (Flags.getNode() &&
18363 // Extra check as FCMOV only supports a subset of X86 cond.
18364 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18365 SDValue Ops[] = { FalseOp, TrueOp,
18366 DAG.getConstant(CC, MVT::i8), Flags };
18367 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18370 // If this is a select between two integer constants, try to do some
18371 // optimizations. Note that the operands are ordered the opposite of SELECT
18373 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18374 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18375 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18376 // larger than FalseC (the false value).
18377 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18378 CC = X86::GetOppositeBranchCondition(CC);
18379 std::swap(TrueC, FalseC);
18380 std::swap(TrueOp, FalseOp);
18383 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18384 // This is efficient for any integer data type (including i8/i16) and
18386 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18387 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18388 DAG.getConstant(CC, MVT::i8), Cond);
18390 // Zero extend the condition if needed.
18391 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18393 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18394 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18395 DAG.getConstant(ShAmt, MVT::i8));
18396 if (N->getNumValues() == 2) // Dead flag value?
18397 return DCI.CombineTo(N, Cond, SDValue());
18401 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18402 // for any integer data type, including i8/i16.
18403 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18404 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18405 DAG.getConstant(CC, MVT::i8), Cond);
18407 // Zero extend the condition if needed.
18408 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18409 FalseC->getValueType(0), Cond);
18410 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18411 SDValue(FalseC, 0));
18413 if (N->getNumValues() == 2) // Dead flag value?
18414 return DCI.CombineTo(N, Cond, SDValue());
18418 // Optimize cases that will turn into an LEA instruction. This requires
18419 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18420 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18421 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18422 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18424 bool isFastMultiplier = false;
18426 switch ((unsigned char)Diff) {
18428 case 1: // result = add base, cond
18429 case 2: // result = lea base( , cond*2)
18430 case 3: // result = lea base(cond, cond*2)
18431 case 4: // result = lea base( , cond*4)
18432 case 5: // result = lea base(cond, cond*4)
18433 case 8: // result = lea base( , cond*8)
18434 case 9: // result = lea base(cond, cond*8)
18435 isFastMultiplier = true;
18440 if (isFastMultiplier) {
18441 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18442 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18443 DAG.getConstant(CC, MVT::i8), Cond);
18444 // Zero extend the condition if needed.
18445 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18447 // Scale the condition by the difference.
18449 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18450 DAG.getConstant(Diff, Cond.getValueType()));
18452 // Add the base if non-zero.
18453 if (FalseC->getAPIntValue() != 0)
18454 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18455 SDValue(FalseC, 0));
18456 if (N->getNumValues() == 2) // Dead flag value?
18457 return DCI.CombineTo(N, Cond, SDValue());
18464 // Handle these cases:
18465 // (select (x != c), e, c) -> select (x != c), e, x),
18466 // (select (x == c), c, e) -> select (x == c), x, e)
18467 // where the c is an integer constant, and the "select" is the combination
18468 // of CMOV and CMP.
18470 // The rationale for this change is that the conditional-move from a constant
18471 // needs two instructions, however, conditional-move from a register needs
18472 // only one instruction.
18474 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18475 // some instruction-combining opportunities. This opt needs to be
18476 // postponed as late as possible.
18478 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18479 // the DCI.xxxx conditions are provided to postpone the optimization as
18480 // late as possible.
18482 ConstantSDNode *CmpAgainst = nullptr;
18483 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18484 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18485 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18487 if (CC == X86::COND_NE &&
18488 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18489 CC = X86::GetOppositeBranchCondition(CC);
18490 std::swap(TrueOp, FalseOp);
18493 if (CC == X86::COND_E &&
18494 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18495 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18496 DAG.getConstant(CC, MVT::i8), Cond };
18497 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18505 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18506 const X86Subtarget *Subtarget) {
18507 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18509 default: return SDValue();
18510 // SSE/AVX/AVX2 blend intrinsics.
18511 case Intrinsic::x86_avx2_pblendvb:
18512 case Intrinsic::x86_avx2_pblendw:
18513 case Intrinsic::x86_avx2_pblendd_128:
18514 case Intrinsic::x86_avx2_pblendd_256:
18515 // Don't try to simplify this intrinsic if we don't have AVX2.
18516 if (!Subtarget->hasAVX2())
18519 case Intrinsic::x86_avx_blend_pd_256:
18520 case Intrinsic::x86_avx_blend_ps_256:
18521 case Intrinsic::x86_avx_blendv_pd_256:
18522 case Intrinsic::x86_avx_blendv_ps_256:
18523 // Don't try to simplify this intrinsic if we don't have AVX.
18524 if (!Subtarget->hasAVX())
18527 case Intrinsic::x86_sse41_pblendw:
18528 case Intrinsic::x86_sse41_blendpd:
18529 case Intrinsic::x86_sse41_blendps:
18530 case Intrinsic::x86_sse41_blendvps:
18531 case Intrinsic::x86_sse41_blendvpd:
18532 case Intrinsic::x86_sse41_pblendvb: {
18533 SDValue Op0 = N->getOperand(1);
18534 SDValue Op1 = N->getOperand(2);
18535 SDValue Mask = N->getOperand(3);
18537 // Don't try to simplify this intrinsic if we don't have SSE4.1.
18538 if (!Subtarget->hasSSE41())
18541 // fold (blend A, A, Mask) -> A
18544 // fold (blend A, B, allZeros) -> A
18545 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18547 // fold (blend A, B, allOnes) -> B
18548 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18551 // Simplify the case where the mask is a constant i32 value.
18552 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18553 if (C->isNullValue())
18555 if (C->isAllOnesValue())
18560 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18561 case Intrinsic::x86_sse2_psrai_w:
18562 case Intrinsic::x86_sse2_psrai_d:
18563 case Intrinsic::x86_avx2_psrai_w:
18564 case Intrinsic::x86_avx2_psrai_d:
18565 case Intrinsic::x86_sse2_psra_w:
18566 case Intrinsic::x86_sse2_psra_d:
18567 case Intrinsic::x86_avx2_psra_w:
18568 case Intrinsic::x86_avx2_psra_d: {
18569 SDValue Op0 = N->getOperand(1);
18570 SDValue Op1 = N->getOperand(2);
18571 EVT VT = Op0.getValueType();
18572 assert(VT.isVector() && "Expected a vector type!");
18574 if (isa<BuildVectorSDNode>(Op1))
18575 Op1 = Op1.getOperand(0);
18577 if (!isa<ConstantSDNode>(Op1))
18580 EVT SVT = VT.getVectorElementType();
18581 unsigned SVTBits = SVT.getSizeInBits();
18583 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18584 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18585 uint64_t ShAmt = C.getZExtValue();
18587 // Don't try to convert this shift into a ISD::SRA if the shift
18588 // count is bigger than or equal to the element size.
18589 if (ShAmt >= SVTBits)
18592 // Trivial case: if the shift count is zero, then fold this
18593 // into the first operand.
18597 // Replace this packed shift intrinsic with a target independent
18599 SDValue Splat = DAG.getConstant(C, VT);
18600 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18605 /// PerformMulCombine - Optimize a single multiply with constant into two
18606 /// in order to implement it with two cheaper instructions, e.g.
18607 /// LEA + SHL, LEA + LEA.
18608 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18609 TargetLowering::DAGCombinerInfo &DCI) {
18610 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18613 EVT VT = N->getValueType(0);
18614 if (VT != MVT::i64)
18617 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18620 uint64_t MulAmt = C->getZExtValue();
18621 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18624 uint64_t MulAmt1 = 0;
18625 uint64_t MulAmt2 = 0;
18626 if ((MulAmt % 9) == 0) {
18628 MulAmt2 = MulAmt / 9;
18629 } else if ((MulAmt % 5) == 0) {
18631 MulAmt2 = MulAmt / 5;
18632 } else if ((MulAmt % 3) == 0) {
18634 MulAmt2 = MulAmt / 3;
18637 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18640 if (isPowerOf2_64(MulAmt2) &&
18641 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18642 // If second multiplifer is pow2, issue it first. We want the multiply by
18643 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18645 std::swap(MulAmt1, MulAmt2);
18648 if (isPowerOf2_64(MulAmt1))
18649 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18650 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18652 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18653 DAG.getConstant(MulAmt1, VT));
18655 if (isPowerOf2_64(MulAmt2))
18656 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18657 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18659 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18660 DAG.getConstant(MulAmt2, VT));
18662 // Do not add new nodes to DAG combiner worklist.
18663 DCI.CombineTo(N, NewMul, false);
18668 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18669 SDValue N0 = N->getOperand(0);
18670 SDValue N1 = N->getOperand(1);
18671 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18672 EVT VT = N0.getValueType();
18674 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18675 // since the result of setcc_c is all zero's or all ones.
18676 if (VT.isInteger() && !VT.isVector() &&
18677 N1C && N0.getOpcode() == ISD::AND &&
18678 N0.getOperand(1).getOpcode() == ISD::Constant) {
18679 SDValue N00 = N0.getOperand(0);
18680 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18681 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18682 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18683 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18684 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18685 APInt ShAmt = N1C->getAPIntValue();
18686 Mask = Mask.shl(ShAmt);
18688 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18689 N00, DAG.getConstant(Mask, VT));
18693 // Hardware support for vector shifts is sparse which makes us scalarize the
18694 // vector operations in many cases. Also, on sandybridge ADD is faster than
18696 // (shl V, 1) -> add V,V
18697 if (isSplatVector(N1.getNode())) {
18698 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18699 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18700 // We shift all of the values by one. In many cases we do not have
18701 // hardware support for this operation. This is better expressed as an ADD
18703 if (N1C && (1 == N1C->getZExtValue())) {
18704 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18711 /// \brief Returns a vector of 0s if the node in input is a vector logical
18712 /// shift by a constant amount which is known to be bigger than or equal
18713 /// to the vector element size in bits.
18714 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18715 const X86Subtarget *Subtarget) {
18716 EVT VT = N->getValueType(0);
18718 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18719 (!Subtarget->hasInt256() ||
18720 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18723 SDValue Amt = N->getOperand(1);
18725 if (isSplatVector(Amt.getNode())) {
18726 SDValue SclrAmt = Amt->getOperand(0);
18727 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18728 APInt ShiftAmt = C->getAPIntValue();
18729 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18731 // SSE2/AVX2 logical shifts always return a vector of 0s
18732 // if the shift amount is bigger than or equal to
18733 // the element size. The constant shift amount will be
18734 // encoded as a 8-bit immediate.
18735 if (ShiftAmt.trunc(8).uge(MaxAmount))
18736 return getZeroVector(VT, Subtarget, DAG, DL);
18743 /// PerformShiftCombine - Combine shifts.
18744 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18745 TargetLowering::DAGCombinerInfo &DCI,
18746 const X86Subtarget *Subtarget) {
18747 if (N->getOpcode() == ISD::SHL) {
18748 SDValue V = PerformSHLCombine(N, DAG);
18749 if (V.getNode()) return V;
18752 if (N->getOpcode() != ISD::SRA) {
18753 // Try to fold this logical shift into a zero vector.
18754 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18755 if (V.getNode()) return V;
18761 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18762 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18763 // and friends. Likewise for OR -> CMPNEQSS.
18764 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18765 TargetLowering::DAGCombinerInfo &DCI,
18766 const X86Subtarget *Subtarget) {
18769 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18770 // we're requiring SSE2 for both.
18771 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18772 SDValue N0 = N->getOperand(0);
18773 SDValue N1 = N->getOperand(1);
18774 SDValue CMP0 = N0->getOperand(1);
18775 SDValue CMP1 = N1->getOperand(1);
18778 // The SETCCs should both refer to the same CMP.
18779 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18782 SDValue CMP00 = CMP0->getOperand(0);
18783 SDValue CMP01 = CMP0->getOperand(1);
18784 EVT VT = CMP00.getValueType();
18786 if (VT == MVT::f32 || VT == MVT::f64) {
18787 bool ExpectingFlags = false;
18788 // Check for any users that want flags:
18789 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18790 !ExpectingFlags && UI != UE; ++UI)
18791 switch (UI->getOpcode()) {
18796 ExpectingFlags = true;
18798 case ISD::CopyToReg:
18799 case ISD::SIGN_EXTEND:
18800 case ISD::ZERO_EXTEND:
18801 case ISD::ANY_EXTEND:
18805 if (!ExpectingFlags) {
18806 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18807 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18809 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18810 X86::CondCode tmp = cc0;
18815 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18816 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18817 // FIXME: need symbolic constants for these magic numbers.
18818 // See X86ATTInstPrinter.cpp:printSSECC().
18819 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18820 if (Subtarget->hasAVX512()) {
18821 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18822 CMP01, DAG.getConstant(x86cc, MVT::i8));
18823 if (N->getValueType(0) != MVT::i1)
18824 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18828 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18829 CMP00.getValueType(), CMP00, CMP01,
18830 DAG.getConstant(x86cc, MVT::i8));
18832 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18833 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18835 if (is64BitFP && !Subtarget->is64Bit()) {
18836 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18837 // 64-bit integer, since that's not a legal type. Since
18838 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18839 // bits, but can do this little dance to extract the lowest 32 bits
18840 // and work with those going forward.
18841 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18843 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18845 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18846 Vector32, DAG.getIntPtrConstant(0));
18850 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18851 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18852 DAG.getConstant(1, IntVT));
18853 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18854 return OneBitOfTruth;
18862 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18863 /// so it can be folded inside ANDNP.
18864 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18865 EVT VT = N->getValueType(0);
18867 // Match direct AllOnes for 128 and 256-bit vectors
18868 if (ISD::isBuildVectorAllOnes(N))
18871 // Look through a bit convert.
18872 if (N->getOpcode() == ISD::BITCAST)
18873 N = N->getOperand(0).getNode();
18875 // Sometimes the operand may come from a insert_subvector building a 256-bit
18877 if (VT.is256BitVector() &&
18878 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18879 SDValue V1 = N->getOperand(0);
18880 SDValue V2 = N->getOperand(1);
18882 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18883 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18884 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18885 ISD::isBuildVectorAllOnes(V2.getNode()))
18892 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18893 // register. In most cases we actually compare or select YMM-sized registers
18894 // and mixing the two types creates horrible code. This method optimizes
18895 // some of the transition sequences.
18896 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18897 TargetLowering::DAGCombinerInfo &DCI,
18898 const X86Subtarget *Subtarget) {
18899 EVT VT = N->getValueType(0);
18900 if (!VT.is256BitVector())
18903 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18904 N->getOpcode() == ISD::ZERO_EXTEND ||
18905 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18907 SDValue Narrow = N->getOperand(0);
18908 EVT NarrowVT = Narrow->getValueType(0);
18909 if (!NarrowVT.is128BitVector())
18912 if (Narrow->getOpcode() != ISD::XOR &&
18913 Narrow->getOpcode() != ISD::AND &&
18914 Narrow->getOpcode() != ISD::OR)
18917 SDValue N0 = Narrow->getOperand(0);
18918 SDValue N1 = Narrow->getOperand(1);
18921 // The Left side has to be a trunc.
18922 if (N0.getOpcode() != ISD::TRUNCATE)
18925 // The type of the truncated inputs.
18926 EVT WideVT = N0->getOperand(0)->getValueType(0);
18930 // The right side has to be a 'trunc' or a constant vector.
18931 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18932 bool RHSConst = (isSplatVector(N1.getNode()) &&
18933 isa<ConstantSDNode>(N1->getOperand(0)));
18934 if (!RHSTrunc && !RHSConst)
18937 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18939 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18942 // Set N0 and N1 to hold the inputs to the new wide operation.
18943 N0 = N0->getOperand(0);
18945 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18946 N1->getOperand(0));
18947 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18948 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18949 } else if (RHSTrunc) {
18950 N1 = N1->getOperand(0);
18953 // Generate the wide operation.
18954 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18955 unsigned Opcode = N->getOpcode();
18957 case ISD::ANY_EXTEND:
18959 case ISD::ZERO_EXTEND: {
18960 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18961 APInt Mask = APInt::getAllOnesValue(InBits);
18962 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18963 return DAG.getNode(ISD::AND, DL, VT,
18964 Op, DAG.getConstant(Mask, VT));
18966 case ISD::SIGN_EXTEND:
18967 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18968 Op, DAG.getValueType(NarrowVT));
18970 llvm_unreachable("Unexpected opcode");
18974 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18975 TargetLowering::DAGCombinerInfo &DCI,
18976 const X86Subtarget *Subtarget) {
18977 EVT VT = N->getValueType(0);
18978 if (DCI.isBeforeLegalizeOps())
18981 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18985 // Create BEXTR instructions
18986 // BEXTR is ((X >> imm) & (2**size-1))
18987 if (VT == MVT::i32 || VT == MVT::i64) {
18988 SDValue N0 = N->getOperand(0);
18989 SDValue N1 = N->getOperand(1);
18992 // Check for BEXTR.
18993 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18994 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18995 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18996 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18997 if (MaskNode && ShiftNode) {
18998 uint64_t Mask = MaskNode->getZExtValue();
18999 uint64_t Shift = ShiftNode->getZExtValue();
19000 if (isMask_64(Mask)) {
19001 uint64_t MaskSize = CountPopulation_64(Mask);
19002 if (Shift + MaskSize <= VT.getSizeInBits())
19003 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19004 DAG.getConstant(Shift | (MaskSize << 8), VT));
19012 // Want to form ANDNP nodes:
19013 // 1) In the hopes of then easily combining them with OR and AND nodes
19014 // to form PBLEND/PSIGN.
19015 // 2) To match ANDN packed intrinsics
19016 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19019 SDValue N0 = N->getOperand(0);
19020 SDValue N1 = N->getOperand(1);
19023 // Check LHS for vnot
19024 if (N0.getOpcode() == ISD::XOR &&
19025 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19026 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19027 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19029 // Check RHS for vnot
19030 if (N1.getOpcode() == ISD::XOR &&
19031 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19032 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19033 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19038 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19039 TargetLowering::DAGCombinerInfo &DCI,
19040 const X86Subtarget *Subtarget) {
19041 if (DCI.isBeforeLegalizeOps())
19044 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19048 SDValue N0 = N->getOperand(0);
19049 SDValue N1 = N->getOperand(1);
19050 EVT VT = N->getValueType(0);
19052 // look for psign/blend
19053 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19054 if (!Subtarget->hasSSSE3() ||
19055 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19058 // Canonicalize pandn to RHS
19059 if (N0.getOpcode() == X86ISD::ANDNP)
19061 // or (and (m, y), (pandn m, x))
19062 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19063 SDValue Mask = N1.getOperand(0);
19064 SDValue X = N1.getOperand(1);
19066 if (N0.getOperand(0) == Mask)
19067 Y = N0.getOperand(1);
19068 if (N0.getOperand(1) == Mask)
19069 Y = N0.getOperand(0);
19071 // Check to see if the mask appeared in both the AND and ANDNP and
19075 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19076 // Look through mask bitcast.
19077 if (Mask.getOpcode() == ISD::BITCAST)
19078 Mask = Mask.getOperand(0);
19079 if (X.getOpcode() == ISD::BITCAST)
19080 X = X.getOperand(0);
19081 if (Y.getOpcode() == ISD::BITCAST)
19082 Y = Y.getOperand(0);
19084 EVT MaskVT = Mask.getValueType();
19086 // Validate that the Mask operand is a vector sra node.
19087 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19088 // there is no psrai.b
19089 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19090 unsigned SraAmt = ~0;
19091 if (Mask.getOpcode() == ISD::SRA) {
19092 SDValue Amt = Mask.getOperand(1);
19093 if (isSplatVector(Amt.getNode())) {
19094 SDValue SclrAmt = Amt->getOperand(0);
19095 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19096 SraAmt = C->getZExtValue();
19098 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19099 SDValue SraC = Mask.getOperand(1);
19100 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19102 if ((SraAmt + 1) != EltBits)
19107 // Now we know we at least have a plendvb with the mask val. See if
19108 // we can form a psignb/w/d.
19109 // psign = x.type == y.type == mask.type && y = sub(0, x);
19110 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19111 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19112 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19113 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19114 "Unsupported VT for PSIGN");
19115 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19116 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19118 // PBLENDVB only available on SSE 4.1
19119 if (!Subtarget->hasSSE41())
19122 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19124 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19125 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19126 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19127 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19128 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19132 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19135 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19136 MachineFunction &MF = DAG.getMachineFunction();
19137 bool OptForSize = MF.getFunction()->getAttributes().
19138 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19140 // SHLD/SHRD instructions have lower register pressure, but on some
19141 // platforms they have higher latency than the equivalent
19142 // series of shifts/or that would otherwise be generated.
19143 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19144 // have higher latencies and we are not optimizing for size.
19145 if (!OptForSize && Subtarget->isSHLDSlow())
19148 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19150 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19152 if (!N0.hasOneUse() || !N1.hasOneUse())
19155 SDValue ShAmt0 = N0.getOperand(1);
19156 if (ShAmt0.getValueType() != MVT::i8)
19158 SDValue ShAmt1 = N1.getOperand(1);
19159 if (ShAmt1.getValueType() != MVT::i8)
19161 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19162 ShAmt0 = ShAmt0.getOperand(0);
19163 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19164 ShAmt1 = ShAmt1.getOperand(0);
19167 unsigned Opc = X86ISD::SHLD;
19168 SDValue Op0 = N0.getOperand(0);
19169 SDValue Op1 = N1.getOperand(0);
19170 if (ShAmt0.getOpcode() == ISD::SUB) {
19171 Opc = X86ISD::SHRD;
19172 std::swap(Op0, Op1);
19173 std::swap(ShAmt0, ShAmt1);
19176 unsigned Bits = VT.getSizeInBits();
19177 if (ShAmt1.getOpcode() == ISD::SUB) {
19178 SDValue Sum = ShAmt1.getOperand(0);
19179 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19180 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19181 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19182 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19183 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19184 return DAG.getNode(Opc, DL, VT,
19186 DAG.getNode(ISD::TRUNCATE, DL,
19189 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19190 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19192 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19193 return DAG.getNode(Opc, DL, VT,
19194 N0.getOperand(0), N1.getOperand(0),
19195 DAG.getNode(ISD::TRUNCATE, DL,
19202 // Generate NEG and CMOV for integer abs.
19203 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19204 EVT VT = N->getValueType(0);
19206 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19207 // 8-bit integer abs to NEG and CMOV.
19208 if (VT.isInteger() && VT.getSizeInBits() == 8)
19211 SDValue N0 = N->getOperand(0);
19212 SDValue N1 = N->getOperand(1);
19215 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19216 // and change it to SUB and CMOV.
19217 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19218 N0.getOpcode() == ISD::ADD &&
19219 N0.getOperand(1) == N1 &&
19220 N1.getOpcode() == ISD::SRA &&
19221 N1.getOperand(0) == N0.getOperand(0))
19222 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19223 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19224 // Generate SUB & CMOV.
19225 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19226 DAG.getConstant(0, VT), N0.getOperand(0));
19228 SDValue Ops[] = { N0.getOperand(0), Neg,
19229 DAG.getConstant(X86::COND_GE, MVT::i8),
19230 SDValue(Neg.getNode(), 1) };
19231 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19236 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19237 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19238 TargetLowering::DAGCombinerInfo &DCI,
19239 const X86Subtarget *Subtarget) {
19240 if (DCI.isBeforeLegalizeOps())
19243 if (Subtarget->hasCMov()) {
19244 SDValue RV = performIntegerAbsCombine(N, DAG);
19252 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19253 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19254 TargetLowering::DAGCombinerInfo &DCI,
19255 const X86Subtarget *Subtarget) {
19256 LoadSDNode *Ld = cast<LoadSDNode>(N);
19257 EVT RegVT = Ld->getValueType(0);
19258 EVT MemVT = Ld->getMemoryVT();
19260 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19261 unsigned RegSz = RegVT.getSizeInBits();
19263 // On Sandybridge unaligned 256bit loads are inefficient.
19264 ISD::LoadExtType Ext = Ld->getExtensionType();
19265 unsigned Alignment = Ld->getAlignment();
19266 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19267 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19268 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19269 unsigned NumElems = RegVT.getVectorNumElements();
19273 SDValue Ptr = Ld->getBasePtr();
19274 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19276 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19278 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19279 Ld->getPointerInfo(), Ld->isVolatile(),
19280 Ld->isNonTemporal(), Ld->isInvariant(),
19282 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19283 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19284 Ld->getPointerInfo(), Ld->isVolatile(),
19285 Ld->isNonTemporal(), Ld->isInvariant(),
19286 std::min(16U, Alignment));
19287 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19289 Load2.getValue(1));
19291 SDValue NewVec = DAG.getUNDEF(RegVT);
19292 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19293 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19294 return DCI.CombineTo(N, NewVec, TF, true);
19297 // If this is a vector EXT Load then attempt to optimize it using a
19298 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19299 // expansion is still better than scalar code.
19300 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19301 // emit a shuffle and a arithmetic shift.
19302 // TODO: It is possible to support ZExt by zeroing the undef values
19303 // during the shuffle phase or after the shuffle.
19304 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19305 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19306 assert(MemVT != RegVT && "Cannot extend to the same type");
19307 assert(MemVT.isVector() && "Must load a vector from memory");
19309 unsigned NumElems = RegVT.getVectorNumElements();
19310 unsigned MemSz = MemVT.getSizeInBits();
19311 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19313 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19316 // All sizes must be a power of two.
19317 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19320 // Attempt to load the original value using scalar loads.
19321 // Find the largest scalar type that divides the total loaded size.
19322 MVT SclrLoadTy = MVT::i8;
19323 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19324 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19325 MVT Tp = (MVT::SimpleValueType)tp;
19326 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19331 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19332 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19334 SclrLoadTy = MVT::f64;
19336 // Calculate the number of scalar loads that we need to perform
19337 // in order to load our vector from memory.
19338 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19339 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19342 unsigned loadRegZize = RegSz;
19343 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19346 // Represent our vector as a sequence of elements which are the
19347 // largest scalar that we can load.
19348 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19349 loadRegZize/SclrLoadTy.getSizeInBits());
19351 // Represent the data using the same element type that is stored in
19352 // memory. In practice, we ''widen'' MemVT.
19354 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19355 loadRegZize/MemVT.getScalarType().getSizeInBits());
19357 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19358 "Invalid vector type");
19360 // We can't shuffle using an illegal type.
19361 if (!TLI.isTypeLegal(WideVecVT))
19364 SmallVector<SDValue, 8> Chains;
19365 SDValue Ptr = Ld->getBasePtr();
19366 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19367 TLI.getPointerTy());
19368 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19370 for (unsigned i = 0; i < NumLoads; ++i) {
19371 // Perform a single load.
19372 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19373 Ptr, Ld->getPointerInfo(),
19374 Ld->isVolatile(), Ld->isNonTemporal(),
19375 Ld->isInvariant(), Ld->getAlignment());
19376 Chains.push_back(ScalarLoad.getValue(1));
19377 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19378 // another round of DAGCombining.
19380 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19382 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19383 ScalarLoad, DAG.getIntPtrConstant(i));
19385 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19388 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19390 // Bitcast the loaded value to a vector of the original element type, in
19391 // the size of the target vector type.
19392 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19393 unsigned SizeRatio = RegSz/MemSz;
19395 if (Ext == ISD::SEXTLOAD) {
19396 // If we have SSE4.1 we can directly emit a VSEXT node.
19397 if (Subtarget->hasSSE41()) {
19398 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19399 return DCI.CombineTo(N, Sext, TF, true);
19402 // Otherwise we'll shuffle the small elements in the high bits of the
19403 // larger type and perform an arithmetic shift. If the shift is not legal
19404 // it's better to scalarize.
19405 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19408 // Redistribute the loaded elements into the different locations.
19409 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19410 for (unsigned i = 0; i != NumElems; ++i)
19411 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19413 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19414 DAG.getUNDEF(WideVecVT),
19417 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19419 // Build the arithmetic shift.
19420 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19421 MemVT.getVectorElementType().getSizeInBits();
19422 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19423 DAG.getConstant(Amt, RegVT));
19425 return DCI.CombineTo(N, Shuff, TF, true);
19428 // Redistribute the loaded elements into the different locations.
19429 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19430 for (unsigned i = 0; i != NumElems; ++i)
19431 ShuffleVec[i*SizeRatio] = i;
19433 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19434 DAG.getUNDEF(WideVecVT),
19437 // Bitcast to the requested type.
19438 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19439 // Replace the original load with the new sequence
19440 // and return the new chain.
19441 return DCI.CombineTo(N, Shuff, TF, true);
19447 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19448 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19449 const X86Subtarget *Subtarget) {
19450 StoreSDNode *St = cast<StoreSDNode>(N);
19451 EVT VT = St->getValue().getValueType();
19452 EVT StVT = St->getMemoryVT();
19454 SDValue StoredVal = St->getOperand(1);
19455 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19457 // If we are saving a concatenation of two XMM registers, perform two stores.
19458 // On Sandy Bridge, 256-bit memory operations are executed by two
19459 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19460 // memory operation.
19461 unsigned Alignment = St->getAlignment();
19462 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19463 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19464 StVT == VT && !IsAligned) {
19465 unsigned NumElems = VT.getVectorNumElements();
19469 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19470 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19472 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19473 SDValue Ptr0 = St->getBasePtr();
19474 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19476 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19477 St->getPointerInfo(), St->isVolatile(),
19478 St->isNonTemporal(), Alignment);
19479 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19480 St->getPointerInfo(), St->isVolatile(),
19481 St->isNonTemporal(),
19482 std::min(16U, Alignment));
19483 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19486 // Optimize trunc store (of multiple scalars) to shuffle and store.
19487 // First, pack all of the elements in one place. Next, store to memory
19488 // in fewer chunks.
19489 if (St->isTruncatingStore() && VT.isVector()) {
19490 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19491 unsigned NumElems = VT.getVectorNumElements();
19492 assert(StVT != VT && "Cannot truncate to the same type");
19493 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19494 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19496 // From, To sizes and ElemCount must be pow of two
19497 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19498 // We are going to use the original vector elt for storing.
19499 // Accumulated smaller vector elements must be a multiple of the store size.
19500 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19502 unsigned SizeRatio = FromSz / ToSz;
19504 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19506 // Create a type on which we perform the shuffle
19507 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19508 StVT.getScalarType(), NumElems*SizeRatio);
19510 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19512 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19513 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19514 for (unsigned i = 0; i != NumElems; ++i)
19515 ShuffleVec[i] = i * SizeRatio;
19517 // Can't shuffle using an illegal type.
19518 if (!TLI.isTypeLegal(WideVecVT))
19521 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19522 DAG.getUNDEF(WideVecVT),
19524 // At this point all of the data is stored at the bottom of the
19525 // register. We now need to save it to mem.
19527 // Find the largest store unit
19528 MVT StoreType = MVT::i8;
19529 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19530 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19531 MVT Tp = (MVT::SimpleValueType)tp;
19532 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19536 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19537 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19538 (64 <= NumElems * ToSz))
19539 StoreType = MVT::f64;
19541 // Bitcast the original vector into a vector of store-size units
19542 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19543 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19544 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19545 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19546 SmallVector<SDValue, 8> Chains;
19547 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19548 TLI.getPointerTy());
19549 SDValue Ptr = St->getBasePtr();
19551 // Perform one or more big stores into memory.
19552 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19553 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19554 StoreType, ShuffWide,
19555 DAG.getIntPtrConstant(i));
19556 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19557 St->getPointerInfo(), St->isVolatile(),
19558 St->isNonTemporal(), St->getAlignment());
19559 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19560 Chains.push_back(Ch);
19563 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19566 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19567 // the FP state in cases where an emms may be missing.
19568 // A preferable solution to the general problem is to figure out the right
19569 // places to insert EMMS. This qualifies as a quick hack.
19571 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19572 if (VT.getSizeInBits() != 64)
19575 const Function *F = DAG.getMachineFunction().getFunction();
19576 bool NoImplicitFloatOps = F->getAttributes().
19577 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19578 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19579 && Subtarget->hasSSE2();
19580 if ((VT.isVector() ||
19581 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19582 isa<LoadSDNode>(St->getValue()) &&
19583 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19584 St->getChain().hasOneUse() && !St->isVolatile()) {
19585 SDNode* LdVal = St->getValue().getNode();
19586 LoadSDNode *Ld = nullptr;
19587 int TokenFactorIndex = -1;
19588 SmallVector<SDValue, 8> Ops;
19589 SDNode* ChainVal = St->getChain().getNode();
19590 // Must be a store of a load. We currently handle two cases: the load
19591 // is a direct child, and it's under an intervening TokenFactor. It is
19592 // possible to dig deeper under nested TokenFactors.
19593 if (ChainVal == LdVal)
19594 Ld = cast<LoadSDNode>(St->getChain());
19595 else if (St->getValue().hasOneUse() &&
19596 ChainVal->getOpcode() == ISD::TokenFactor) {
19597 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19598 if (ChainVal->getOperand(i).getNode() == LdVal) {
19599 TokenFactorIndex = i;
19600 Ld = cast<LoadSDNode>(St->getValue());
19602 Ops.push_back(ChainVal->getOperand(i));
19606 if (!Ld || !ISD::isNormalLoad(Ld))
19609 // If this is not the MMX case, i.e. we are just turning i64 load/store
19610 // into f64 load/store, avoid the transformation if there are multiple
19611 // uses of the loaded value.
19612 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19617 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19618 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19620 if (Subtarget->is64Bit() || F64IsLegal) {
19621 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19622 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19623 Ld->getPointerInfo(), Ld->isVolatile(),
19624 Ld->isNonTemporal(), Ld->isInvariant(),
19625 Ld->getAlignment());
19626 SDValue NewChain = NewLd.getValue(1);
19627 if (TokenFactorIndex != -1) {
19628 Ops.push_back(NewChain);
19629 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19631 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19632 St->getPointerInfo(),
19633 St->isVolatile(), St->isNonTemporal(),
19634 St->getAlignment());
19637 // Otherwise, lower to two pairs of 32-bit loads / stores.
19638 SDValue LoAddr = Ld->getBasePtr();
19639 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19640 DAG.getConstant(4, MVT::i32));
19642 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19643 Ld->getPointerInfo(),
19644 Ld->isVolatile(), Ld->isNonTemporal(),
19645 Ld->isInvariant(), Ld->getAlignment());
19646 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19647 Ld->getPointerInfo().getWithOffset(4),
19648 Ld->isVolatile(), Ld->isNonTemporal(),
19650 MinAlign(Ld->getAlignment(), 4));
19652 SDValue NewChain = LoLd.getValue(1);
19653 if (TokenFactorIndex != -1) {
19654 Ops.push_back(LoLd);
19655 Ops.push_back(HiLd);
19656 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19659 LoAddr = St->getBasePtr();
19660 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19661 DAG.getConstant(4, MVT::i32));
19663 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19664 St->getPointerInfo(),
19665 St->isVolatile(), St->isNonTemporal(),
19666 St->getAlignment());
19667 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19668 St->getPointerInfo().getWithOffset(4),
19670 St->isNonTemporal(),
19671 MinAlign(St->getAlignment(), 4));
19672 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19677 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19678 /// and return the operands for the horizontal operation in LHS and RHS. A
19679 /// horizontal operation performs the binary operation on successive elements
19680 /// of its first operand, then on successive elements of its second operand,
19681 /// returning the resulting values in a vector. For example, if
19682 /// A = < float a0, float a1, float a2, float a3 >
19684 /// B = < float b0, float b1, float b2, float b3 >
19685 /// then the result of doing a horizontal operation on A and B is
19686 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19687 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19688 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19689 /// set to A, RHS to B, and the routine returns 'true'.
19690 /// Note that the binary operation should have the property that if one of the
19691 /// operands is UNDEF then the result is UNDEF.
19692 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19693 // Look for the following pattern: if
19694 // A = < float a0, float a1, float a2, float a3 >
19695 // B = < float b0, float b1, float b2, float b3 >
19697 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19698 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19699 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19700 // which is A horizontal-op B.
19702 // At least one of the operands should be a vector shuffle.
19703 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19704 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19707 MVT VT = LHS.getSimpleValueType();
19709 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19710 "Unsupported vector type for horizontal add/sub");
19712 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19713 // operate independently on 128-bit lanes.
19714 unsigned NumElts = VT.getVectorNumElements();
19715 unsigned NumLanes = VT.getSizeInBits()/128;
19716 unsigned NumLaneElts = NumElts / NumLanes;
19717 assert((NumLaneElts % 2 == 0) &&
19718 "Vector type should have an even number of elements in each lane");
19719 unsigned HalfLaneElts = NumLaneElts/2;
19721 // View LHS in the form
19722 // LHS = VECTOR_SHUFFLE A, B, LMask
19723 // If LHS is not a shuffle then pretend it is the shuffle
19724 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19725 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19728 SmallVector<int, 16> LMask(NumElts);
19729 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19730 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19731 A = LHS.getOperand(0);
19732 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19733 B = LHS.getOperand(1);
19734 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19735 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19737 if (LHS.getOpcode() != ISD::UNDEF)
19739 for (unsigned i = 0; i != NumElts; ++i)
19743 // Likewise, view RHS in the form
19744 // RHS = VECTOR_SHUFFLE C, D, RMask
19746 SmallVector<int, 16> RMask(NumElts);
19747 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19748 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19749 C = RHS.getOperand(0);
19750 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19751 D = RHS.getOperand(1);
19752 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19753 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19755 if (RHS.getOpcode() != ISD::UNDEF)
19757 for (unsigned i = 0; i != NumElts; ++i)
19761 // Check that the shuffles are both shuffling the same vectors.
19762 if (!(A == C && B == D) && !(A == D && B == C))
19765 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19766 if (!A.getNode() && !B.getNode())
19769 // If A and B occur in reverse order in RHS, then "swap" them (which means
19770 // rewriting the mask).
19772 CommuteVectorShuffleMask(RMask, NumElts);
19774 // At this point LHS and RHS are equivalent to
19775 // LHS = VECTOR_SHUFFLE A, B, LMask
19776 // RHS = VECTOR_SHUFFLE A, B, RMask
19777 // Check that the masks correspond to performing a horizontal operation.
19778 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19779 for (unsigned i = 0; i != NumLaneElts; ++i) {
19780 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19782 // Ignore any UNDEF components.
19783 if (LIdx < 0 || RIdx < 0 ||
19784 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19785 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19788 // Check that successive elements are being operated on. If not, this is
19789 // not a horizontal operation.
19790 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19791 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19792 if (!(LIdx == Index && RIdx == Index + 1) &&
19793 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19798 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19799 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19803 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19804 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19805 const X86Subtarget *Subtarget) {
19806 EVT VT = N->getValueType(0);
19807 SDValue LHS = N->getOperand(0);
19808 SDValue RHS = N->getOperand(1);
19810 // Try to synthesize horizontal adds from adds of shuffles.
19811 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19812 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19813 isHorizontalBinOp(LHS, RHS, true))
19814 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19818 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19819 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19820 const X86Subtarget *Subtarget) {
19821 EVT VT = N->getValueType(0);
19822 SDValue LHS = N->getOperand(0);
19823 SDValue RHS = N->getOperand(1);
19825 // Try to synthesize horizontal subs from subs of shuffles.
19826 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19827 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19828 isHorizontalBinOp(LHS, RHS, false))
19829 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19833 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19834 /// X86ISD::FXOR nodes.
19835 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19836 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19837 // F[X]OR(0.0, x) -> x
19838 // F[X]OR(x, 0.0) -> x
19839 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19840 if (C->getValueAPF().isPosZero())
19841 return N->getOperand(1);
19842 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19843 if (C->getValueAPF().isPosZero())
19844 return N->getOperand(0);
19848 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19849 /// X86ISD::FMAX nodes.
19850 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19851 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19853 // Only perform optimizations if UnsafeMath is used.
19854 if (!DAG.getTarget().Options.UnsafeFPMath)
19857 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19858 // into FMINC and FMAXC, which are Commutative operations.
19859 unsigned NewOp = 0;
19860 switch (N->getOpcode()) {
19861 default: llvm_unreachable("unknown opcode");
19862 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19863 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19866 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19867 N->getOperand(0), N->getOperand(1));
19870 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19871 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19872 // FAND(0.0, x) -> 0.0
19873 // FAND(x, 0.0) -> 0.0
19874 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19875 if (C->getValueAPF().isPosZero())
19876 return N->getOperand(0);
19877 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19878 if (C->getValueAPF().isPosZero())
19879 return N->getOperand(1);
19883 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19884 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19885 // FANDN(x, 0.0) -> 0.0
19886 // FANDN(0.0, x) -> x
19887 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19888 if (C->getValueAPF().isPosZero())
19889 return N->getOperand(1);
19890 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19891 if (C->getValueAPF().isPosZero())
19892 return N->getOperand(1);
19896 static SDValue PerformBTCombine(SDNode *N,
19898 TargetLowering::DAGCombinerInfo &DCI) {
19899 // BT ignores high bits in the bit index operand.
19900 SDValue Op1 = N->getOperand(1);
19901 if (Op1.hasOneUse()) {
19902 unsigned BitWidth = Op1.getValueSizeInBits();
19903 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19904 APInt KnownZero, KnownOne;
19905 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19906 !DCI.isBeforeLegalizeOps());
19907 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19908 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19909 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19910 DCI.CommitTargetLoweringOpt(TLO);
19915 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19916 SDValue Op = N->getOperand(0);
19917 if (Op.getOpcode() == ISD::BITCAST)
19918 Op = Op.getOperand(0);
19919 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19920 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19921 VT.getVectorElementType().getSizeInBits() ==
19922 OpVT.getVectorElementType().getSizeInBits()) {
19923 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19928 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19929 const X86Subtarget *Subtarget) {
19930 EVT VT = N->getValueType(0);
19931 if (!VT.isVector())
19934 SDValue N0 = N->getOperand(0);
19935 SDValue N1 = N->getOperand(1);
19936 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19939 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19940 // both SSE and AVX2 since there is no sign-extended shift right
19941 // operation on a vector with 64-bit elements.
19942 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19943 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19944 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19945 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19946 SDValue N00 = N0.getOperand(0);
19948 // EXTLOAD has a better solution on AVX2,
19949 // it may be replaced with X86ISD::VSEXT node.
19950 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19951 if (!ISD::isNormalLoad(N00.getNode()))
19954 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19955 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19957 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19963 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19964 TargetLowering::DAGCombinerInfo &DCI,
19965 const X86Subtarget *Subtarget) {
19966 if (!DCI.isBeforeLegalizeOps())
19969 if (!Subtarget->hasFp256())
19972 EVT VT = N->getValueType(0);
19973 if (VT.isVector() && VT.getSizeInBits() == 256) {
19974 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19982 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19983 const X86Subtarget* Subtarget) {
19985 EVT VT = N->getValueType(0);
19987 // Let legalize expand this if it isn't a legal type yet.
19988 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19991 EVT ScalarVT = VT.getScalarType();
19992 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19993 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19996 SDValue A = N->getOperand(0);
19997 SDValue B = N->getOperand(1);
19998 SDValue C = N->getOperand(2);
20000 bool NegA = (A.getOpcode() == ISD::FNEG);
20001 bool NegB = (B.getOpcode() == ISD::FNEG);
20002 bool NegC = (C.getOpcode() == ISD::FNEG);
20004 // Negative multiplication when NegA xor NegB
20005 bool NegMul = (NegA != NegB);
20007 A = A.getOperand(0);
20009 B = B.getOperand(0);
20011 C = C.getOperand(0);
20015 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20017 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20019 return DAG.getNode(Opcode, dl, VT, A, B, C);
20022 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20023 TargetLowering::DAGCombinerInfo &DCI,
20024 const X86Subtarget *Subtarget) {
20025 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20026 // (and (i32 x86isd::setcc_carry), 1)
20027 // This eliminates the zext. This transformation is necessary because
20028 // ISD::SETCC is always legalized to i8.
20030 SDValue N0 = N->getOperand(0);
20031 EVT VT = N->getValueType(0);
20033 if (N0.getOpcode() == ISD::AND &&
20035 N0.getOperand(0).hasOneUse()) {
20036 SDValue N00 = N0.getOperand(0);
20037 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20038 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20039 if (!C || C->getZExtValue() != 1)
20041 return DAG.getNode(ISD::AND, dl, VT,
20042 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20043 N00.getOperand(0), N00.getOperand(1)),
20044 DAG.getConstant(1, VT));
20048 if (N0.getOpcode() == ISD::TRUNCATE &&
20050 N0.getOperand(0).hasOneUse()) {
20051 SDValue N00 = N0.getOperand(0);
20052 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20053 return DAG.getNode(ISD::AND, dl, VT,
20054 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20055 N00.getOperand(0), N00.getOperand(1)),
20056 DAG.getConstant(1, VT));
20059 if (VT.is256BitVector()) {
20060 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20068 // Optimize x == -y --> x+y == 0
20069 // x != -y --> x+y != 0
20070 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20071 const X86Subtarget* Subtarget) {
20072 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20073 SDValue LHS = N->getOperand(0);
20074 SDValue RHS = N->getOperand(1);
20075 EVT VT = N->getValueType(0);
20078 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20079 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20080 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20081 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20082 LHS.getValueType(), RHS, LHS.getOperand(1));
20083 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20084 addV, DAG.getConstant(0, addV.getValueType()), CC);
20086 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20088 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20089 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20090 RHS.getValueType(), LHS, RHS.getOperand(1));
20091 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20092 addV, DAG.getConstant(0, addV.getValueType()), CC);
20095 if (VT.getScalarType() == MVT::i1) {
20096 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20097 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20098 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20099 if (!IsSEXT0 && !IsVZero0)
20101 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20102 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20103 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20105 if (!IsSEXT1 && !IsVZero1)
20108 if (IsSEXT0 && IsVZero1) {
20109 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20110 if (CC == ISD::SETEQ)
20111 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20112 return LHS.getOperand(0);
20114 if (IsSEXT1 && IsVZero0) {
20115 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20116 if (CC == ISD::SETEQ)
20117 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20118 return RHS.getOperand(0);
20125 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20126 // as "sbb reg,reg", since it can be extended without zext and produces
20127 // an all-ones bit which is more useful than 0/1 in some cases.
20128 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20131 return DAG.getNode(ISD::AND, DL, VT,
20132 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20133 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20134 DAG.getConstant(1, VT));
20135 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20136 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20137 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20138 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20141 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20142 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20143 TargetLowering::DAGCombinerInfo &DCI,
20144 const X86Subtarget *Subtarget) {
20146 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20147 SDValue EFLAGS = N->getOperand(1);
20149 if (CC == X86::COND_A) {
20150 // Try to convert COND_A into COND_B in an attempt to facilitate
20151 // materializing "setb reg".
20153 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20154 // cannot take an immediate as its first operand.
20156 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20157 EFLAGS.getValueType().isInteger() &&
20158 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20159 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20160 EFLAGS.getNode()->getVTList(),
20161 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20162 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20163 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20167 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20168 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20170 if (CC == X86::COND_B)
20171 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20175 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20176 if (Flags.getNode()) {
20177 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20178 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20184 // Optimize branch condition evaluation.
20186 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20187 TargetLowering::DAGCombinerInfo &DCI,
20188 const X86Subtarget *Subtarget) {
20190 SDValue Chain = N->getOperand(0);
20191 SDValue Dest = N->getOperand(1);
20192 SDValue EFLAGS = N->getOperand(3);
20193 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20197 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20198 if (Flags.getNode()) {
20199 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20200 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20207 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20208 const X86TargetLowering *XTLI) {
20209 SDValue Op0 = N->getOperand(0);
20210 EVT InVT = Op0->getValueType(0);
20212 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20213 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20215 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20216 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20217 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20220 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20221 // a 32-bit target where SSE doesn't support i64->FP operations.
20222 if (Op0.getOpcode() == ISD::LOAD) {
20223 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20224 EVT VT = Ld->getValueType(0);
20225 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20226 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20227 !XTLI->getSubtarget()->is64Bit() &&
20229 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20230 Ld->getChain(), Op0, DAG);
20231 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20238 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20239 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20240 X86TargetLowering::DAGCombinerInfo &DCI) {
20241 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20242 // the result is either zero or one (depending on the input carry bit).
20243 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20244 if (X86::isZeroNode(N->getOperand(0)) &&
20245 X86::isZeroNode(N->getOperand(1)) &&
20246 // We don't have a good way to replace an EFLAGS use, so only do this when
20248 SDValue(N, 1).use_empty()) {
20250 EVT VT = N->getValueType(0);
20251 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20252 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20253 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20254 DAG.getConstant(X86::COND_B,MVT::i8),
20256 DAG.getConstant(1, VT));
20257 return DCI.CombineTo(N, Res1, CarryOut);
20263 // fold (add Y, (sete X, 0)) -> adc 0, Y
20264 // (add Y, (setne X, 0)) -> sbb -1, Y
20265 // (sub (sete X, 0), Y) -> sbb 0, Y
20266 // (sub (setne X, 0), Y) -> adc -1, Y
20267 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20270 // Look through ZExts.
20271 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20272 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20275 SDValue SetCC = Ext.getOperand(0);
20276 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20279 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20280 if (CC != X86::COND_E && CC != X86::COND_NE)
20283 SDValue Cmp = SetCC.getOperand(1);
20284 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20285 !X86::isZeroNode(Cmp.getOperand(1)) ||
20286 !Cmp.getOperand(0).getValueType().isInteger())
20289 SDValue CmpOp0 = Cmp.getOperand(0);
20290 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20291 DAG.getConstant(1, CmpOp0.getValueType()));
20293 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20294 if (CC == X86::COND_NE)
20295 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20296 DL, OtherVal.getValueType(), OtherVal,
20297 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20298 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20299 DL, OtherVal.getValueType(), OtherVal,
20300 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20303 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20304 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20305 const X86Subtarget *Subtarget) {
20306 EVT VT = N->getValueType(0);
20307 SDValue Op0 = N->getOperand(0);
20308 SDValue Op1 = N->getOperand(1);
20310 // Try to synthesize horizontal adds from adds of shuffles.
20311 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20312 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20313 isHorizontalBinOp(Op0, Op1, true))
20314 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20316 return OptimizeConditionalInDecrement(N, DAG);
20319 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20320 const X86Subtarget *Subtarget) {
20321 SDValue Op0 = N->getOperand(0);
20322 SDValue Op1 = N->getOperand(1);
20324 // X86 can't encode an immediate LHS of a sub. See if we can push the
20325 // negation into a preceding instruction.
20326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20327 // If the RHS of the sub is a XOR with one use and a constant, invert the
20328 // immediate. Then add one to the LHS of the sub so we can turn
20329 // X-Y -> X+~Y+1, saving one register.
20330 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20331 isa<ConstantSDNode>(Op1.getOperand(1))) {
20332 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20333 EVT VT = Op0.getValueType();
20334 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20336 DAG.getConstant(~XorC, VT));
20337 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20338 DAG.getConstant(C->getAPIntValue()+1, VT));
20342 // Try to synthesize horizontal adds from adds of shuffles.
20343 EVT VT = N->getValueType(0);
20344 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20345 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20346 isHorizontalBinOp(Op0, Op1, true))
20347 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20349 return OptimizeConditionalInDecrement(N, DAG);
20352 /// performVZEXTCombine - Performs build vector combines
20353 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20354 TargetLowering::DAGCombinerInfo &DCI,
20355 const X86Subtarget *Subtarget) {
20356 // (vzext (bitcast (vzext (x)) -> (vzext x)
20357 SDValue In = N->getOperand(0);
20358 while (In.getOpcode() == ISD::BITCAST)
20359 In = In.getOperand(0);
20361 if (In.getOpcode() != X86ISD::VZEXT)
20364 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20368 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20369 DAGCombinerInfo &DCI) const {
20370 SelectionDAG &DAG = DCI.DAG;
20371 switch (N->getOpcode()) {
20373 case ISD::EXTRACT_VECTOR_ELT:
20374 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20376 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20377 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20378 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20379 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20380 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20381 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20384 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20385 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20386 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20387 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20388 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20389 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20390 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20391 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20392 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20394 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20396 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20397 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20398 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20399 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20400 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20401 case ISD::ANY_EXTEND:
20402 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20403 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20404 case ISD::SIGN_EXTEND_INREG:
20405 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20406 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20407 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20408 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20409 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20410 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20411 case X86ISD::SHUFP: // Handle all target specific shuffles
20412 case X86ISD::PALIGNR:
20413 case X86ISD::UNPCKH:
20414 case X86ISD::UNPCKL:
20415 case X86ISD::MOVHLPS:
20416 case X86ISD::MOVLHPS:
20417 case X86ISD::PSHUFD:
20418 case X86ISD::PSHUFHW:
20419 case X86ISD::PSHUFLW:
20420 case X86ISD::MOVSS:
20421 case X86ISD::MOVSD:
20422 case X86ISD::VPERMILP:
20423 case X86ISD::VPERM2X128:
20424 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20425 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20426 case ISD::INTRINSIC_WO_CHAIN:
20427 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20433 /// isTypeDesirableForOp - Return true if the target has native support for
20434 /// the specified value type and it is 'desirable' to use the type for the
20435 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20436 /// instruction encodings are longer and some i16 instructions are slow.
20437 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20438 if (!isTypeLegal(VT))
20440 if (VT != MVT::i16)
20447 case ISD::SIGN_EXTEND:
20448 case ISD::ZERO_EXTEND:
20449 case ISD::ANY_EXTEND:
20462 /// IsDesirableToPromoteOp - This method query the target whether it is
20463 /// beneficial for dag combiner to promote the specified node. If true, it
20464 /// should return the desired promotion type by reference.
20465 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20466 EVT VT = Op.getValueType();
20467 if (VT != MVT::i16)
20470 bool Promote = false;
20471 bool Commute = false;
20472 switch (Op.getOpcode()) {
20475 LoadSDNode *LD = cast<LoadSDNode>(Op);
20476 // If the non-extending load has a single use and it's not live out, then it
20477 // might be folded.
20478 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20479 Op.hasOneUse()*/) {
20480 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20481 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20482 // The only case where we'd want to promote LOAD (rather then it being
20483 // promoted as an operand is when it's only use is liveout.
20484 if (UI->getOpcode() != ISD::CopyToReg)
20491 case ISD::SIGN_EXTEND:
20492 case ISD::ZERO_EXTEND:
20493 case ISD::ANY_EXTEND:
20498 SDValue N0 = Op.getOperand(0);
20499 // Look out for (store (shl (load), x)).
20500 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20513 SDValue N0 = Op.getOperand(0);
20514 SDValue N1 = Op.getOperand(1);
20515 if (!Commute && MayFoldLoad(N1))
20517 // Avoid disabling potential load folding opportunities.
20518 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20520 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20530 //===----------------------------------------------------------------------===//
20531 // X86 Inline Assembly Support
20532 //===----------------------------------------------------------------------===//
20535 // Helper to match a string separated by whitespace.
20536 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20537 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20539 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20540 StringRef piece(*args[i]);
20541 if (!s.startswith(piece)) // Check if the piece matches.
20544 s = s.substr(piece.size());
20545 StringRef::size_type pos = s.find_first_not_of(" \t");
20546 if (pos == 0) // We matched a prefix.
20554 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20557 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20559 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20560 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20561 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20562 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20564 if (AsmPieces.size() == 3)
20566 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20573 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20574 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20576 std::string AsmStr = IA->getAsmString();
20578 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20579 if (!Ty || Ty->getBitWidth() % 16 != 0)
20582 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20583 SmallVector<StringRef, 4> AsmPieces;
20584 SplitString(AsmStr, AsmPieces, ";\n");
20586 switch (AsmPieces.size()) {
20587 default: return false;
20589 // FIXME: this should verify that we are targeting a 486 or better. If not,
20590 // we will turn this bswap into something that will be lowered to logical
20591 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20592 // lower so don't worry about this.
20594 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20595 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20596 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20597 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20598 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20599 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20600 // No need to check constraints, nothing other than the equivalent of
20601 // "=r,0" would be valid here.
20602 return IntrinsicLowering::LowerToByteSwap(CI);
20605 // rorw $$8, ${0:w} --> llvm.bswap.i16
20606 if (CI->getType()->isIntegerTy(16) &&
20607 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20608 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20609 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20611 const std::string &ConstraintsStr = IA->getConstraintString();
20612 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20613 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20614 if (clobbersFlagRegisters(AsmPieces))
20615 return IntrinsicLowering::LowerToByteSwap(CI);
20619 if (CI->getType()->isIntegerTy(32) &&
20620 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20621 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20622 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20623 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20625 const std::string &ConstraintsStr = IA->getConstraintString();
20626 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20627 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20628 if (clobbersFlagRegisters(AsmPieces))
20629 return IntrinsicLowering::LowerToByteSwap(CI);
20632 if (CI->getType()->isIntegerTy(64)) {
20633 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20634 if (Constraints.size() >= 2 &&
20635 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20636 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20637 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20638 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20639 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20640 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20641 return IntrinsicLowering::LowerToByteSwap(CI);
20649 /// getConstraintType - Given a constraint letter, return the type of
20650 /// constraint it is for this target.
20651 X86TargetLowering::ConstraintType
20652 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20653 if (Constraint.size() == 1) {
20654 switch (Constraint[0]) {
20665 return C_RegisterClass;
20689 return TargetLowering::getConstraintType(Constraint);
20692 /// Examine constraint type and operand type and determine a weight value.
20693 /// This object must already have been set up with the operand type
20694 /// and the current alternative constraint selected.
20695 TargetLowering::ConstraintWeight
20696 X86TargetLowering::getSingleConstraintMatchWeight(
20697 AsmOperandInfo &info, const char *constraint) const {
20698 ConstraintWeight weight = CW_Invalid;
20699 Value *CallOperandVal = info.CallOperandVal;
20700 // If we don't have a value, we can't do a match,
20701 // but allow it at the lowest weight.
20702 if (!CallOperandVal)
20704 Type *type = CallOperandVal->getType();
20705 // Look at the constraint type.
20706 switch (*constraint) {
20708 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20719 if (CallOperandVal->getType()->isIntegerTy())
20720 weight = CW_SpecificReg;
20725 if (type->isFloatingPointTy())
20726 weight = CW_SpecificReg;
20729 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20730 weight = CW_SpecificReg;
20734 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20735 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20736 weight = CW_Register;
20739 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20740 if (C->getZExtValue() <= 31)
20741 weight = CW_Constant;
20745 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20746 if (C->getZExtValue() <= 63)
20747 weight = CW_Constant;
20751 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20752 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20753 weight = CW_Constant;
20757 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20758 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20759 weight = CW_Constant;
20763 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20764 if (C->getZExtValue() <= 3)
20765 weight = CW_Constant;
20769 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20770 if (C->getZExtValue() <= 0xff)
20771 weight = CW_Constant;
20776 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20777 weight = CW_Constant;
20781 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20782 if ((C->getSExtValue() >= -0x80000000LL) &&
20783 (C->getSExtValue() <= 0x7fffffffLL))
20784 weight = CW_Constant;
20788 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20789 if (C->getZExtValue() <= 0xffffffff)
20790 weight = CW_Constant;
20797 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20798 /// with another that has more specific requirements based on the type of the
20799 /// corresponding operand.
20800 const char *X86TargetLowering::
20801 LowerXConstraint(EVT ConstraintVT) const {
20802 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20803 // 'f' like normal targets.
20804 if (ConstraintVT.isFloatingPoint()) {
20805 if (Subtarget->hasSSE2())
20807 if (Subtarget->hasSSE1())
20811 return TargetLowering::LowerXConstraint(ConstraintVT);
20814 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20815 /// vector. If it is invalid, don't add anything to Ops.
20816 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20817 std::string &Constraint,
20818 std::vector<SDValue>&Ops,
20819 SelectionDAG &DAG) const {
20822 // Only support length 1 constraints for now.
20823 if (Constraint.length() > 1) return;
20825 char ConstraintLetter = Constraint[0];
20826 switch (ConstraintLetter) {
20829 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20830 if (C->getZExtValue() <= 31) {
20831 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20837 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20838 if (C->getZExtValue() <= 63) {
20839 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20845 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20846 if (isInt<8>(C->getSExtValue())) {
20847 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20854 if (C->getZExtValue() <= 255) {
20855 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20861 // 32-bit signed value
20862 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20863 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20864 C->getSExtValue())) {
20865 // Widen to 64 bits here to get it sign extended.
20866 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20869 // FIXME gcc accepts some relocatable values here too, but only in certain
20870 // memory models; it's complicated.
20875 // 32-bit unsigned value
20876 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20877 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20878 C->getZExtValue())) {
20879 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20883 // FIXME gcc accepts some relocatable values here too, but only in certain
20884 // memory models; it's complicated.
20888 // Literal immediates are always ok.
20889 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20890 // Widen to 64 bits here to get it sign extended.
20891 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20895 // In any sort of PIC mode addresses need to be computed at runtime by
20896 // adding in a register or some sort of table lookup. These can't
20897 // be used as immediates.
20898 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20901 // If we are in non-pic codegen mode, we allow the address of a global (with
20902 // an optional displacement) to be used with 'i'.
20903 GlobalAddressSDNode *GA = nullptr;
20904 int64_t Offset = 0;
20906 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20908 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20909 Offset += GA->getOffset();
20911 } else if (Op.getOpcode() == ISD::ADD) {
20912 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20913 Offset += C->getZExtValue();
20914 Op = Op.getOperand(0);
20917 } else if (Op.getOpcode() == ISD::SUB) {
20918 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20919 Offset += -C->getZExtValue();
20920 Op = Op.getOperand(0);
20925 // Otherwise, this isn't something we can handle, reject it.
20929 const GlobalValue *GV = GA->getGlobal();
20930 // If we require an extra load to get this address, as in PIC mode, we
20931 // can't accept it.
20932 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20933 getTargetMachine())))
20936 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20937 GA->getValueType(0), Offset);
20942 if (Result.getNode()) {
20943 Ops.push_back(Result);
20946 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20949 std::pair<unsigned, const TargetRegisterClass*>
20950 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20952 // First, see if this is a constraint that directly corresponds to an LLVM
20954 if (Constraint.size() == 1) {
20955 // GCC Constraint Letters
20956 switch (Constraint[0]) {
20958 // TODO: Slight differences here in allocation order and leaving
20959 // RIP in the class. Do they matter any more here than they do
20960 // in the normal allocation?
20961 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20962 if (Subtarget->is64Bit()) {
20963 if (VT == MVT::i32 || VT == MVT::f32)
20964 return std::make_pair(0U, &X86::GR32RegClass);
20965 if (VT == MVT::i16)
20966 return std::make_pair(0U, &X86::GR16RegClass);
20967 if (VT == MVT::i8 || VT == MVT::i1)
20968 return std::make_pair(0U, &X86::GR8RegClass);
20969 if (VT == MVT::i64 || VT == MVT::f64)
20970 return std::make_pair(0U, &X86::GR64RegClass);
20973 // 32-bit fallthrough
20974 case 'Q': // Q_REGS
20975 if (VT == MVT::i32 || VT == MVT::f32)
20976 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20977 if (VT == MVT::i16)
20978 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20979 if (VT == MVT::i8 || VT == MVT::i1)
20980 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20981 if (VT == MVT::i64)
20982 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20984 case 'r': // GENERAL_REGS
20985 case 'l': // INDEX_REGS
20986 if (VT == MVT::i8 || VT == MVT::i1)
20987 return std::make_pair(0U, &X86::GR8RegClass);
20988 if (VT == MVT::i16)
20989 return std::make_pair(0U, &X86::GR16RegClass);
20990 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20991 return std::make_pair(0U, &X86::GR32RegClass);
20992 return std::make_pair(0U, &X86::GR64RegClass);
20993 case 'R': // LEGACY_REGS
20994 if (VT == MVT::i8 || VT == MVT::i1)
20995 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20996 if (VT == MVT::i16)
20997 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20998 if (VT == MVT::i32 || !Subtarget->is64Bit())
20999 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21000 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21001 case 'f': // FP Stack registers.
21002 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21003 // value to the correct fpstack register class.
21004 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21005 return std::make_pair(0U, &X86::RFP32RegClass);
21006 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21007 return std::make_pair(0U, &X86::RFP64RegClass);
21008 return std::make_pair(0U, &X86::RFP80RegClass);
21009 case 'y': // MMX_REGS if MMX allowed.
21010 if (!Subtarget->hasMMX()) break;
21011 return std::make_pair(0U, &X86::VR64RegClass);
21012 case 'Y': // SSE_REGS if SSE2 allowed
21013 if (!Subtarget->hasSSE2()) break;
21015 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21016 if (!Subtarget->hasSSE1()) break;
21018 switch (VT.SimpleTy) {
21020 // Scalar SSE types.
21023 return std::make_pair(0U, &X86::FR32RegClass);
21026 return std::make_pair(0U, &X86::FR64RegClass);
21034 return std::make_pair(0U, &X86::VR128RegClass);
21042 return std::make_pair(0U, &X86::VR256RegClass);
21047 return std::make_pair(0U, &X86::VR512RegClass);
21053 // Use the default implementation in TargetLowering to convert the register
21054 // constraint into a member of a register class.
21055 std::pair<unsigned, const TargetRegisterClass*> Res;
21056 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21058 // Not found as a standard register?
21060 // Map st(0) -> st(7) -> ST0
21061 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21062 tolower(Constraint[1]) == 's' &&
21063 tolower(Constraint[2]) == 't' &&
21064 Constraint[3] == '(' &&
21065 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21066 Constraint[5] == ')' &&
21067 Constraint[6] == '}') {
21069 Res.first = X86::ST0+Constraint[4]-'0';
21070 Res.second = &X86::RFP80RegClass;
21074 // GCC allows "st(0)" to be called just plain "st".
21075 if (StringRef("{st}").equals_lower(Constraint)) {
21076 Res.first = X86::ST0;
21077 Res.second = &X86::RFP80RegClass;
21082 if (StringRef("{flags}").equals_lower(Constraint)) {
21083 Res.first = X86::EFLAGS;
21084 Res.second = &X86::CCRRegClass;
21088 // 'A' means EAX + EDX.
21089 if (Constraint == "A") {
21090 Res.first = X86::EAX;
21091 Res.second = &X86::GR32_ADRegClass;
21097 // Otherwise, check to see if this is a register class of the wrong value
21098 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21099 // turn into {ax},{dx}.
21100 if (Res.second->hasType(VT))
21101 return Res; // Correct type already, nothing to do.
21103 // All of the single-register GCC register classes map their values onto
21104 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21105 // really want an 8-bit or 32-bit register, map to the appropriate register
21106 // class and return the appropriate register.
21107 if (Res.second == &X86::GR16RegClass) {
21108 if (VT == MVT::i8 || VT == MVT::i1) {
21109 unsigned DestReg = 0;
21110 switch (Res.first) {
21112 case X86::AX: DestReg = X86::AL; break;
21113 case X86::DX: DestReg = X86::DL; break;
21114 case X86::CX: DestReg = X86::CL; break;
21115 case X86::BX: DestReg = X86::BL; break;
21118 Res.first = DestReg;
21119 Res.second = &X86::GR8RegClass;
21121 } else if (VT == MVT::i32 || VT == MVT::f32) {
21122 unsigned DestReg = 0;
21123 switch (Res.first) {
21125 case X86::AX: DestReg = X86::EAX; break;
21126 case X86::DX: DestReg = X86::EDX; break;
21127 case X86::CX: DestReg = X86::ECX; break;
21128 case X86::BX: DestReg = X86::EBX; break;
21129 case X86::SI: DestReg = X86::ESI; break;
21130 case X86::DI: DestReg = X86::EDI; break;
21131 case X86::BP: DestReg = X86::EBP; break;
21132 case X86::SP: DestReg = X86::ESP; break;
21135 Res.first = DestReg;
21136 Res.second = &X86::GR32RegClass;
21138 } else if (VT == MVT::i64 || VT == MVT::f64) {
21139 unsigned DestReg = 0;
21140 switch (Res.first) {
21142 case X86::AX: DestReg = X86::RAX; break;
21143 case X86::DX: DestReg = X86::RDX; break;
21144 case X86::CX: DestReg = X86::RCX; break;
21145 case X86::BX: DestReg = X86::RBX; break;
21146 case X86::SI: DestReg = X86::RSI; break;
21147 case X86::DI: DestReg = X86::RDI; break;
21148 case X86::BP: DestReg = X86::RBP; break;
21149 case X86::SP: DestReg = X86::RSP; break;
21152 Res.first = DestReg;
21153 Res.second = &X86::GR64RegClass;
21156 } else if (Res.second == &X86::FR32RegClass ||
21157 Res.second == &X86::FR64RegClass ||
21158 Res.second == &X86::VR128RegClass ||
21159 Res.second == &X86::VR256RegClass ||
21160 Res.second == &X86::FR32XRegClass ||
21161 Res.second == &X86::FR64XRegClass ||
21162 Res.second == &X86::VR128XRegClass ||
21163 Res.second == &X86::VR256XRegClass ||
21164 Res.second == &X86::VR512RegClass) {
21165 // Handle references to XMM physical registers that got mapped into the
21166 // wrong class. This can happen with constraints like {xmm0} where the
21167 // target independent register mapper will just pick the first match it can
21168 // find, ignoring the required type.
21170 if (VT == MVT::f32 || VT == MVT::i32)
21171 Res.second = &X86::FR32RegClass;
21172 else if (VT == MVT::f64 || VT == MVT::i64)
21173 Res.second = &X86::FR64RegClass;
21174 else if (X86::VR128RegClass.hasType(VT))
21175 Res.second = &X86::VR128RegClass;
21176 else if (X86::VR256RegClass.hasType(VT))
21177 Res.second = &X86::VR256RegClass;
21178 else if (X86::VR512RegClass.hasType(VT))
21179 Res.second = &X86::VR512RegClass;
21185 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21187 // Scaling factors are not free at all.
21188 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21189 // will take 2 allocations in the out of order engine instead of 1
21190 // for plain addressing mode, i.e. inst (reg1).
21192 // vaddps (%rsi,%drx), %ymm0, %ymm1
21193 // Requires two allocations (one for the load, one for the computation)
21195 // vaddps (%rsi), %ymm0, %ymm1
21196 // Requires just 1 allocation, i.e., freeing allocations for other operations
21197 // and having less micro operations to execute.
21199 // For some X86 architectures, this is even worse because for instance for
21200 // stores, the complex addressing mode forces the instruction to use the
21201 // "load" ports instead of the dedicated "store" port.
21202 // E.g., on Haswell:
21203 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21204 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21205 if (isLegalAddressingMode(AM, Ty))
21206 // Scale represents reg2 * scale, thus account for 1
21207 // as soon as we use a second register.
21208 return AM.Scale != 0;