1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62 SelectionDAG &DAG, SDLoc dl,
63 unsigned vectorWidth) {
64 assert((vectorWidth == 128 || vectorWidth == 256) &&
65 "Unsupported vector width");
66 EVT VT = Vec.getValueType();
67 EVT ElVT = VT.getVectorElementType();
68 unsigned Factor = VT.getSizeInBits()/vectorWidth;
69 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70 VT.getVectorNumElements()/Factor);
72 // Extract from UNDEF is UNDEF.
73 if (Vec.getOpcode() == ISD::UNDEF)
74 return DAG.getUNDEF(ResultVT);
76 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
77 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79 // This is the index of the first element of the vectorWidth-bit chunk
81 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84 // If the input is a buildvector just emit a smaller one.
85 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103 SelectionDAG &DAG, SDLoc dl) {
104 assert((Vec.getValueType().is256BitVector() ||
105 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111 SelectionDAG &DAG, SDLoc dl) {
112 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117 unsigned IdxVal, SelectionDAG &DAG,
118 SDLoc dl, unsigned vectorWidth) {
119 assert((vectorWidth == 128 || vectorWidth == 256) &&
120 "Unsupported vector width");
121 // Inserting UNDEF is Result
122 if (Vec.getOpcode() == ISD::UNDEF)
124 EVT VT = Vec.getValueType();
125 EVT ElVT = VT.getVectorElementType();
126 EVT ResultVT = Result.getValueType();
128 // Insert the relevant vectorWidth bits.
129 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131 // This is the index of the first element of the vectorWidth-bit chunk
133 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
136 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
140 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference. Idx is an index in the 128 bits
144 /// we want. It need not be aligned to a 128-bit bounday. That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147 unsigned IdxVal, SelectionDAG &DAG,
149 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154 unsigned IdxVal, SelectionDAG &DAG,
156 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165 unsigned NumElems, SelectionDAG &DAG,
167 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172 unsigned NumElems, SelectionDAG &DAG,
174 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180 bool is64Bit = Subtarget->is64Bit();
182 if (Subtarget->isTargetEnvMacho()) {
184 return new X86_64MachoTargetObjectFile();
185 return new TargetLoweringObjectFileMachO();
188 if (Subtarget->isTargetLinux())
189 return new X86LinuxTargetObjectFile();
190 if (Subtarget->isTargetELF())
191 return new TargetLoweringObjectFileELF();
192 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
193 return new TargetLoweringObjectFileCOFF();
194 llvm_unreachable("unknown subtarget type");
197 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
198 : TargetLowering(TM, createTLOF(TM)) {
199 Subtarget = &TM.getSubtarget<X86Subtarget>();
200 X86ScalarSSEf64 = Subtarget->hasSSE2();
201 X86ScalarSSEf32 = Subtarget->hasSSE1();
202 TD = getDataLayout();
204 resetOperationActions();
207 void X86TargetLowering::resetOperationActions() {
208 const TargetMachine &TM = getTargetMachine();
209 static bool FirstTimeThrough = true;
211 // If none of the target options have changed, then we don't need to reset the
212 // operation actions.
213 if (!FirstTimeThrough && TO == TM.Options) return;
215 if (!FirstTimeThrough) {
216 // Reinitialize the actions.
218 FirstTimeThrough = false;
223 // Set up the TargetLowering object.
224 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
226 // X86 is weird, it always uses i8 for shift amounts and setcc results.
227 setBooleanContents(ZeroOrOneBooleanContent);
228 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
229 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231 // For 64-bit since we have so many registers use the ILP scheduler, for
232 // 32-bit code use the register pressure specific scheduling.
233 // For Atom, always use ILP scheduling.
234 if (Subtarget->isAtom())
235 setSchedulingPreference(Sched::ILP);
236 else if (Subtarget->is64Bit())
237 setSchedulingPreference(Sched::ILP);
239 setSchedulingPreference(Sched::RegPressure);
240 const X86RegisterInfo *RegInfo =
241 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
242 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
244 // Bypass expensive divides on Atom when compiling with O2
245 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
246 addBypassSlowDiv(32, 8);
247 if (Subtarget->is64Bit())
248 addBypassSlowDiv(64, 16);
251 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
252 // Setup Windows compiler runtime calls.
253 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
254 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
255 setLibcallName(RTLIB::SREM_I64, "_allrem");
256 setLibcallName(RTLIB::UREM_I64, "_aullrem");
257 setLibcallName(RTLIB::MUL_I64, "_allmul");
258 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
259 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
260 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
264 // The _ftol2 runtime function has an unusual calling conv, which
265 // is modeled by a special pseudo-instruction.
266 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
267 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
268 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
269 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
272 if (Subtarget->isTargetDarwin()) {
273 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
274 setUseUnderscoreSetJmp(false);
275 setUseUnderscoreLongJmp(false);
276 } else if (Subtarget->isTargetMingw()) {
277 // MS runtime is weird: it exports _setjmp, but longjmp!
278 setUseUnderscoreSetJmp(true);
279 setUseUnderscoreLongJmp(false);
281 setUseUnderscoreSetJmp(true);
282 setUseUnderscoreLongJmp(true);
285 // Set up the register classes.
286 addRegisterClass(MVT::i8, &X86::GR8RegClass);
287 addRegisterClass(MVT::i16, &X86::GR16RegClass);
288 addRegisterClass(MVT::i32, &X86::GR32RegClass);
289 if (Subtarget->is64Bit())
290 addRegisterClass(MVT::i64, &X86::GR64RegClass);
292 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
294 // We don't accept any truncstore of integer registers.
295 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
296 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
297 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
298 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
302 // SETOEQ and SETUNE require checking two conditions.
303 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
304 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
305 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
306 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
310 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
312 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
313 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
314 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
316 if (Subtarget->is64Bit()) {
317 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
319 } else if (!TM.Options.UseSoftFloat) {
320 // We have an algorithm for SSE2->double, and we turn this into a
321 // 64-bit FILD followed by conditional FADD for other targets.
322 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
323 // We have an algorithm for SSE2, and we turn this into a 64-bit
324 // FILD for other targets.
325 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
328 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
330 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
331 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
333 if (!TM.Options.UseSoftFloat) {
334 // SSE has no i16 to fp conversion, only i32
335 if (X86ScalarSSEf32) {
336 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
337 // f32 and f64 cases are Legal, f80 case is not
338 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
340 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
341 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
348 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
349 // are Legal, f80 is custom lowered.
350 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
351 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
353 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
355 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
356 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
358 if (X86ScalarSSEf32) {
359 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
360 // f32 and f64 cases are Legal, f80 case is not
361 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
363 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
364 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
367 // Handle FP_TO_UINT by promoting the destination to a larger signed
369 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
370 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
371 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
373 if (Subtarget->is64Bit()) {
374 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
376 } else if (!TM.Options.UseSoftFloat) {
377 // Since AVX is a superset of SSE3, only check for SSE here.
378 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
379 // Expand FP_TO_UINT into a select.
380 // FIXME: We would like to use a Custom expander here eventually to do
381 // the optimal thing for SSE vs. the default expansion in the legalizer.
382 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
384 // With SSE3 we can use fisttpll to convert to a signed i64; without
385 // SSE, we're stuck with a fistpll.
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
389 if (isTargetFTOL()) {
390 // Use the _ftol2 runtime function, which has a pseudo-instruction
391 // to handle its weird calling convention.
392 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
395 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
396 if (!X86ScalarSSEf64) {
397 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
398 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
399 if (Subtarget->is64Bit()) {
400 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
401 // Without SSE, i64->f64 goes through memory.
402 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
406 // Scalar integer divide and remainder are lowered to use operations that
407 // produce two results, to match the available instructions. This exposes
408 // the two-result form to trivial CSE, which is able to combine x/y and x%y
409 // into a single instruction.
411 // Scalar integer multiply-high is also lowered to use two-result
412 // operations, to match the available instructions. However, plain multiply
413 // (low) operations are left as Legal, as there are single-result
414 // instructions for this in x86. Using the two-result multiply instructions
415 // when both high and low results are needed must be arranged by dagcombine.
416 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
418 setOperationAction(ISD::MULHS, VT, Expand);
419 setOperationAction(ISD::MULHU, VT, Expand);
420 setOperationAction(ISD::SDIV, VT, Expand);
421 setOperationAction(ISD::UDIV, VT, Expand);
422 setOperationAction(ISD::SREM, VT, Expand);
423 setOperationAction(ISD::UREM, VT, Expand);
425 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
426 setOperationAction(ISD::ADDC, VT, Custom);
427 setOperationAction(ISD::ADDE, VT, Custom);
428 setOperationAction(ISD::SUBC, VT, Custom);
429 setOperationAction(ISD::SUBE, VT, Custom);
432 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
433 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
434 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
435 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
436 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
437 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
438 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
441 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
442 if (Subtarget->is64Bit())
443 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
444 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
447 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
448 setOperationAction(ISD::FREM , MVT::f32 , Expand);
449 setOperationAction(ISD::FREM , MVT::f64 , Expand);
450 setOperationAction(ISD::FREM , MVT::f80 , Expand);
451 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
453 // Promote the i8 variants and force them on up to i32 which has a shorter
455 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
456 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
457 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
459 if (Subtarget->hasBMI()) {
460 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
461 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
462 if (Subtarget->is64Bit())
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
465 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
466 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
467 if (Subtarget->is64Bit())
468 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
471 if (Subtarget->hasLZCNT()) {
472 // When promoting the i8 variants, force them to i32 for a shorter
474 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
475 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
480 if (Subtarget->is64Bit())
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
483 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
484 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
485 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
487 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
489 if (Subtarget->is64Bit()) {
490 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
495 if (Subtarget->hasPOPCNT()) {
496 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
498 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
499 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
500 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
501 if (Subtarget->is64Bit())
502 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
505 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
506 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
508 // These should be promoted to a larger select which is supported.
509 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
510 // X86 wants to expand cmov itself.
511 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
512 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
513 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
514 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
515 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
516 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
517 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
518 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
519 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
520 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
521 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
522 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
523 if (Subtarget->is64Bit()) {
524 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
527 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
528 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
529 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
530 // support continuation, user-level threading, and etc.. As a result, no
531 // other SjLj exception interfaces are implemented and please don't build
532 // your own exception handling based on them.
533 // LLVM/Clang supports zero-cost DWARF exception handling.
534 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
535 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
538 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
539 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
540 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
541 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
542 if (Subtarget->is64Bit())
543 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
544 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
545 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
546 if (Subtarget->is64Bit()) {
547 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
548 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
549 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
550 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
551 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
553 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
554 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
555 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
556 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
557 if (Subtarget->is64Bit()) {
558 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
563 if (Subtarget->hasSSE1())
564 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
566 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
568 // Expand certain atomics
569 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
571 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
572 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
573 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
576 if (!Subtarget->is64Bit()) {
577 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
578 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
579 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
580 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
581 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
591 if (Subtarget->hasCmpxchg16b()) {
592 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
595 // FIXME - use subtarget debug flags
596 if (!Subtarget->isTargetDarwin() &&
597 !Subtarget->isTargetELF() &&
598 !Subtarget->isTargetCygMing()) {
599 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
602 if (Subtarget->is64Bit()) {
603 setExceptionPointerRegister(X86::RAX);
604 setExceptionSelectorRegister(X86::RDX);
606 setExceptionPointerRegister(X86::EAX);
607 setExceptionSelectorRegister(X86::EDX);
609 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
610 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
612 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
613 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
615 setOperationAction(ISD::TRAP, MVT::Other, Legal);
616 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
618 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
619 setOperationAction(ISD::VASTART , MVT::Other, Custom);
620 setOperationAction(ISD::VAEND , MVT::Other, Expand);
621 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
622 // TargetInfo::X86_64ABIBuiltinVaList
623 setOperationAction(ISD::VAARG , MVT::Other, Custom);
624 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
626 // TargetInfo::CharPtrBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Expand);
628 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
631 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
632 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
634 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
635 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
636 MVT::i64 : MVT::i32, Custom);
637 else if (TM.Options.EnableSegmentedStacks)
638 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639 MVT::i64 : MVT::i32, Custom);
641 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642 MVT::i64 : MVT::i32, Expand);
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::UMUL_LOHI, VT, Expand);
832 setOperationAction(ISD::SDIVREM, VT, Expand);
833 setOperationAction(ISD::UDIVREM, VT, Expand);
834 setOperationAction(ISD::FPOW, VT, Expand);
835 setOperationAction(ISD::CTPOP, VT, Expand);
836 setOperationAction(ISD::CTTZ, VT, Expand);
837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::CTLZ, VT, Expand);
839 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::SHL, VT, Expand);
841 setOperationAction(ISD::SRA, VT, Expand);
842 setOperationAction(ISD::SRL, VT, Expand);
843 setOperationAction(ISD::ROTL, VT, Expand);
844 setOperationAction(ISD::ROTR, VT, Expand);
845 setOperationAction(ISD::BSWAP, VT, Expand);
846 setOperationAction(ISD::SETCC, VT, Expand);
847 setOperationAction(ISD::FLOG, VT, Expand);
848 setOperationAction(ISD::FLOG2, VT, Expand);
849 setOperationAction(ISD::FLOG10, VT, Expand);
850 setOperationAction(ISD::FEXP, VT, Expand);
851 setOperationAction(ISD::FEXP2, VT, Expand);
852 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857 setOperationAction(ISD::TRUNCATE, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861 setOperationAction(ISD::VSELECT, VT, Expand);
862 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864 setTruncStoreAction(VT,
865 (MVT::SimpleValueType)InnerVT, Expand);
866 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872 // with -msoft-float, disable use of MMX as well.
873 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875 // No operations on x86mmx supported, everything uses intrinsics.
878 // MMX-sized vectors (other than x86mmx) are expected to be expanded
879 // into smaller operations.
880 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
881 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
882 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
883 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
884 setOperationAction(ISD::AND, MVT::v8i8, Expand);
885 setOperationAction(ISD::AND, MVT::v4i16, Expand);
886 setOperationAction(ISD::AND, MVT::v2i32, Expand);
887 setOperationAction(ISD::AND, MVT::v1i64, Expand);
888 setOperationAction(ISD::OR, MVT::v8i8, Expand);
889 setOperationAction(ISD::OR, MVT::v4i16, Expand);
890 setOperationAction(ISD::OR, MVT::v2i32, Expand);
891 setOperationAction(ISD::OR, MVT::v1i64, Expand);
892 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
893 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
894 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
895 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
901 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
902 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
903 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
904 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
910 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
914 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
915 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
916 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
917 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
918 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
919 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
920 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
921 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
922 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
927 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931 // registers cannot be used even for integer operations.
932 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
938 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
939 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
940 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
941 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
942 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
943 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
944 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
945 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
946 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
947 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
948 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
949 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
950 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
951 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
953 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
954 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
956 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
957 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
958 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
959 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
961 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
962 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
967 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
968 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
969 MVT VT = (MVT::SimpleValueType)i;
970 // Do not attempt to custom lower non-power-of-2 vectors
971 if (!isPowerOf2_32(VT.getVectorNumElements()))
973 // Do not attempt to custom lower non-128-bit vectors
974 if (!VT.is128BitVector())
976 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
977 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
978 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
981 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
982 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
983 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
984 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
986 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
988 if (Subtarget->is64Bit()) {
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
993 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
994 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
995 MVT VT = (MVT::SimpleValueType)i;
997 // Do not attempt to promote non-128-bit vectors
998 if (!VT.is128BitVector())
1001 setOperationAction(ISD::AND, VT, Promote);
1002 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1003 setOperationAction(ISD::OR, VT, Promote);
1004 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1005 setOperationAction(ISD::XOR, VT, Promote);
1006 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1007 setOperationAction(ISD::LOAD, VT, Promote);
1008 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1009 setOperationAction(ISD::SELECT, VT, Promote);
1010 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1013 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1015 // Custom lower v2i64 and v2f64 selects.
1016 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1017 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1018 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1019 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1021 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1022 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1024 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1025 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1026 // As there is no 64-bit GPR available, we need build a special custom
1027 // sequence to convert from v2i32 to v2f32.
1028 if (!Subtarget->is64Bit())
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1031 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1032 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1034 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1037 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1038 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1039 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1040 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1041 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1042 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1043 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1044 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1045 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1046 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1047 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1049 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1050 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1051 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1052 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1053 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1055 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1056 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1057 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1058 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1060 // FIXME: Do we need to handle scalar-to-vector here?
1061 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1063 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1064 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1069 // i8 and i16 vectors are custom , because the source register and source
1070 // source memory operand types are not the same width. f32 vectors are
1071 // custom since the immediate controlling the insert encodes additional
1073 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1075 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1076 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1078 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1080 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1081 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1083 // FIXME: these should be Legal but thats only for the case where
1084 // the index is constant. For now custom expand to deal with that.
1085 if (Subtarget->is64Bit()) {
1086 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1091 if (Subtarget->hasSSE2()) {
1092 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1093 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1095 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1096 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1098 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1099 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1101 // In the customized shift lowering, the legal cases in AVX2 will be
1103 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1104 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1106 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1107 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1109 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1111 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1112 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1115 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1116 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1117 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1123 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1124 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1125 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1127 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1128 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1138 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1140 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1141 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1151 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1153 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1154 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1156 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1158 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1159 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1160 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1161 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1163 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1164 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1167 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1169 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1186 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1187 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1189 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1191 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1192 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1201 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1202 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1203 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1205 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1206 setOperationAction(ISD::FMA, MVT::f32, Legal);
1207 setOperationAction(ISD::FMA, MVT::f64, Legal);
1210 if (Subtarget->hasInt256()) {
1211 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1212 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1213 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1214 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1216 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1217 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1218 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1219 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1221 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1222 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1223 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1224 // Don't lower v32i8 because there is no 128-bit byte mul
1226 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1228 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1230 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1231 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1232 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1233 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1235 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1236 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1237 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1238 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1240 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1241 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1242 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1243 // Don't lower v32i8 because there is no 128-bit byte mul
1246 // In the customized shift lowering, the legal cases in AVX2 will be
1248 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1249 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1254 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1256 // Custom lower several nodes for 256-bit types.
1257 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1258 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1259 MVT VT = (MVT::SimpleValueType)i;
1261 // Extract subvector is special because the value type
1262 // (result) is 128-bit but the source is 256-bit wide.
1263 if (VT.is128BitVector())
1264 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1266 // Do not attempt to custom lower other non-256-bit vectors
1267 if (!VT.is256BitVector())
1270 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1271 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1272 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1273 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1275 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1276 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1279 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1280 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1281 MVT VT = (MVT::SimpleValueType)i;
1283 // Do not attempt to promote non-256-bit vectors
1284 if (!VT.is256BitVector())
1287 setOperationAction(ISD::AND, VT, Promote);
1288 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1289 setOperationAction(ISD::OR, VT, Promote);
1290 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1291 setOperationAction(ISD::XOR, VT, Promote);
1292 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1293 setOperationAction(ISD::LOAD, VT, Promote);
1294 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1295 setOperationAction(ISD::SELECT, VT, Promote);
1296 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1301 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1302 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1303 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1304 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1307 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1309 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1310 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1311 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1312 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1313 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1314 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1316 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1317 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1318 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1319 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1320 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1321 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1323 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1324 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1325 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1326 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1327 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1328 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1329 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1330 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1331 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1334 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1335 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1336 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1337 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1338 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1339 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1340 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1341 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1343 setOperationAction(ISD::TRUNCATE, MVT::i1, Legal);
1344 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1345 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1346 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1347 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1348 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1349 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1350 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1351 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1352 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1353 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1354 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1356 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1357 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1358 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1359 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1360 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1362 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1363 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1365 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1367 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1368 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1369 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1370 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1371 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1373 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1374 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1376 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1377 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1379 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1381 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1382 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1384 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1385 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1387 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1388 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1390 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1391 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1392 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1394 // Custom lower several nodes.
1395 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1396 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1397 MVT VT = (MVT::SimpleValueType)i;
1399 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1400 // Extract subvector is special because the value type
1401 // (result) is 256/128-bit but the source is 512-bit wide.
1402 if (VT.is128BitVector() || VT.is256BitVector())
1403 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1405 if (VT.getVectorElementType() == MVT::i1)
1406 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1408 // Do not attempt to custom lower other non-512-bit vectors
1409 if (!VT.is512BitVector())
1412 if (VT != MVT::v8i64) {
1413 setOperationAction(ISD::XOR, VT, Promote);
1414 AddPromotedToType (ISD::XOR, VT, MVT::v8i64);
1415 setOperationAction(ISD::OR, VT, Promote);
1416 AddPromotedToType (ISD::OR, VT, MVT::v8i64);
1417 setOperationAction(ISD::AND, VT, Promote);
1418 AddPromotedToType (ISD::AND, VT, MVT::v8i64);
1420 if ( EltSize >= 32) {
1421 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1422 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1423 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1424 setOperationAction(ISD::VSELECT, VT, Legal);
1425 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1426 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1427 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1430 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1431 MVT VT = (MVT::SimpleValueType)i;
1433 // Do not attempt to promote non-256-bit vectors
1434 if (!VT.is512BitVector())
1437 setOperationAction(ISD::LOAD, VT, Promote);
1438 AddPromotedToType (ISD::LOAD, VT, MVT::v8i64);
1439 setOperationAction(ISD::SELECT, VT, Promote);
1440 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1444 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1445 // of this type with custom code.
1446 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1447 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1448 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1452 // We want to custom lower some of our intrinsics.
1453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1454 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1456 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1457 // handle type legalization for these operations here.
1459 // FIXME: We really should do custom legalization for addition and
1460 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1461 // than generic legalization for 64-bit multiplication-with-overflow, though.
1462 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1463 // Add/Sub/Mul with overflow operations are custom lowered.
1465 setOperationAction(ISD::SADDO, VT, Custom);
1466 setOperationAction(ISD::UADDO, VT, Custom);
1467 setOperationAction(ISD::SSUBO, VT, Custom);
1468 setOperationAction(ISD::USUBO, VT, Custom);
1469 setOperationAction(ISD::SMULO, VT, Custom);
1470 setOperationAction(ISD::UMULO, VT, Custom);
1473 // There are no 8-bit 3-address imul/mul instructions
1474 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1475 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1477 if (!Subtarget->is64Bit()) {
1478 // These libcalls are not available in 32-bit.
1479 setLibcallName(RTLIB::SHL_I128, 0);
1480 setLibcallName(RTLIB::SRL_I128, 0);
1481 setLibcallName(RTLIB::SRA_I128, 0);
1484 // Combine sin / cos into one node or libcall if possible.
1485 if (Subtarget->hasSinCos()) {
1486 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1487 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1488 if (Subtarget->isTargetDarwin()) {
1489 // For MacOSX, we don't want to the normal expansion of a libcall to
1490 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1492 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1493 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1497 // We have target-specific dag combine patterns for the following nodes:
1498 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1499 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1500 setTargetDAGCombine(ISD::VSELECT);
1501 setTargetDAGCombine(ISD::SELECT);
1502 setTargetDAGCombine(ISD::SHL);
1503 setTargetDAGCombine(ISD::SRA);
1504 setTargetDAGCombine(ISD::SRL);
1505 setTargetDAGCombine(ISD::OR);
1506 setTargetDAGCombine(ISD::AND);
1507 setTargetDAGCombine(ISD::ADD);
1508 setTargetDAGCombine(ISD::FADD);
1509 setTargetDAGCombine(ISD::FSUB);
1510 setTargetDAGCombine(ISD::FMA);
1511 setTargetDAGCombine(ISD::SUB);
1512 setTargetDAGCombine(ISD::LOAD);
1513 setTargetDAGCombine(ISD::STORE);
1514 setTargetDAGCombine(ISD::ZERO_EXTEND);
1515 setTargetDAGCombine(ISD::ANY_EXTEND);
1516 setTargetDAGCombine(ISD::SIGN_EXTEND);
1517 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1518 setTargetDAGCombine(ISD::TRUNCATE);
1519 setTargetDAGCombine(ISD::SINT_TO_FP);
1520 setTargetDAGCombine(ISD::SETCC);
1521 if (Subtarget->is64Bit())
1522 setTargetDAGCombine(ISD::MUL);
1523 setTargetDAGCombine(ISD::XOR);
1525 computeRegisterProperties();
1527 // On Darwin, -Os means optimize for size without hurting performance,
1528 // do not reduce the limit.
1529 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1530 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1531 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1532 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1533 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1534 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1535 setPrefLoopAlignment(4); // 2^4 bytes.
1537 // Predictable cmov don't hurt on atom because it's in-order.
1538 PredictableSelectIsExpensive = !Subtarget->isAtom();
1540 setPrefFunctionAlignment(4); // 2^4 bytes.
1543 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1544 if (!VT.isVector()) return MVT::i8;
1545 return VT.changeVectorElementTypeToInteger();
1548 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1549 /// the desired ByVal argument alignment.
1550 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1553 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1554 if (VTy->getBitWidth() == 128)
1556 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1557 unsigned EltAlign = 0;
1558 getMaxByValAlign(ATy->getElementType(), EltAlign);
1559 if (EltAlign > MaxAlign)
1560 MaxAlign = EltAlign;
1561 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1562 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1563 unsigned EltAlign = 0;
1564 getMaxByValAlign(STy->getElementType(i), EltAlign);
1565 if (EltAlign > MaxAlign)
1566 MaxAlign = EltAlign;
1573 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1574 /// function arguments in the caller parameter area. For X86, aggregates
1575 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1576 /// are at 4-byte boundaries.
1577 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1578 if (Subtarget->is64Bit()) {
1579 // Max of 8 and alignment of type.
1580 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1587 if (Subtarget->hasSSE1())
1588 getMaxByValAlign(Ty, Align);
1592 /// getOptimalMemOpType - Returns the target specific optimal type for load
1593 /// and store operations as a result of memset, memcpy, and memmove
1594 /// lowering. If DstAlign is zero that means it's safe to destination
1595 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1596 /// means there isn't a need to check it against alignment requirement,
1597 /// probably because the source does not need to be loaded. If 'IsMemset' is
1598 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1599 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1600 /// source is constant so it does not need to be loaded.
1601 /// It returns EVT::Other if the type should be determined using generic
1602 /// target-independent logic.
1604 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1605 unsigned DstAlign, unsigned SrcAlign,
1606 bool IsMemset, bool ZeroMemset,
1608 MachineFunction &MF) const {
1609 const Function *F = MF.getFunction();
1610 if ((!IsMemset || ZeroMemset) &&
1611 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1612 Attribute::NoImplicitFloat)) {
1614 (Subtarget->isUnalignedMemAccessFast() ||
1615 ((DstAlign == 0 || DstAlign >= 16) &&
1616 (SrcAlign == 0 || SrcAlign >= 16)))) {
1618 if (Subtarget->hasInt256())
1620 if (Subtarget->hasFp256())
1623 if (Subtarget->hasSSE2())
1625 if (Subtarget->hasSSE1())
1627 } else if (!MemcpyStrSrc && Size >= 8 &&
1628 !Subtarget->is64Bit() &&
1629 Subtarget->hasSSE2()) {
1630 // Do not use f64 to lower memcpy if source is string constant. It's
1631 // better to use i32 to avoid the loads.
1635 if (Subtarget->is64Bit() && Size >= 8)
1640 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1642 return X86ScalarSSEf32;
1643 else if (VT == MVT::f64)
1644 return X86ScalarSSEf64;
1649 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1651 *Fast = Subtarget->isUnalignedMemAccessFast();
1655 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1656 /// current function. The returned value is a member of the
1657 /// MachineJumpTableInfo::JTEntryKind enum.
1658 unsigned X86TargetLowering::getJumpTableEncoding() const {
1659 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1661 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1662 Subtarget->isPICStyleGOT())
1663 return MachineJumpTableInfo::EK_Custom32;
1665 // Otherwise, use the normal jump table encoding heuristics.
1666 return TargetLowering::getJumpTableEncoding();
1670 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1671 const MachineBasicBlock *MBB,
1672 unsigned uid,MCContext &Ctx) const{
1673 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1674 Subtarget->isPICStyleGOT());
1675 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1677 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1678 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1681 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1683 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1684 SelectionDAG &DAG) const {
1685 if (!Subtarget->is64Bit())
1686 // This doesn't have SDLoc associated with it, but is not really the
1687 // same as a Register.
1688 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1692 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1693 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1695 const MCExpr *X86TargetLowering::
1696 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1697 MCContext &Ctx) const {
1698 // X86-64 uses RIP relative addressing based on the jump table label.
1699 if (Subtarget->isPICStyleRIPRel())
1700 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1702 // Otherwise, the reference is relative to the PIC base.
1703 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1706 // FIXME: Why this routine is here? Move to RegInfo!
1707 std::pair<const TargetRegisterClass*, uint8_t>
1708 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1709 const TargetRegisterClass *RRC = 0;
1711 switch (VT.SimpleTy) {
1713 return TargetLowering::findRepresentativeClass(VT);
1714 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1715 RRC = Subtarget->is64Bit() ?
1716 (const TargetRegisterClass*)&X86::GR64RegClass :
1717 (const TargetRegisterClass*)&X86::GR32RegClass;
1720 RRC = &X86::VR64RegClass;
1722 case MVT::f32: case MVT::f64:
1723 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1724 case MVT::v4f32: case MVT::v2f64:
1725 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1727 RRC = &X86::VR128RegClass;
1730 return std::make_pair(RRC, Cost);
1733 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1734 unsigned &Offset) const {
1735 if (!Subtarget->isTargetLinux())
1738 if (Subtarget->is64Bit()) {
1739 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1741 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1753 //===----------------------------------------------------------------------===//
1754 // Return Value Calling Convention Implementation
1755 //===----------------------------------------------------------------------===//
1757 #include "X86GenCallingConv.inc"
1760 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1761 MachineFunction &MF, bool isVarArg,
1762 const SmallVectorImpl<ISD::OutputArg> &Outs,
1763 LLVMContext &Context) const {
1764 SmallVector<CCValAssign, 16> RVLocs;
1765 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1767 return CCInfo.CheckReturn(Outs, RetCC_X86);
1771 X86TargetLowering::LowerReturn(SDValue Chain,
1772 CallingConv::ID CallConv, bool isVarArg,
1773 const SmallVectorImpl<ISD::OutputArg> &Outs,
1774 const SmallVectorImpl<SDValue> &OutVals,
1775 SDLoc dl, SelectionDAG &DAG) const {
1776 MachineFunction &MF = DAG.getMachineFunction();
1777 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1779 SmallVector<CCValAssign, 16> RVLocs;
1780 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1781 RVLocs, *DAG.getContext());
1782 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1785 SmallVector<SDValue, 6> RetOps;
1786 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1787 // Operand #1 = Bytes To Pop
1788 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1791 // Copy the result values into the output registers.
1792 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1793 CCValAssign &VA = RVLocs[i];
1794 assert(VA.isRegLoc() && "Can only return in registers!");
1795 SDValue ValToCopy = OutVals[i];
1796 EVT ValVT = ValToCopy.getValueType();
1798 // Promote values to the appropriate types
1799 if (VA.getLocInfo() == CCValAssign::SExt)
1800 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801 else if (VA.getLocInfo() == CCValAssign::ZExt)
1802 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1803 else if (VA.getLocInfo() == CCValAssign::AExt)
1804 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1805 else if (VA.getLocInfo() == CCValAssign::BCvt)
1806 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1808 // If this is x86-64, and we disabled SSE, we can't return FP values,
1809 // or SSE or MMX vectors.
1810 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1811 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1812 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1813 report_fatal_error("SSE register return with SSE disabled");
1815 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1816 // llvm-gcc has never done it right and no one has noticed, so this
1817 // should be OK for now.
1818 if (ValVT == MVT::f64 &&
1819 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1820 report_fatal_error("SSE2 register return with SSE2 disabled");
1822 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1823 // the RET instruction and handled by the FP Stackifier.
1824 if (VA.getLocReg() == X86::ST0 ||
1825 VA.getLocReg() == X86::ST1) {
1826 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1827 // change the value to the FP stack register class.
1828 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1829 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1830 RetOps.push_back(ValToCopy);
1831 // Don't emit a copytoreg.
1835 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1836 // which is returned in RAX / RDX.
1837 if (Subtarget->is64Bit()) {
1838 if (ValVT == MVT::x86mmx) {
1839 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1840 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1841 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1843 // If we don't have SSE2 available, convert to v4f32 so the generated
1844 // register is legal.
1845 if (!Subtarget->hasSSE2())
1846 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1851 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1852 Flag = Chain.getValue(1);
1853 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1856 // The x86-64 ABIs require that for returning structs by value we copy
1857 // the sret argument into %rax/%eax (depending on ABI) for the return.
1858 // Win32 requires us to put the sret argument to %eax as well.
1859 // We saved the argument into a virtual register in the entry block,
1860 // so now we copy the value out and into %rax/%eax.
1861 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1862 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1863 MachineFunction &MF = DAG.getMachineFunction();
1864 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865 unsigned Reg = FuncInfo->getSRetReturnReg();
1867 "SRetReturnReg should have been set in LowerFormalArguments().");
1868 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1871 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1872 X86::RAX : X86::EAX;
1873 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1874 Flag = Chain.getValue(1);
1876 // RAX/EAX now acts like a return value.
1877 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1880 RetOps[0] = Chain; // Update chain.
1882 // Add the flag if we have it.
1884 RetOps.push_back(Flag);
1886 return DAG.getNode(X86ISD::RET_FLAG, dl,
1887 MVT::Other, &RetOps[0], RetOps.size());
1890 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1891 if (N->getNumValues() != 1)
1893 if (!N->hasNUsesOfValue(1, 0))
1896 SDValue TCChain = Chain;
1897 SDNode *Copy = *N->use_begin();
1898 if (Copy->getOpcode() == ISD::CopyToReg) {
1899 // If the copy has a glue operand, we conservatively assume it isn't safe to
1900 // perform a tail call.
1901 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1903 TCChain = Copy->getOperand(0);
1904 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1907 bool HasRet = false;
1908 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1910 if (UI->getOpcode() != X86ISD::RET_FLAG)
1923 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1924 ISD::NodeType ExtendKind) const {
1926 // TODO: Is this also valid on 32-bit?
1927 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1928 ReturnMVT = MVT::i8;
1930 ReturnMVT = MVT::i32;
1932 MVT MinVT = getRegisterType(ReturnMVT);
1933 return VT.bitsLT(MinVT) ? MinVT : VT;
1936 /// LowerCallResult - Lower the result values of a call into the
1937 /// appropriate copies out of appropriate physical registers.
1940 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1941 CallingConv::ID CallConv, bool isVarArg,
1942 const SmallVectorImpl<ISD::InputArg> &Ins,
1943 SDLoc dl, SelectionDAG &DAG,
1944 SmallVectorImpl<SDValue> &InVals) const {
1946 // Assign locations to each value returned by this call.
1947 SmallVector<CCValAssign, 16> RVLocs;
1948 bool Is64Bit = Subtarget->is64Bit();
1949 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1950 getTargetMachine(), RVLocs, *DAG.getContext());
1951 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1953 // Copy all of the result registers out of their specified physreg.
1954 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1955 CCValAssign &VA = RVLocs[i];
1956 EVT CopyVT = VA.getValVT();
1958 // If this is x86-64, and we disabled SSE, we can't return FP values
1959 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1960 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1961 report_fatal_error("SSE register return with SSE disabled");
1966 // If this is a call to a function that returns an fp value on the floating
1967 // point stack, we must guarantee the value is popped from the stack, so
1968 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1969 // if the return value is not used. We use the FpPOP_RETVAL instruction
1971 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1972 // If we prefer to use the value in xmm registers, copy it out as f80 and
1973 // use a truncate to move it from fp stack reg to xmm reg.
1974 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1975 SDValue Ops[] = { Chain, InFlag };
1976 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1977 MVT::Other, MVT::Glue, Ops), 1);
1978 Val = Chain.getValue(0);
1980 // Round the f80 to the right size, which also moves it to the appropriate
1982 if (CopyVT != VA.getValVT())
1983 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1984 // This truncation won't change the value.
1985 DAG.getIntPtrConstant(1));
1987 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1988 CopyVT, InFlag).getValue(1);
1989 Val = Chain.getValue(0);
1991 InFlag = Chain.getValue(2);
1992 InVals.push_back(Val);
1998 //===----------------------------------------------------------------------===//
1999 // C & StdCall & Fast Calling Convention implementation
2000 //===----------------------------------------------------------------------===//
2001 // StdCall calling convention seems to be standard for many Windows' API
2002 // routines and around. It differs from C calling convention just a little:
2003 // callee should clean up the stack, not caller. Symbols should be also
2004 // decorated in some fancy way :) It doesn't support any vector arguments.
2005 // For info on fast calling convention see Fast Calling Convention (tail call)
2006 // implementation LowerX86_32FastCCCallTo.
2008 /// CallIsStructReturn - Determines whether a call uses struct return
2010 enum StructReturnType {
2015 static StructReturnType
2016 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2018 return NotStructReturn;
2020 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2021 if (!Flags.isSRet())
2022 return NotStructReturn;
2023 if (Flags.isInReg())
2024 return RegStructReturn;
2025 return StackStructReturn;
2028 /// ArgsAreStructReturn - Determines whether a function uses struct
2029 /// return semantics.
2030 static StructReturnType
2031 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2033 return NotStructReturn;
2035 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2036 if (!Flags.isSRet())
2037 return NotStructReturn;
2038 if (Flags.isInReg())
2039 return RegStructReturn;
2040 return StackStructReturn;
2043 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2044 /// by "Src" to address "Dst" with size and alignment information specified by
2045 /// the specific parameter attribute. The copy will be passed as a byval
2046 /// function parameter.
2048 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2049 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2051 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2053 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2054 /*isVolatile*/false, /*AlwaysInline=*/true,
2055 MachinePointerInfo(), MachinePointerInfo());
2058 /// IsTailCallConvention - Return true if the calling convention is one that
2059 /// supports tail call optimization.
2060 static bool IsTailCallConvention(CallingConv::ID CC) {
2061 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2062 CC == CallingConv::HiPE);
2065 /// \brief Return true if the calling convention is a C calling convention.
2066 static bool IsCCallConvention(CallingConv::ID CC) {
2067 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2068 CC == CallingConv::X86_64_SysV);
2071 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2072 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2076 CallingConv::ID CalleeCC = CS.getCallingConv();
2077 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2083 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2084 /// a tailcall target by changing its ABI.
2085 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2086 bool GuaranteedTailCallOpt) {
2087 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2091 X86TargetLowering::LowerMemArgument(SDValue Chain,
2092 CallingConv::ID CallConv,
2093 const SmallVectorImpl<ISD::InputArg> &Ins,
2094 SDLoc dl, SelectionDAG &DAG,
2095 const CCValAssign &VA,
2096 MachineFrameInfo *MFI,
2098 // Create the nodes corresponding to a load from this parameter slot.
2099 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2100 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2101 getTargetMachine().Options.GuaranteedTailCallOpt);
2102 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2105 // If value is passed by pointer we have address passed instead of the value
2107 if (VA.getLocInfo() == CCValAssign::Indirect)
2108 ValVT = VA.getLocVT();
2110 ValVT = VA.getValVT();
2112 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2113 // changed with more analysis.
2114 // In case of tail call optimization mark all arguments mutable. Since they
2115 // could be overwritten by lowering of arguments in case of a tail call.
2116 if (Flags.isByVal()) {
2117 unsigned Bytes = Flags.getByValSize();
2118 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2119 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2120 return DAG.getFrameIndex(FI, getPointerTy());
2122 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2123 VA.getLocMemOffset(), isImmutable);
2124 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2125 return DAG.getLoad(ValVT, dl, Chain, FIN,
2126 MachinePointerInfo::getFixedStack(FI),
2127 false, false, false, 0);
2132 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2133 CallingConv::ID CallConv,
2135 const SmallVectorImpl<ISD::InputArg> &Ins,
2138 SmallVectorImpl<SDValue> &InVals)
2140 MachineFunction &MF = DAG.getMachineFunction();
2141 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2143 const Function* Fn = MF.getFunction();
2144 if (Fn->hasExternalLinkage() &&
2145 Subtarget->isTargetCygMing() &&
2146 Fn->getName() == "main")
2147 FuncInfo->setForceFramePointer(true);
2149 MachineFrameInfo *MFI = MF.getFrameInfo();
2150 bool Is64Bit = Subtarget->is64Bit();
2151 bool IsWindows = Subtarget->isTargetWindows();
2152 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2154 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2155 "Var args not supported with calling convention fastcc, ghc or hipe");
2157 // Assign locations to all of the incoming arguments.
2158 SmallVector<CCValAssign, 16> ArgLocs;
2159 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2160 ArgLocs, *DAG.getContext());
2162 // Allocate shadow area for Win64
2164 CCInfo.AllocateStack(32, 8);
2166 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2168 unsigned LastVal = ~0U;
2170 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2171 CCValAssign &VA = ArgLocs[i];
2172 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2174 assert(VA.getValNo() != LastVal &&
2175 "Don't support value assigned to multiple locs yet");
2177 LastVal = VA.getValNo();
2179 if (VA.isRegLoc()) {
2180 EVT RegVT = VA.getLocVT();
2181 const TargetRegisterClass *RC;
2182 if (RegVT == MVT::i32)
2183 RC = &X86::GR32RegClass;
2184 else if (Is64Bit && RegVT == MVT::i64)
2185 RC = &X86::GR64RegClass;
2186 else if (RegVT == MVT::f32)
2187 RC = &X86::FR32RegClass;
2188 else if (RegVT == MVT::f64)
2189 RC = &X86::FR64RegClass;
2190 else if (RegVT.is512BitVector())
2191 RC = &X86::VR512RegClass;
2192 else if (RegVT.is256BitVector())
2193 RC = &X86::VR256RegClass;
2194 else if (RegVT.is128BitVector())
2195 RC = &X86::VR128RegClass;
2196 else if (RegVT == MVT::x86mmx)
2197 RC = &X86::VR64RegClass;
2198 else if (RegVT == MVT::v8i1)
2199 RC = &X86::VK8RegClass;
2200 else if (RegVT == MVT::v16i1)
2201 RC = &X86::VK16RegClass;
2203 llvm_unreachable("Unknown argument type!");
2205 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2206 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2208 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2209 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2211 if (VA.getLocInfo() == CCValAssign::SExt)
2212 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2213 DAG.getValueType(VA.getValVT()));
2214 else if (VA.getLocInfo() == CCValAssign::ZExt)
2215 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2216 DAG.getValueType(VA.getValVT()));
2217 else if (VA.getLocInfo() == CCValAssign::BCvt)
2218 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2220 if (VA.isExtInLoc()) {
2221 // Handle MMX values passed in XMM regs.
2222 if (RegVT.isVector())
2223 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2225 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2228 assert(VA.isMemLoc());
2229 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2232 // If value is passed via pointer - do a load.
2233 if (VA.getLocInfo() == CCValAssign::Indirect)
2234 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2235 MachinePointerInfo(), false, false, false, 0);
2237 InVals.push_back(ArgValue);
2240 // The x86-64 ABIs require that for returning structs by value we copy
2241 // the sret argument into %rax/%eax (depending on ABI) for the return.
2242 // Win32 requires us to put the sret argument to %eax as well.
2243 // Save the argument into a virtual register so that we can access it
2244 // from the return points.
2245 if (MF.getFunction()->hasStructRetAttr() &&
2246 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2247 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2248 unsigned Reg = FuncInfo->getSRetReturnReg();
2250 MVT PtrTy = getPointerTy();
2251 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2252 FuncInfo->setSRetReturnReg(Reg);
2254 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2255 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2258 unsigned StackSize = CCInfo.getNextStackOffset();
2259 // Align stack specially for tail calls.
2260 if (FuncIsMadeTailCallSafe(CallConv,
2261 MF.getTarget().Options.GuaranteedTailCallOpt))
2262 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2264 // If the function takes variable number of arguments, make a frame index for
2265 // the start of the first vararg value... for expansion of llvm.va_start.
2267 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2268 CallConv != CallingConv::X86_ThisCall)) {
2269 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2272 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2274 // FIXME: We should really autogenerate these arrays
2275 static const uint16_t GPR64ArgRegsWin64[] = {
2276 X86::RCX, X86::RDX, X86::R8, X86::R9
2278 static const uint16_t GPR64ArgRegs64Bit[] = {
2279 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2281 static const uint16_t XMMArgRegs64Bit[] = {
2282 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2283 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2285 const uint16_t *GPR64ArgRegs;
2286 unsigned NumXMMRegs = 0;
2289 // The XMM registers which might contain var arg parameters are shadowed
2290 // in their paired GPR. So we only need to save the GPR to their home
2292 TotalNumIntRegs = 4;
2293 GPR64ArgRegs = GPR64ArgRegsWin64;
2295 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2296 GPR64ArgRegs = GPR64ArgRegs64Bit;
2298 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2301 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2304 bool NoImplicitFloatOps = Fn->getAttributes().
2305 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2306 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2307 "SSE register cannot be used when SSE is disabled!");
2308 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2309 NoImplicitFloatOps) &&
2310 "SSE register cannot be used when SSE is disabled!");
2311 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2312 !Subtarget->hasSSE1())
2313 // Kernel mode asks for SSE to be disabled, so don't push them
2315 TotalNumXMMRegs = 0;
2318 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2319 // Get to the caller-allocated home save location. Add 8 to account
2320 // for the return address.
2321 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2322 FuncInfo->setRegSaveFrameIndex(
2323 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2324 // Fixup to set vararg frame on shadow area (4 x i64).
2326 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2328 // For X86-64, if there are vararg parameters that are passed via
2329 // registers, then we must store them to their spots on the stack so
2330 // they may be loaded by deferencing the result of va_next.
2331 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2332 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2333 FuncInfo->setRegSaveFrameIndex(
2334 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2338 // Store the integer parameter registers.
2339 SmallVector<SDValue, 8> MemOps;
2340 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2342 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2343 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2344 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2345 DAG.getIntPtrConstant(Offset));
2346 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2347 &X86::GR64RegClass);
2348 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2350 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2351 MachinePointerInfo::getFixedStack(
2352 FuncInfo->getRegSaveFrameIndex(), Offset),
2354 MemOps.push_back(Store);
2358 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2359 // Now store the XMM (fp + vector) parameter registers.
2360 SmallVector<SDValue, 11> SaveXMMOps;
2361 SaveXMMOps.push_back(Chain);
2363 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2364 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2365 SaveXMMOps.push_back(ALVal);
2367 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2368 FuncInfo->getRegSaveFrameIndex()));
2369 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2370 FuncInfo->getVarArgsFPOffset()));
2372 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2373 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2374 &X86::VR128RegClass);
2375 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2376 SaveXMMOps.push_back(Val);
2378 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2380 &SaveXMMOps[0], SaveXMMOps.size()));
2383 if (!MemOps.empty())
2384 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2385 &MemOps[0], MemOps.size());
2389 // Some CCs need callee pop.
2390 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2391 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2392 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2394 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2395 // If this is an sret function, the return should pop the hidden pointer.
2396 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2397 argsAreStructReturn(Ins) == StackStructReturn)
2398 FuncInfo->setBytesToPopOnReturn(4);
2402 // RegSaveFrameIndex is X86-64 only.
2403 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2404 if (CallConv == CallingConv::X86_FastCall ||
2405 CallConv == CallingConv::X86_ThisCall)
2406 // fastcc functions can't have varargs.
2407 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2410 FuncInfo->setArgumentStackSize(StackSize);
2416 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2417 SDValue StackPtr, SDValue Arg,
2418 SDLoc dl, SelectionDAG &DAG,
2419 const CCValAssign &VA,
2420 ISD::ArgFlagsTy Flags) const {
2421 unsigned LocMemOffset = VA.getLocMemOffset();
2422 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2423 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2424 if (Flags.isByVal())
2425 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2427 return DAG.getStore(Chain, dl, Arg, PtrOff,
2428 MachinePointerInfo::getStack(LocMemOffset),
2432 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2433 /// optimization is performed and it is required.
2435 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2436 SDValue &OutRetAddr, SDValue Chain,
2437 bool IsTailCall, bool Is64Bit,
2438 int FPDiff, SDLoc dl) const {
2439 // Adjust the Return address stack slot.
2440 EVT VT = getPointerTy();
2441 OutRetAddr = getReturnAddressFrameIndex(DAG);
2443 // Load the "old" Return address.
2444 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2445 false, false, false, 0);
2446 return SDValue(OutRetAddr.getNode(), 1);
2449 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2450 /// optimization is performed and it is required (FPDiff!=0).
2452 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2453 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2454 unsigned SlotSize, int FPDiff, SDLoc dl) {
2455 // Store the return address to the appropriate stack slot.
2456 if (!FPDiff) return Chain;
2457 // Calculate the new stack slot for the return address.
2458 int NewReturnAddrFI =
2459 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2461 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2462 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2463 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2469 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2470 SmallVectorImpl<SDValue> &InVals) const {
2471 SelectionDAG &DAG = CLI.DAG;
2473 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2474 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2475 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2476 SDValue Chain = CLI.Chain;
2477 SDValue Callee = CLI.Callee;
2478 CallingConv::ID CallConv = CLI.CallConv;
2479 bool &isTailCall = CLI.IsTailCall;
2480 bool isVarArg = CLI.IsVarArg;
2482 MachineFunction &MF = DAG.getMachineFunction();
2483 bool Is64Bit = Subtarget->is64Bit();
2484 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2485 bool IsWindows = Subtarget->isTargetWindows();
2486 StructReturnType SR = callIsStructReturn(Outs);
2487 bool IsSibcall = false;
2489 if (MF.getTarget().Options.DisableTailCalls)
2493 // Check if it's really possible to do a tail call.
2494 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2495 isVarArg, SR != NotStructReturn,
2496 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2497 Outs, OutVals, Ins, DAG);
2499 // Sibcalls are automatically detected tailcalls which do not require
2501 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2508 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509 "Var args not supported with calling convention fastcc, ghc or hipe");
2511 // Analyze operands of the call, assigning locations to each operand.
2512 SmallVector<CCValAssign, 16> ArgLocs;
2513 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2514 ArgLocs, *DAG.getContext());
2516 // Allocate shadow area for Win64
2518 CCInfo.AllocateStack(32, 8);
2520 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2522 // Get a count of how many bytes are to be pushed on the stack.
2523 unsigned NumBytes = CCInfo.getNextStackOffset();
2525 // This is a sibcall. The memory operands are available in caller's
2526 // own caller's stack.
2528 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2529 IsTailCallConvention(CallConv))
2530 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2533 if (isTailCall && !IsSibcall) {
2534 // Lower arguments at fp - stackoffset + fpdiff.
2535 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2536 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2538 FPDiff = NumBytesCallerPushed - NumBytes;
2540 // Set the delta of movement of the returnaddr stackslot.
2541 // But only set if delta is greater than previous delta.
2542 if (FPDiff < X86Info->getTCReturnAddrDelta())
2543 X86Info->setTCReturnAddrDelta(FPDiff);
2547 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2550 SDValue RetAddrFrIdx;
2551 // Load return address for tail calls.
2552 if (isTailCall && FPDiff)
2553 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2554 Is64Bit, FPDiff, dl);
2556 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2557 SmallVector<SDValue, 8> MemOpChains;
2560 // Walk the register/memloc assignments, inserting copies/loads. In the case
2561 // of tail call optimization arguments are handle later.
2562 const X86RegisterInfo *RegInfo =
2563 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2564 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2565 CCValAssign &VA = ArgLocs[i];
2566 EVT RegVT = VA.getLocVT();
2567 SDValue Arg = OutVals[i];
2568 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2569 bool isByVal = Flags.isByVal();
2571 // Promote the value if needed.
2572 switch (VA.getLocInfo()) {
2573 default: llvm_unreachable("Unknown loc info!");
2574 case CCValAssign::Full: break;
2575 case CCValAssign::SExt:
2576 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2578 case CCValAssign::ZExt:
2579 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2581 case CCValAssign::AExt:
2582 if (RegVT.is128BitVector()) {
2583 // Special case: passing MMX values in XMM registers.
2584 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2585 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2586 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2588 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2590 case CCValAssign::BCvt:
2591 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2593 case CCValAssign::Indirect: {
2594 // Store the argument.
2595 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2596 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2597 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2598 MachinePointerInfo::getFixedStack(FI),
2605 if (VA.isRegLoc()) {
2606 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2607 if (isVarArg && IsWin64) {
2608 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2609 // shadow reg if callee is a varargs function.
2610 unsigned ShadowReg = 0;
2611 switch (VA.getLocReg()) {
2612 case X86::XMM0: ShadowReg = X86::RCX; break;
2613 case X86::XMM1: ShadowReg = X86::RDX; break;
2614 case X86::XMM2: ShadowReg = X86::R8; break;
2615 case X86::XMM3: ShadowReg = X86::R9; break;
2618 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2620 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2621 assert(VA.isMemLoc());
2622 if (StackPtr.getNode() == 0)
2623 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2625 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2626 dl, DAG, VA, Flags));
2630 if (!MemOpChains.empty())
2631 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2632 &MemOpChains[0], MemOpChains.size());
2634 if (Subtarget->isPICStyleGOT()) {
2635 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2638 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2639 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2641 // If we are tail calling and generating PIC/GOT style code load the
2642 // address of the callee into ECX. The value in ecx is used as target of
2643 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2644 // for tail calls on PIC/GOT architectures. Normally we would just put the
2645 // address of GOT into ebx and then call target@PLT. But for tail calls
2646 // ebx would be restored (since ebx is callee saved) before jumping to the
2649 // Note: The actual moving to ECX is done further down.
2650 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2651 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2652 !G->getGlobal()->hasProtectedVisibility())
2653 Callee = LowerGlobalAddress(Callee, DAG);
2654 else if (isa<ExternalSymbolSDNode>(Callee))
2655 Callee = LowerExternalSymbol(Callee, DAG);
2659 if (Is64Bit && isVarArg && !IsWin64) {
2660 // From AMD64 ABI document:
2661 // For calls that may call functions that use varargs or stdargs
2662 // (prototype-less calls or calls to functions containing ellipsis (...) in
2663 // the declaration) %al is used as hidden argument to specify the number
2664 // of SSE registers used. The contents of %al do not need to match exactly
2665 // the number of registers, but must be an ubound on the number of SSE
2666 // registers used and is in the range 0 - 8 inclusive.
2668 // Count the number of XMM registers allocated.
2669 static const uint16_t XMMArgRegs[] = {
2670 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2671 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2673 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2674 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2675 && "SSE registers cannot be used when SSE is disabled");
2677 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2678 DAG.getConstant(NumXMMRegs, MVT::i8)));
2681 // For tail calls lower the arguments to the 'real' stack slot.
2683 // Force all the incoming stack arguments to be loaded from the stack
2684 // before any new outgoing arguments are stored to the stack, because the
2685 // outgoing stack slots may alias the incoming argument stack slots, and
2686 // the alias isn't otherwise explicit. This is slightly more conservative
2687 // than necessary, because it means that each store effectively depends
2688 // on every argument instead of just those arguments it would clobber.
2689 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2691 SmallVector<SDValue, 8> MemOpChains2;
2694 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2695 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696 CCValAssign &VA = ArgLocs[i];
2699 assert(VA.isMemLoc());
2700 SDValue Arg = OutVals[i];
2701 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2702 // Create frame index.
2703 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2704 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2705 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2706 FIN = DAG.getFrameIndex(FI, getPointerTy());
2708 if (Flags.isByVal()) {
2709 // Copy relative to framepointer.
2710 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2711 if (StackPtr.getNode() == 0)
2712 StackPtr = DAG.getCopyFromReg(Chain, dl,
2713 RegInfo->getStackRegister(),
2715 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2717 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2721 // Store relative to framepointer.
2722 MemOpChains2.push_back(
2723 DAG.getStore(ArgChain, dl, Arg, FIN,
2724 MachinePointerInfo::getFixedStack(FI),
2730 if (!MemOpChains2.empty())
2731 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2732 &MemOpChains2[0], MemOpChains2.size());
2734 // Store the return address to the appropriate stack slot.
2735 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2736 getPointerTy(), RegInfo->getSlotSize(),
2740 // Build a sequence of copy-to-reg nodes chained together with token chain
2741 // and flag operands which copy the outgoing args into registers.
2743 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2744 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2745 RegsToPass[i].second, InFlag);
2746 InFlag = Chain.getValue(1);
2749 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2750 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2751 // In the 64-bit large code model, we have to make all calls
2752 // through a register, since the call instruction's 32-bit
2753 // pc-relative offset may not be large enough to hold the whole
2755 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2756 // If the callee is a GlobalAddress node (quite common, every direct call
2757 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2760 // We should use extra load for direct calls to dllimported functions in
2762 const GlobalValue *GV = G->getGlobal();
2763 if (!GV->hasDLLImportLinkage()) {
2764 unsigned char OpFlags = 0;
2765 bool ExtraLoad = false;
2766 unsigned WrapperKind = ISD::DELETED_NODE;
2768 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2769 // external symbols most go through the PLT in PIC mode. If the symbol
2770 // has hidden or protected visibility, or if it is static or local, then
2771 // we don't need to use the PLT - we can directly call it.
2772 if (Subtarget->isTargetELF() &&
2773 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2774 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2775 OpFlags = X86II::MO_PLT;
2776 } else if (Subtarget->isPICStyleStubAny() &&
2777 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2778 (!Subtarget->getTargetTriple().isMacOSX() ||
2779 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2780 // PC-relative references to external symbols should go through $stub,
2781 // unless we're building with the leopard linker or later, which
2782 // automatically synthesizes these stubs.
2783 OpFlags = X86II::MO_DARWIN_STUB;
2784 } else if (Subtarget->isPICStyleRIPRel() &&
2785 isa<Function>(GV) &&
2786 cast<Function>(GV)->getAttributes().
2787 hasAttribute(AttributeSet::FunctionIndex,
2788 Attribute::NonLazyBind)) {
2789 // If the function is marked as non-lazy, generate an indirect call
2790 // which loads from the GOT directly. This avoids runtime overhead
2791 // at the cost of eager binding (and one extra byte of encoding).
2792 OpFlags = X86II::MO_GOTPCREL;
2793 WrapperKind = X86ISD::WrapperRIP;
2797 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2798 G->getOffset(), OpFlags);
2800 // Add a wrapper if needed.
2801 if (WrapperKind != ISD::DELETED_NODE)
2802 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2803 // Add extra indirection if needed.
2805 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2806 MachinePointerInfo::getGOT(),
2807 false, false, false, 0);
2809 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2810 unsigned char OpFlags = 0;
2812 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2813 // external symbols should go through the PLT.
2814 if (Subtarget->isTargetELF() &&
2815 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2816 OpFlags = X86II::MO_PLT;
2817 } else if (Subtarget->isPICStyleStubAny() &&
2818 (!Subtarget->getTargetTriple().isMacOSX() ||
2819 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2820 // PC-relative references to external symbols should go through $stub,
2821 // unless we're building with the leopard linker or later, which
2822 // automatically synthesizes these stubs.
2823 OpFlags = X86II::MO_DARWIN_STUB;
2826 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2830 // Returns a chain & a flag for retval copy to use.
2831 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2832 SmallVector<SDValue, 8> Ops;
2834 if (!IsSibcall && isTailCall) {
2835 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2836 DAG.getIntPtrConstant(0, true), InFlag, dl);
2837 InFlag = Chain.getValue(1);
2840 Ops.push_back(Chain);
2841 Ops.push_back(Callee);
2844 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2846 // Add argument registers to the end of the list so that they are known live
2848 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2849 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2850 RegsToPass[i].second.getValueType()));
2852 // Add a register mask operand representing the call-preserved registers.
2853 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2854 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2855 assert(Mask && "Missing call preserved mask for calling convention");
2856 Ops.push_back(DAG.getRegisterMask(Mask));
2858 if (InFlag.getNode())
2859 Ops.push_back(InFlag);
2863 //// If this is the first return lowered for this function, add the regs
2864 //// to the liveout set for the function.
2865 // This isn't right, although it's probably harmless on x86; liveouts
2866 // should be computed from returns not tail calls. Consider a void
2867 // function making a tail call to a function returning int.
2868 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2871 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2872 InFlag = Chain.getValue(1);
2874 // Create the CALLSEQ_END node.
2875 unsigned NumBytesForCalleeToPush;
2876 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2877 getTargetMachine().Options.GuaranteedTailCallOpt))
2878 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2879 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2880 SR == StackStructReturn)
2881 // If this is a call to a struct-return function, the callee
2882 // pops the hidden struct pointer, so we have to push it back.
2883 // This is common for Darwin/X86, Linux & Mingw32 targets.
2884 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2885 NumBytesForCalleeToPush = 4;
2887 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2889 // Returns a flag for retval copy to use.
2891 Chain = DAG.getCALLSEQ_END(Chain,
2892 DAG.getIntPtrConstant(NumBytes, true),
2893 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2896 InFlag = Chain.getValue(1);
2899 // Handle result values, copying them out of physregs into vregs that we
2901 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2902 Ins, dl, DAG, InVals);
2905 //===----------------------------------------------------------------------===//
2906 // Fast Calling Convention (tail call) implementation
2907 //===----------------------------------------------------------------------===//
2909 // Like std call, callee cleans arguments, convention except that ECX is
2910 // reserved for storing the tail called function address. Only 2 registers are
2911 // free for argument passing (inreg). Tail call optimization is performed
2913 // * tailcallopt is enabled
2914 // * caller/callee are fastcc
2915 // On X86_64 architecture with GOT-style position independent code only local
2916 // (within module) calls are supported at the moment.
2917 // To keep the stack aligned according to platform abi the function
2918 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2919 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2920 // If a tail called function callee has more arguments than the caller the
2921 // caller needs to make sure that there is room to move the RETADDR to. This is
2922 // achieved by reserving an area the size of the argument delta right after the
2923 // original REtADDR, but before the saved framepointer or the spilled registers
2924 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2936 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2937 /// for a 16 byte align requirement.
2939 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2940 SelectionDAG& DAG) const {
2941 MachineFunction &MF = DAG.getMachineFunction();
2942 const TargetMachine &TM = MF.getTarget();
2943 const X86RegisterInfo *RegInfo =
2944 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2945 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2946 unsigned StackAlignment = TFI.getStackAlignment();
2947 uint64_t AlignMask = StackAlignment - 1;
2948 int64_t Offset = StackSize;
2949 unsigned SlotSize = RegInfo->getSlotSize();
2950 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2951 // Number smaller than 12 so just add the difference.
2952 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2954 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2955 Offset = ((~AlignMask) & Offset) + StackAlignment +
2956 (StackAlignment-SlotSize);
2961 /// MatchingStackOffset - Return true if the given stack call argument is
2962 /// already available in the same position (relatively) of the caller's
2963 /// incoming argument stack.
2965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2966 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2967 const X86InstrInfo *TII) {
2968 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2970 if (Arg.getOpcode() == ISD::CopyFromReg) {
2971 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2972 if (!TargetRegisterInfo::isVirtualRegister(VR))
2974 MachineInstr *Def = MRI->getVRegDef(VR);
2977 if (!Flags.isByVal()) {
2978 if (!TII->isLoadFromStackSlot(Def, FI))
2981 unsigned Opcode = Def->getOpcode();
2982 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2983 Def->getOperand(1).isFI()) {
2984 FI = Def->getOperand(1).getIndex();
2985 Bytes = Flags.getByValSize();
2989 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2990 if (Flags.isByVal())
2991 // ByVal argument is passed in as a pointer but it's now being
2992 // dereferenced. e.g.
2993 // define @foo(%struct.X* %A) {
2994 // tail call @bar(%struct.X* byval %A)
2997 SDValue Ptr = Ld->getBasePtr();
2998 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3001 FI = FINode->getIndex();
3002 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3003 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3004 FI = FINode->getIndex();
3005 Bytes = Flags.getByValSize();
3009 assert(FI != INT_MAX);
3010 if (!MFI->isFixedObjectIndex(FI))
3012 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3015 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3016 /// for tail call optimization. Targets which want to do tail call
3017 /// optimization should implement this function.
3019 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3020 CallingConv::ID CalleeCC,
3022 bool isCalleeStructRet,
3023 bool isCallerStructRet,
3025 const SmallVectorImpl<ISD::OutputArg> &Outs,
3026 const SmallVectorImpl<SDValue> &OutVals,
3027 const SmallVectorImpl<ISD::InputArg> &Ins,
3028 SelectionDAG &DAG) const {
3029 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3032 // If -tailcallopt is specified, make fastcc functions tail-callable.
3033 const MachineFunction &MF = DAG.getMachineFunction();
3034 const Function *CallerF = MF.getFunction();
3036 // If the function return type is x86_fp80 and the callee return type is not,
3037 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3038 // perform a tailcall optimization here.
3039 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3042 CallingConv::ID CallerCC = CallerF->getCallingConv();
3043 bool CCMatch = CallerCC == CalleeCC;
3044 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3045 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3047 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3048 if (IsTailCallConvention(CalleeCC) && CCMatch)
3053 // Look for obvious safe cases to perform tail call optimization that do not
3054 // require ABI changes. This is what gcc calls sibcall.
3056 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3057 // emit a special epilogue.
3058 const X86RegisterInfo *RegInfo =
3059 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3060 if (RegInfo->needsStackRealignment(MF))
3063 // Also avoid sibcall optimization if either caller or callee uses struct
3064 // return semantics.
3065 if (isCalleeStructRet || isCallerStructRet)
3068 // An stdcall caller is expected to clean up its arguments; the callee
3069 // isn't going to do that.
3070 if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3073 // Do not sibcall optimize vararg calls unless all arguments are passed via
3075 if (isVarArg && !Outs.empty()) {
3077 // Optimizing for varargs on Win64 is unlikely to be safe without
3078 // additional testing.
3079 if (IsCalleeWin64 || IsCallerWin64)
3082 SmallVector<CCValAssign, 16> ArgLocs;
3083 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3084 getTargetMachine(), ArgLocs, *DAG.getContext());
3086 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3087 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3088 if (!ArgLocs[i].isRegLoc())
3092 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3093 // stack. Therefore, if it's not used by the call it is not safe to optimize
3094 // this into a sibcall.
3095 bool Unused = false;
3096 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3103 SmallVector<CCValAssign, 16> RVLocs;
3104 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3105 getTargetMachine(), RVLocs, *DAG.getContext());
3106 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3107 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3108 CCValAssign &VA = RVLocs[i];
3109 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3114 // If the calling conventions do not match, then we'd better make sure the
3115 // results are returned in the same way as what the caller expects.
3117 SmallVector<CCValAssign, 16> RVLocs1;
3118 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3119 getTargetMachine(), RVLocs1, *DAG.getContext());
3120 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3122 SmallVector<CCValAssign, 16> RVLocs2;
3123 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3124 getTargetMachine(), RVLocs2, *DAG.getContext());
3125 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3127 if (RVLocs1.size() != RVLocs2.size())
3129 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3130 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3132 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3134 if (RVLocs1[i].isRegLoc()) {
3135 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3138 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3144 // If the callee takes no arguments then go on to check the results of the
3146 if (!Outs.empty()) {
3147 // Check if stack adjustment is needed. For now, do not do this if any
3148 // argument is passed on the stack.
3149 SmallVector<CCValAssign, 16> ArgLocs;
3150 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151 getTargetMachine(), ArgLocs, *DAG.getContext());
3153 // Allocate shadow area for Win64
3155 CCInfo.AllocateStack(32, 8);
3157 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3158 if (CCInfo.getNextStackOffset()) {
3159 MachineFunction &MF = DAG.getMachineFunction();
3160 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3163 // Check if the arguments are already laid out in the right way as
3164 // the caller's fixed stack objects.
3165 MachineFrameInfo *MFI = MF.getFrameInfo();
3166 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3167 const X86InstrInfo *TII =
3168 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3169 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3170 CCValAssign &VA = ArgLocs[i];
3171 SDValue Arg = OutVals[i];
3172 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3173 if (VA.getLocInfo() == CCValAssign::Indirect)
3175 if (!VA.isRegLoc()) {
3176 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3183 // If the tailcall address may be in a register, then make sure it's
3184 // possible to register allocate for it. In 32-bit, the call address can
3185 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3186 // callee-saved registers are restored. These happen to be the same
3187 // registers used to pass 'inreg' arguments so watch out for those.
3188 if (!Subtarget->is64Bit() &&
3189 ((!isa<GlobalAddressSDNode>(Callee) &&
3190 !isa<ExternalSymbolSDNode>(Callee)) ||
3191 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3192 unsigned NumInRegs = 0;
3193 // In PIC we need an extra register to formulate the address computation
3195 unsigned MaxInRegs =
3196 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3198 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199 CCValAssign &VA = ArgLocs[i];
3202 unsigned Reg = VA.getLocReg();
3205 case X86::EAX: case X86::EDX: case X86::ECX:
3206 if (++NumInRegs == MaxInRegs)
3218 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3219 const TargetLibraryInfo *libInfo) const {
3220 return X86::createFastISel(funcInfo, libInfo);
3223 //===----------------------------------------------------------------------===//
3224 // Other Lowering Hooks
3225 //===----------------------------------------------------------------------===//
3227 static bool MayFoldLoad(SDValue Op) {
3228 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3231 static bool MayFoldIntoStore(SDValue Op) {
3232 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3235 static bool isTargetShuffle(unsigned Opcode) {
3237 default: return false;
3238 case X86ISD::PSHUFD:
3239 case X86ISD::PSHUFHW:
3240 case X86ISD::PSHUFLW:
3242 case X86ISD::PALIGNR:
3243 case X86ISD::MOVLHPS:
3244 case X86ISD::MOVLHPD:
3245 case X86ISD::MOVHLPS:
3246 case X86ISD::MOVLPS:
3247 case X86ISD::MOVLPD:
3248 case X86ISD::MOVSHDUP:
3249 case X86ISD::MOVSLDUP:
3250 case X86ISD::MOVDDUP:
3253 case X86ISD::UNPCKL:
3254 case X86ISD::UNPCKH:
3255 case X86ISD::VPERMILP:
3256 case X86ISD::VPERM2X128:
3257 case X86ISD::VPERMI:
3262 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3263 SDValue V1, SelectionDAG &DAG) {
3265 default: llvm_unreachable("Unknown x86 shuffle node");
3266 case X86ISD::MOVSHDUP:
3267 case X86ISD::MOVSLDUP:
3268 case X86ISD::MOVDDUP:
3269 return DAG.getNode(Opc, dl, VT, V1);
3273 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3274 SDValue V1, unsigned TargetMask,
3275 SelectionDAG &DAG) {
3277 default: llvm_unreachable("Unknown x86 shuffle node");
3278 case X86ISD::PSHUFD:
3279 case X86ISD::PSHUFHW:
3280 case X86ISD::PSHUFLW:
3281 case X86ISD::VPERMILP:
3282 case X86ISD::VPERMI:
3283 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3287 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3288 SDValue V1, SDValue V2, unsigned TargetMask,
3289 SelectionDAG &DAG) {
3291 default: llvm_unreachable("Unknown x86 shuffle node");
3292 case X86ISD::PALIGNR:
3294 case X86ISD::VPERM2X128:
3295 return DAG.getNode(Opc, dl, VT, V1, V2,
3296 DAG.getConstant(TargetMask, MVT::i8));
3300 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3301 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3303 default: llvm_unreachable("Unknown x86 shuffle node");
3304 case X86ISD::MOVLHPS:
3305 case X86ISD::MOVLHPD:
3306 case X86ISD::MOVHLPS:
3307 case X86ISD::MOVLPS:
3308 case X86ISD::MOVLPD:
3311 case X86ISD::UNPCKL:
3312 case X86ISD::UNPCKH:
3313 return DAG.getNode(Opc, dl, VT, V1, V2);
3317 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3318 MachineFunction &MF = DAG.getMachineFunction();
3319 const X86RegisterInfo *RegInfo =
3320 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3321 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3322 int ReturnAddrIndex = FuncInfo->getRAIndex();
3324 if (ReturnAddrIndex == 0) {
3325 // Set up a frame object for the return address.
3326 unsigned SlotSize = RegInfo->getSlotSize();
3327 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3330 FuncInfo->setRAIndex(ReturnAddrIndex);
3333 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3336 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3337 bool hasSymbolicDisplacement) {
3338 // Offset should fit into 32 bit immediate field.
3339 if (!isInt<32>(Offset))
3342 // If we don't have a symbolic displacement - we don't have any extra
3344 if (!hasSymbolicDisplacement)
3347 // FIXME: Some tweaks might be needed for medium code model.
3348 if (M != CodeModel::Small && M != CodeModel::Kernel)
3351 // For small code model we assume that latest object is 16MB before end of 31
3352 // bits boundary. We may also accept pretty large negative constants knowing
3353 // that all objects are in the positive half of address space.
3354 if (M == CodeModel::Small && Offset < 16*1024*1024)
3357 // For kernel code model we know that all object resist in the negative half
3358 // of 32bits address space. We may not accept negative offsets, since they may
3359 // be just off and we may accept pretty large positive ones.
3360 if (M == CodeModel::Kernel && Offset > 0)
3366 /// isCalleePop - Determines whether the callee is required to pop its
3367 /// own arguments. Callee pop is necessary to support tail calls.
3368 bool X86::isCalleePop(CallingConv::ID CallingConv,
3369 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3373 switch (CallingConv) {
3376 case CallingConv::X86_StdCall:
3378 case CallingConv::X86_FastCall:
3380 case CallingConv::X86_ThisCall:
3382 case CallingConv::Fast:
3384 case CallingConv::GHC:
3386 case CallingConv::HiPE:
3391 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3392 /// specific condition code, returning the condition code and the LHS/RHS of the
3393 /// comparison to make.
3394 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3395 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3397 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3398 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3399 // X > -1 -> X == 0, jump !sign.
3400 RHS = DAG.getConstant(0, RHS.getValueType());
3401 return X86::COND_NS;
3403 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3404 // X < 0 -> X == 0, jump on sign.
3407 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3409 RHS = DAG.getConstant(0, RHS.getValueType());
3410 return X86::COND_LE;
3414 switch (SetCCOpcode) {
3415 default: llvm_unreachable("Invalid integer condition!");
3416 case ISD::SETEQ: return X86::COND_E;
3417 case ISD::SETGT: return X86::COND_G;
3418 case ISD::SETGE: return X86::COND_GE;
3419 case ISD::SETLT: return X86::COND_L;
3420 case ISD::SETLE: return X86::COND_LE;
3421 case ISD::SETNE: return X86::COND_NE;
3422 case ISD::SETULT: return X86::COND_B;
3423 case ISD::SETUGT: return X86::COND_A;
3424 case ISD::SETULE: return X86::COND_BE;
3425 case ISD::SETUGE: return X86::COND_AE;
3429 // First determine if it is required or is profitable to flip the operands.
3431 // If LHS is a foldable load, but RHS is not, flip the condition.
3432 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3433 !ISD::isNON_EXTLoad(RHS.getNode())) {
3434 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3435 std::swap(LHS, RHS);
3438 switch (SetCCOpcode) {
3444 std::swap(LHS, RHS);
3448 // On a floating point condition, the flags are set as follows:
3450 // 0 | 0 | 0 | X > Y
3451 // 0 | 0 | 1 | X < Y
3452 // 1 | 0 | 0 | X == Y
3453 // 1 | 1 | 1 | unordered
3454 switch (SetCCOpcode) {
3455 default: llvm_unreachable("Condcode should be pre-legalized away");
3457 case ISD::SETEQ: return X86::COND_E;
3458 case ISD::SETOLT: // flipped
3460 case ISD::SETGT: return X86::COND_A;
3461 case ISD::SETOLE: // flipped
3463 case ISD::SETGE: return X86::COND_AE;
3464 case ISD::SETUGT: // flipped
3466 case ISD::SETLT: return X86::COND_B;
3467 case ISD::SETUGE: // flipped
3469 case ISD::SETLE: return X86::COND_BE;
3471 case ISD::SETNE: return X86::COND_NE;
3472 case ISD::SETUO: return X86::COND_P;
3473 case ISD::SETO: return X86::COND_NP;
3475 case ISD::SETUNE: return X86::COND_INVALID;
3479 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3480 /// code. Current x86 isa includes the following FP cmov instructions:
3481 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3482 static bool hasFPCMov(unsigned X86CC) {
3498 /// isFPImmLegal - Returns true if the target can instruction select the
3499 /// specified FP immediate natively. If false, the legalizer will
3500 /// materialize the FP immediate as a load from a constant pool.
3501 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3502 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3503 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3509 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3510 /// the specified range (L, H].
3511 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3512 return (Val < 0) || (Val >= Low && Val < Hi);
3515 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3516 /// specified value.
3517 static bool isUndefOrEqual(int Val, int CmpVal) {
3518 return (Val < 0 || Val == CmpVal);
3521 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3522 /// from position Pos and ending in Pos+Size, falls within the specified
3523 /// sequential range (L, L+Pos]. or is undef.
3524 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3525 unsigned Pos, unsigned Size, int Low) {
3526 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3527 if (!isUndefOrEqual(Mask[i], Low))
3532 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3533 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3534 /// the second operand.
3535 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3536 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3537 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3538 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3539 return (Mask[0] < 2 && Mask[1] < 2);
3543 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3544 /// is suitable for input to PSHUFHW.
3545 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3546 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3549 // Lower quadword copied in order or undef.
3550 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3553 // Upper quadword shuffled.
3554 for (unsigned i = 4; i != 8; ++i)
3555 if (!isUndefOrInRange(Mask[i], 4, 8))
3558 if (VT == MVT::v16i16) {
3559 // Lower quadword copied in order or undef.
3560 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3563 // Upper quadword shuffled.
3564 for (unsigned i = 12; i != 16; ++i)
3565 if (!isUndefOrInRange(Mask[i], 12, 16))
3572 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3573 /// is suitable for input to PSHUFLW.
3574 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3575 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3578 // Upper quadword copied in order.
3579 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3582 // Lower quadword shuffled.
3583 for (unsigned i = 0; i != 4; ++i)
3584 if (!isUndefOrInRange(Mask[i], 0, 4))
3587 if (VT == MVT::v16i16) {
3588 // Upper quadword copied in order.
3589 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3592 // Lower quadword shuffled.
3593 for (unsigned i = 8; i != 12; ++i)
3594 if (!isUndefOrInRange(Mask[i], 8, 12))
3601 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PALIGNR.
3603 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3604 const X86Subtarget *Subtarget) {
3605 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3606 (VT.is256BitVector() && !Subtarget->hasInt256()))
3609 unsigned NumElts = VT.getVectorNumElements();
3610 unsigned NumLanes = VT.getSizeInBits()/128;
3611 unsigned NumLaneElts = NumElts/NumLanes;
3613 // Do not handle 64-bit element shuffles with palignr.
3614 if (NumLaneElts == 2)
3617 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3619 for (i = 0; i != NumLaneElts; ++i) {
3624 // Lane is all undef, go to next lane
3625 if (i == NumLaneElts)
3628 int Start = Mask[i+l];
3630 // Make sure its in this lane in one of the sources
3631 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3632 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3635 // If not lane 0, then we must match lane 0
3636 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3639 // Correct second source to be contiguous with first source
3640 if (Start >= (int)NumElts)
3641 Start -= NumElts - NumLaneElts;
3643 // Make sure we're shifting in the right direction.
3644 if (Start <= (int)(i+l))
3649 // Check the rest of the elements to see if they are consecutive.
3650 for (++i; i != NumLaneElts; ++i) {
3651 int Idx = Mask[i+l];
3653 // Make sure its in this lane
3654 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3655 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3658 // If not lane 0, then we must match lane 0
3659 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3662 if (Idx >= (int)NumElts)
3663 Idx -= NumElts - NumLaneElts;
3665 if (!isUndefOrEqual(Idx, Start+i))
3674 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3675 /// the two vector operands have swapped position.
3676 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3677 unsigned NumElems) {
3678 for (unsigned i = 0; i != NumElems; ++i) {
3682 else if (idx < (int)NumElems)
3683 Mask[i] = idx + NumElems;
3685 Mask[i] = idx - NumElems;
3689 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3690 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3691 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3692 /// reverse of what x86 shuffles want.
3693 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool HasFp256,
3694 bool Commuted = false) {
3695 if (!HasFp256 && VT.is256BitVector())
3698 unsigned NumElems = VT.getVectorNumElements();
3699 unsigned NumLanes = VT.getSizeInBits()/128;
3700 unsigned NumLaneElems = NumElems/NumLanes;
3702 if (NumLaneElems != 2 && NumLaneElems != 4)
3705 // VSHUFPSY divides the resulting vector into 4 chunks.
3706 // The sources are also splitted into 4 chunks, and each destination
3707 // chunk must come from a different source chunk.
3709 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3710 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3712 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3713 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3715 // VSHUFPDY divides the resulting vector into 4 chunks.
3716 // The sources are also splitted into 4 chunks, and each destination
3717 // chunk must come from a different source chunk.
3719 // SRC1 => X3 X2 X1 X0
3720 // SRC2 => Y3 Y2 Y1 Y0
3722 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3724 unsigned HalfLaneElems = NumLaneElems/2;
3725 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3726 for (unsigned i = 0; i != NumLaneElems; ++i) {
3727 int Idx = Mask[i+l];
3728 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3729 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3731 // For VSHUFPSY, the mask of the second half must be the same as the
3732 // first but with the appropriate offsets. This works in the same way as
3733 // VPERMILPS works with masks.
3734 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3736 if (!isUndefOrEqual(Idx, Mask[i]+l))
3744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3746 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3747 if (!VT.is128BitVector())
3750 unsigned NumElems = VT.getVectorNumElements();
3755 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3756 return isUndefOrEqual(Mask[0], 6) &&
3757 isUndefOrEqual(Mask[1], 7) &&
3758 isUndefOrEqual(Mask[2], 2) &&
3759 isUndefOrEqual(Mask[3], 3);
3762 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3763 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3765 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3766 if (!VT.is128BitVector())
3769 unsigned NumElems = VT.getVectorNumElements();
3774 return isUndefOrEqual(Mask[0], 2) &&
3775 isUndefOrEqual(Mask[1], 3) &&
3776 isUndefOrEqual(Mask[2], 2) &&
3777 isUndefOrEqual(Mask[3], 3);
3780 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3782 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3783 if (!VT.is128BitVector())
3786 unsigned NumElems = VT.getVectorNumElements();
3788 if (NumElems != 2 && NumElems != 4)
3791 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3792 if (!isUndefOrEqual(Mask[i], i + NumElems))
3795 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3796 if (!isUndefOrEqual(Mask[i], i))
3802 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3803 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3804 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3805 if (!VT.is128BitVector())
3808 unsigned NumElems = VT.getVectorNumElements();
3810 if (NumElems != 2 && NumElems != 4)
3813 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3814 if (!isUndefOrEqual(Mask[i], i))
3817 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3818 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3825 // Some special combinations that can be optimized.
3828 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3829 SelectionDAG &DAG) {
3830 MVT VT = SVOp->getSimpleValueType(0);
3833 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3836 ArrayRef<int> Mask = SVOp->getMask();
3838 // These are the special masks that may be optimized.
3839 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3840 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3841 bool MatchEvenMask = true;
3842 bool MatchOddMask = true;
3843 for (int i=0; i<8; ++i) {
3844 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3845 MatchEvenMask = false;
3846 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3847 MatchOddMask = false;
3850 if (!MatchEvenMask && !MatchOddMask)
3853 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3855 SDValue Op0 = SVOp->getOperand(0);
3856 SDValue Op1 = SVOp->getOperand(1);
3858 if (MatchEvenMask) {
3859 // Shift the second operand right to 32 bits.
3860 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3861 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3863 // Shift the first operand left to 32 bits.
3864 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3865 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3867 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3868 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3871 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3873 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3874 bool HasInt256, bool V2IsSplat = false) {
3876 if (VT.is512BitVector())
3878 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3879 "Unsupported vector type for unpckh");
3881 unsigned NumElts = VT.getVectorNumElements();
3882 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3883 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3886 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3887 // independently on 128-bit lanes.
3888 unsigned NumLanes = VT.getSizeInBits()/128;
3889 unsigned NumLaneElts = NumElts/NumLanes;
3891 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3892 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3893 int BitI = Mask[l+i];
3894 int BitI1 = Mask[l+i+1];
3895 if (!isUndefOrEqual(BitI, j))
3898 if (!isUndefOrEqual(BitI1, NumElts))
3901 if (!isUndefOrEqual(BitI1, j + NumElts))
3910 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3912 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3913 bool HasInt256, bool V2IsSplat = false) {
3914 unsigned NumElts = VT.getVectorNumElements();
3916 if (VT.is512BitVector())
3918 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3919 "Unsupported vector type for unpckh");
3921 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3922 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3925 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3926 // independently on 128-bit lanes.
3927 unsigned NumLanes = VT.getSizeInBits()/128;
3928 unsigned NumLaneElts = NumElts/NumLanes;
3930 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3931 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
3932 int BitI = Mask[l+i];
3933 int BitI1 = Mask[l+i+1];
3934 if (!isUndefOrEqual(BitI, j))
3937 if (isUndefOrEqual(BitI1, NumElts))
3940 if (!isUndefOrEqual(BitI1, j+NumElts))
3948 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3949 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3951 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3952 unsigned NumElts = VT.getVectorNumElements();
3953 bool Is256BitVec = VT.is256BitVector();
3955 if (VT.is512BitVector())
3957 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3958 "Unsupported vector type for unpckh");
3960 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3961 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3964 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3965 // FIXME: Need a better way to get rid of this, there's no latency difference
3966 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3967 // the former later. We should also remove the "_undef" special mask.
3968 if (NumElts == 4 && Is256BitVec)
3971 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3972 // independently on 128-bit lanes.
3973 unsigned NumLanes = VT.getSizeInBits()/128;
3974 unsigned NumLaneElts = NumElts/NumLanes;
3976 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3977 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3978 int BitI = Mask[l+i];
3979 int BitI1 = Mask[l+i+1];
3981 if (!isUndefOrEqual(BitI, j))
3983 if (!isUndefOrEqual(BitI1, j))
3991 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3992 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3994 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3995 unsigned NumElts = VT.getVectorNumElements();
3997 if (VT.is512BitVector())
4000 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4001 "Unsupported vector type for unpckh");
4003 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4004 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4007 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4008 // independently on 128-bit lanes.
4009 unsigned NumLanes = VT.getSizeInBits()/128;
4010 unsigned NumLaneElts = NumElts/NumLanes;
4012 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4013 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4014 int BitI = Mask[l+i];
4015 int BitI1 = Mask[l+i+1];
4016 if (!isUndefOrEqual(BitI, j))
4018 if (!isUndefOrEqual(BitI1, j))
4025 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4026 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4027 /// MOVSD, and MOVD, i.e. setting the lowest element.
4028 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4029 if (VT.getVectorElementType().getSizeInBits() < 32)
4031 if (!VT.is128BitVector())
4034 unsigned NumElts = VT.getVectorNumElements();
4036 if (!isUndefOrEqual(Mask[0], NumElts))
4039 for (unsigned i = 1; i != NumElts; ++i)
4040 if (!isUndefOrEqual(Mask[i], i))
4046 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4047 /// as permutations between 128-bit chunks or halves. As an example: this
4049 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4050 /// The first half comes from the second half of V1 and the second half from the
4051 /// the second half of V2.
4052 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4053 if (!HasFp256 || !VT.is256BitVector())
4056 // The shuffle result is divided into half A and half B. In total the two
4057 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4058 // B must come from C, D, E or F.
4059 unsigned HalfSize = VT.getVectorNumElements()/2;
4060 bool MatchA = false, MatchB = false;
4062 // Check if A comes from one of C, D, E, F.
4063 for (unsigned Half = 0; Half != 4; ++Half) {
4064 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4070 // Check if B comes from one of C, D, E, F.
4071 for (unsigned Half = 0; Half != 4; ++Half) {
4072 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4078 return MatchA && MatchB;
4081 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4083 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4084 MVT VT = SVOp->getSimpleValueType(0);
4086 unsigned HalfSize = VT.getVectorNumElements()/2;
4088 unsigned FstHalf = 0, SndHalf = 0;
4089 for (unsigned i = 0; i < HalfSize; ++i) {
4090 if (SVOp->getMaskElt(i) > 0) {
4091 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4095 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4096 if (SVOp->getMaskElt(i) > 0) {
4097 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4102 return (FstHalf | (SndHalf << 4));
4105 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4106 static bool isPermImmMask(ArrayRef<int> Mask, EVT VT, unsigned& Imm8) {
4107 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4111 unsigned NumElts = VT.getVectorNumElements();
4113 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4114 for (unsigned i = 0; i != NumElts; ++i) {
4117 Imm8 |= Mask[i] << (i*2);
4122 unsigned LaneSize = 4;
4123 SmallVector<int, 4> MaskVal(LaneSize, -1);
4125 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4126 for (unsigned i = 0; i != LaneSize; ++i) {
4127 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4131 if (MaskVal[i] < 0) {
4132 MaskVal[i] = Mask[i+l] - l;
4133 Imm8 |= MaskVal[i] << (i*2);
4136 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4143 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4144 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4145 /// Note that VPERMIL mask matching is different depending whether theunderlying
4146 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4147 /// to the same elements of the low, but to the higher half of the source.
4148 /// In VPERMILPD the two lanes could be shuffled independently of each other
4149 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4150 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4154 unsigned NumElts = VT.getVectorNumElements();
4155 // Only match 256-bit with 32/64-bit types
4156 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4159 unsigned NumLanes = VT.getSizeInBits()/128;
4160 unsigned LaneSize = NumElts/NumLanes;
4161 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4162 for (unsigned i = 0; i != LaneSize; ++i) {
4163 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4165 if (NumElts != 8 || l == 0)
4167 // VPERMILPS handling
4170 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4178 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4179 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4180 /// element of vector 2 and the other elements to come from vector 1 in order.
4181 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4182 bool V2IsSplat = false, bool V2IsUndef = false) {
4183 if (!VT.is128BitVector())
4186 unsigned NumOps = VT.getVectorNumElements();
4187 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4190 if (!isUndefOrEqual(Mask[0], 0))
4193 for (unsigned i = 1; i != NumOps; ++i)
4194 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4195 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4196 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4202 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4203 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4204 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4205 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4206 const X86Subtarget *Subtarget) {
4207 if (!Subtarget->hasSSE3())
4210 unsigned NumElems = VT.getVectorNumElements();
4212 if ((VT.is128BitVector() && NumElems != 4) ||
4213 (VT.is256BitVector() && NumElems != 8) ||
4214 (VT.is512BitVector() && NumElems != 16))
4217 // "i+1" is the value the indexed mask element must have
4218 for (unsigned i = 0; i != NumElems; i += 2)
4219 if (!isUndefOrEqual(Mask[i], i+1) ||
4220 !isUndefOrEqual(Mask[i+1], i+1))
4226 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4227 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4228 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4229 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4230 const X86Subtarget *Subtarget) {
4231 if (!Subtarget->hasSSE3())
4234 unsigned NumElems = VT.getVectorNumElements();
4236 if ((VT.is128BitVector() && NumElems != 4) ||
4237 (VT.is256BitVector() && NumElems != 8) ||
4238 (VT.is512BitVector() && NumElems != 16))
4241 // "i" is the value the indexed mask element must have
4242 for (unsigned i = 0; i != NumElems; i += 2)
4243 if (!isUndefOrEqual(Mask[i], i) ||
4244 !isUndefOrEqual(Mask[i+1], i))
4250 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4251 /// specifies a shuffle of elements that is suitable for input to 256-bit
4252 /// version of MOVDDUP.
4253 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4254 if (!HasFp256 || !VT.is256BitVector())
4257 unsigned NumElts = VT.getVectorNumElements();
4261 for (unsigned i = 0; i != NumElts/2; ++i)
4262 if (!isUndefOrEqual(Mask[i], 0))
4264 for (unsigned i = NumElts/2; i != NumElts; ++i)
4265 if (!isUndefOrEqual(Mask[i], NumElts/2))
4270 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4271 /// specifies a shuffle of elements that is suitable for input to 128-bit
4272 /// version of MOVDDUP.
4273 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4274 if (!VT.is128BitVector())
4277 unsigned e = VT.getVectorNumElements() / 2;
4278 for (unsigned i = 0; i != e; ++i)
4279 if (!isUndefOrEqual(Mask[i], i))
4281 for (unsigned i = 0; i != e; ++i)
4282 if (!isUndefOrEqual(Mask[e+i], i))
4287 /// isVEXTRACTIndex - Return true if the specified
4288 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4289 /// suitable for instruction that extract 128 or 256 bit vectors
4290 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4291 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4292 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4295 // The index should be aligned on a vecWidth-bit boundary.
4297 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4299 MVT VT = N->getSimpleValueType(0);
4300 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4301 bool Result = (Index * ElSize) % vecWidth == 0;
4306 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4307 /// operand specifies a subvector insert that is suitable for input to
4308 /// insertion of 128 or 256-bit subvectors
4309 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4310 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4311 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4313 // The index should be aligned on a vecWidth-bit boundary.
4315 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4317 MVT VT = N->getSimpleValueType(0);
4318 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4319 bool Result = (Index * ElSize) % vecWidth == 0;
4324 bool X86::isVINSERT128Index(SDNode *N) {
4325 return isVINSERTIndex(N, 128);
4328 bool X86::isVINSERT256Index(SDNode *N) {
4329 return isVINSERTIndex(N, 256);
4332 bool X86::isVEXTRACT128Index(SDNode *N) {
4333 return isVEXTRACTIndex(N, 128);
4336 bool X86::isVEXTRACT256Index(SDNode *N) {
4337 return isVEXTRACTIndex(N, 256);
4340 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4341 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4342 /// Handles 128-bit and 256-bit.
4343 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4344 MVT VT = N->getSimpleValueType(0);
4346 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4347 "Unsupported vector type for PSHUF/SHUFP");
4349 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4350 // independently on 128-bit lanes.
4351 unsigned NumElts = VT.getVectorNumElements();
4352 unsigned NumLanes = VT.getSizeInBits()/128;
4353 unsigned NumLaneElts = NumElts/NumLanes;
4355 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4356 "Only supports 2 or 4 elements per lane");
4358 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4360 for (unsigned i = 0; i != NumElts; ++i) {
4361 int Elt = N->getMaskElt(i);
4362 if (Elt < 0) continue;
4363 Elt &= NumLaneElts - 1;
4364 unsigned ShAmt = (i << Shift) % 8;
4365 Mask |= Elt << ShAmt;
4371 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4372 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4373 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4374 MVT VT = N->getSimpleValueType(0);
4376 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4377 "Unsupported vector type for PSHUFHW");
4379 unsigned NumElts = VT.getVectorNumElements();
4382 for (unsigned l = 0; l != NumElts; l += 8) {
4383 // 8 nodes per lane, but we only care about the last 4.
4384 for (unsigned i = 0; i < 4; ++i) {
4385 int Elt = N->getMaskElt(l+i+4);
4386 if (Elt < 0) continue;
4387 Elt &= 0x3; // only 2-bits.
4388 Mask |= Elt << (i * 2);
4395 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4396 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4397 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4398 MVT VT = N->getSimpleValueType(0);
4400 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4401 "Unsupported vector type for PSHUFHW");
4403 unsigned NumElts = VT.getVectorNumElements();
4406 for (unsigned l = 0; l != NumElts; l += 8) {
4407 // 8 nodes per lane, but we only care about the first 4.
4408 for (unsigned i = 0; i < 4; ++i) {
4409 int Elt = N->getMaskElt(l+i);
4410 if (Elt < 0) continue;
4411 Elt &= 0x3; // only 2-bits
4412 Mask |= Elt << (i * 2);
4419 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4420 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4421 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4422 MVT VT = SVOp->getSimpleValueType(0);
4423 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4425 unsigned NumElts = VT.getVectorNumElements();
4426 unsigned NumLanes = VT.getSizeInBits()/128;
4427 unsigned NumLaneElts = NumElts/NumLanes;
4431 for (i = 0; i != NumElts; ++i) {
4432 Val = SVOp->getMaskElt(i);
4436 if (Val >= (int)NumElts)
4437 Val -= NumElts - NumLaneElts;
4439 assert(Val - i > 0 && "PALIGNR imm should be positive");
4440 return (Val - i) * EltSize;
4443 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4444 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4445 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4446 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4449 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4451 MVT VecVT = N->getOperand(0).getSimpleValueType();
4452 MVT ElVT = VecVT.getVectorElementType();
4454 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4455 return Index / NumElemsPerChunk;
4458 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4459 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4460 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4461 llvm_unreachable("Illegal insert subvector for VINSERT");
4464 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4466 MVT VecVT = N->getSimpleValueType(0);
4467 MVT ElVT = VecVT.getVectorElementType();
4469 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4470 return Index / NumElemsPerChunk;
4473 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4474 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4475 /// and VINSERTI128 instructions.
4476 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4477 return getExtractVEXTRACTImmediate(N, 128);
4480 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4481 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4482 /// and VINSERTI64x4 instructions.
4483 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4484 return getExtractVEXTRACTImmediate(N, 256);
4487 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4488 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4489 /// and VINSERTI128 instructions.
4490 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4491 return getInsertVINSERTImmediate(N, 128);
4494 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4495 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4496 /// and VINSERTI64x4 instructions.
4497 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4498 return getInsertVINSERTImmediate(N, 256);
4501 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4503 bool X86::isZeroNode(SDValue Elt) {
4504 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4505 return CN->isNullValue();
4506 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4507 return CFP->getValueAPF().isPosZero();
4511 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4512 /// their permute mask.
4513 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4514 SelectionDAG &DAG) {
4515 MVT VT = SVOp->getSimpleValueType(0);
4516 unsigned NumElems = VT.getVectorNumElements();
4517 SmallVector<int, 8> MaskVec;
4519 for (unsigned i = 0; i != NumElems; ++i) {
4520 int Idx = SVOp->getMaskElt(i);
4522 if (Idx < (int)NumElems)
4527 MaskVec.push_back(Idx);
4529 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4530 SVOp->getOperand(0), &MaskVec[0]);
4533 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4534 /// match movhlps. The lower half elements should come from upper half of
4535 /// V1 (and in order), and the upper half elements should come from the upper
4536 /// half of V2 (and in order).
4537 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4538 if (!VT.is128BitVector())
4540 if (VT.getVectorNumElements() != 4)
4542 for (unsigned i = 0, e = 2; i != e; ++i)
4543 if (!isUndefOrEqual(Mask[i], i+2))
4545 for (unsigned i = 2; i != 4; ++i)
4546 if (!isUndefOrEqual(Mask[i], i+4))
4551 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4552 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4554 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4555 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4557 N = N->getOperand(0).getNode();
4558 if (!ISD::isNON_EXTLoad(N))
4561 *LD = cast<LoadSDNode>(N);
4565 // Test whether the given value is a vector value which will be legalized
4567 static bool WillBeConstantPoolLoad(SDNode *N) {
4568 if (N->getOpcode() != ISD::BUILD_VECTOR)
4571 // Check for any non-constant elements.
4572 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4573 switch (N->getOperand(i).getNode()->getOpcode()) {
4575 case ISD::ConstantFP:
4582 // Vectors of all-zeros and all-ones are materialized with special
4583 // instructions rather than being loaded.
4584 return !ISD::isBuildVectorAllZeros(N) &&
4585 !ISD::isBuildVectorAllOnes(N);
4588 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4589 /// match movlp{s|d}. The lower half elements should come from lower half of
4590 /// V1 (and in order), and the upper half elements should come from the upper
4591 /// half of V2 (and in order). And since V1 will become the source of the
4592 /// MOVLP, it must be either a vector load or a scalar load to vector.
4593 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4594 ArrayRef<int> Mask, MVT VT) {
4595 if (!VT.is128BitVector())
4598 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4600 // Is V2 is a vector load, don't do this transformation. We will try to use
4601 // load folding shufps op.
4602 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4605 unsigned NumElems = VT.getVectorNumElements();
4607 if (NumElems != 2 && NumElems != 4)
4609 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4610 if (!isUndefOrEqual(Mask[i], i))
4612 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4613 if (!isUndefOrEqual(Mask[i], i+NumElems))
4618 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4620 static bool isSplatVector(SDNode *N) {
4621 if (N->getOpcode() != ISD::BUILD_VECTOR)
4624 SDValue SplatValue = N->getOperand(0);
4625 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4626 if (N->getOperand(i) != SplatValue)
4631 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4632 /// to an zero vector.
4633 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4634 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4635 SDValue V1 = N->getOperand(0);
4636 SDValue V2 = N->getOperand(1);
4637 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4638 for (unsigned i = 0; i != NumElems; ++i) {
4639 int Idx = N->getMaskElt(i);
4640 if (Idx >= (int)NumElems) {
4641 unsigned Opc = V2.getOpcode();
4642 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4644 if (Opc != ISD::BUILD_VECTOR ||
4645 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4647 } else if (Idx >= 0) {
4648 unsigned Opc = V1.getOpcode();
4649 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4651 if (Opc != ISD::BUILD_VECTOR ||
4652 !X86::isZeroNode(V1.getOperand(Idx)))
4659 /// getZeroVector - Returns a vector of specified type with all zero elements.
4661 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4662 SelectionDAG &DAG, SDLoc dl) {
4663 assert(VT.isVector() && "Expected a vector type");
4665 // Always build SSE zero vectors as <4 x i32> bitcasted
4666 // to their dest type. This ensures they get CSE'd.
4668 if (VT.is128BitVector()) { // SSE
4669 if (Subtarget->hasSSE2()) { // SSE2
4670 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4671 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4673 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4674 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4676 } else if (VT.is256BitVector()) { // AVX
4677 if (Subtarget->hasInt256()) { // AVX2
4678 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4679 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4680 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4681 array_lengthof(Ops));
4683 // 256-bit logic and arithmetic instructions in AVX are all
4684 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4685 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4686 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4687 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4688 array_lengthof(Ops));
4691 llvm_unreachable("Unexpected vector type");
4693 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4696 /// getOnesVector - Returns a vector of specified type with all bits set.
4697 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4698 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4699 /// Then bitcast to their original type, ensuring they get CSE'd.
4700 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4702 assert(VT.isVector() && "Expected a vector type");
4704 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4706 if (VT.is256BitVector()) {
4707 if (HasInt256) { // AVX2
4708 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4709 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4710 array_lengthof(Ops));
4712 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4713 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4715 } else if (VT.is128BitVector()) {
4716 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4718 llvm_unreachable("Unexpected vector type");
4720 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4723 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4724 /// that point to V2 points to its first element.
4725 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4726 for (unsigned i = 0; i != NumElems; ++i) {
4727 if (Mask[i] > (int)NumElems) {
4733 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4734 /// operation of specified width.
4735 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4737 unsigned NumElems = VT.getVectorNumElements();
4738 SmallVector<int, 8> Mask;
4739 Mask.push_back(NumElems);
4740 for (unsigned i = 1; i != NumElems; ++i)
4742 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4745 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4746 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4748 unsigned NumElems = VT.getVectorNumElements();
4749 SmallVector<int, 8> Mask;
4750 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4752 Mask.push_back(i + NumElems);
4754 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4757 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4758 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4760 unsigned NumElems = VT.getVectorNumElements();
4761 SmallVector<int, 8> Mask;
4762 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4763 Mask.push_back(i + Half);
4764 Mask.push_back(i + NumElems + Half);
4766 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4769 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4770 // a generic shuffle instruction because the target has no such instructions.
4771 // Generate shuffles which repeat i16 and i8 several times until they can be
4772 // represented by v4f32 and then be manipulated by target suported shuffles.
4773 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4774 EVT VT = V.getValueType();
4775 int NumElems = VT.getVectorNumElements();
4778 while (NumElems > 4) {
4779 if (EltNo < NumElems/2) {
4780 V = getUnpackl(DAG, dl, VT, V, V);
4782 V = getUnpackh(DAG, dl, VT, V, V);
4783 EltNo -= NumElems/2;
4790 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4791 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4792 MVT VT = V.getSimpleValueType();
4795 if (VT.is128BitVector()) {
4796 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4797 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4798 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4800 } else if (VT.is256BitVector()) {
4801 // To use VPERMILPS to splat scalars, the second half of indicies must
4802 // refer to the higher part, which is a duplication of the lower one,
4803 // because VPERMILPS can only handle in-lane permutations.
4804 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4805 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4807 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4808 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4811 llvm_unreachable("Vector size not supported");
4813 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4816 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4817 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4818 MVT SrcVT = SV->getSimpleValueType(0);
4819 SDValue V1 = SV->getOperand(0);
4822 int EltNo = SV->getSplatIndex();
4823 int NumElems = SrcVT.getVectorNumElements();
4824 bool Is256BitVec = SrcVT.is256BitVector();
4826 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4827 "Unknown how to promote splat for type");
4829 // Extract the 128-bit part containing the splat element and update
4830 // the splat element index when it refers to the higher register.
4832 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4833 if (EltNo >= NumElems/2)
4834 EltNo -= NumElems/2;
4837 // All i16 and i8 vector types can't be used directly by a generic shuffle
4838 // instruction because the target has no such instruction. Generate shuffles
4839 // which repeat i16 and i8 several times until they fit in i32, and then can
4840 // be manipulated by target suported shuffles.
4841 MVT EltVT = SrcVT.getVectorElementType();
4842 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4843 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4845 // Recreate the 256-bit vector and place the same 128-bit vector
4846 // into the low and high part. This is necessary because we want
4847 // to use VPERM* to shuffle the vectors
4849 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4852 return getLegalSplat(DAG, V1, EltNo);
4855 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4856 /// vector of zero or undef vector. This produces a shuffle where the low
4857 /// element of V2 is swizzled into the zero/undef vector, landing at element
4858 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4859 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4861 const X86Subtarget *Subtarget,
4862 SelectionDAG &DAG) {
4863 MVT VT = V2.getSimpleValueType();
4865 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4866 unsigned NumElems = VT.getVectorNumElements();
4867 SmallVector<int, 16> MaskVec;
4868 for (unsigned i = 0; i != NumElems; ++i)
4869 // If this is the insertion idx, put the low elt of V2 here.
4870 MaskVec.push_back(i == Idx ? NumElems : i);
4871 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4874 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4875 /// target specific opcode. Returns true if the Mask could be calculated.
4876 /// Sets IsUnary to true if only uses one source.
4877 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4878 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4879 unsigned NumElems = VT.getVectorNumElements();
4883 switch(N->getOpcode()) {
4885 ImmN = N->getOperand(N->getNumOperands()-1);
4886 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4888 case X86ISD::UNPCKH:
4889 DecodeUNPCKHMask(VT, Mask);
4891 case X86ISD::UNPCKL:
4892 DecodeUNPCKLMask(VT, Mask);
4894 case X86ISD::MOVHLPS:
4895 DecodeMOVHLPSMask(NumElems, Mask);
4897 case X86ISD::MOVLHPS:
4898 DecodeMOVLHPSMask(NumElems, Mask);
4900 case X86ISD::PALIGNR:
4901 ImmN = N->getOperand(N->getNumOperands()-1);
4902 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4904 case X86ISD::PSHUFD:
4905 case X86ISD::VPERMILP:
4906 ImmN = N->getOperand(N->getNumOperands()-1);
4907 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4910 case X86ISD::PSHUFHW:
4911 ImmN = N->getOperand(N->getNumOperands()-1);
4912 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4915 case X86ISD::PSHUFLW:
4916 ImmN = N->getOperand(N->getNumOperands()-1);
4917 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4920 case X86ISD::VPERMI:
4921 ImmN = N->getOperand(N->getNumOperands()-1);
4922 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4926 case X86ISD::MOVSD: {
4927 // The index 0 always comes from the first element of the second source,
4928 // this is why MOVSS and MOVSD are used in the first place. The other
4929 // elements come from the other positions of the first source vector
4930 Mask.push_back(NumElems);
4931 for (unsigned i = 1; i != NumElems; ++i) {
4936 case X86ISD::VPERM2X128:
4937 ImmN = N->getOperand(N->getNumOperands()-1);
4938 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4939 if (Mask.empty()) return false;
4941 case X86ISD::MOVDDUP:
4942 case X86ISD::MOVLHPD:
4943 case X86ISD::MOVLPD:
4944 case X86ISD::MOVLPS:
4945 case X86ISD::MOVSHDUP:
4946 case X86ISD::MOVSLDUP:
4947 // Not yet implemented
4949 default: llvm_unreachable("unknown target shuffle node");
4955 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4956 /// element of the result of the vector shuffle.
4957 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4960 return SDValue(); // Limit search depth.
4962 SDValue V = SDValue(N, 0);
4963 EVT VT = V.getValueType();
4964 unsigned Opcode = V.getOpcode();
4966 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4967 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4968 int Elt = SV->getMaskElt(Index);
4971 return DAG.getUNDEF(VT.getVectorElementType());
4973 unsigned NumElems = VT.getVectorNumElements();
4974 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4975 : SV->getOperand(1);
4976 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4979 // Recurse into target specific vector shuffles to find scalars.
4980 if (isTargetShuffle(Opcode)) {
4981 MVT ShufVT = V.getSimpleValueType();
4982 unsigned NumElems = ShufVT.getVectorNumElements();
4983 SmallVector<int, 16> ShuffleMask;
4986 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4989 int Elt = ShuffleMask[Index];
4991 return DAG.getUNDEF(ShufVT.getVectorElementType());
4993 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4995 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4999 // Actual nodes that may contain scalar elements
5000 if (Opcode == ISD::BITCAST) {
5001 V = V.getOperand(0);
5002 EVT SrcVT = V.getValueType();
5003 unsigned NumElems = VT.getVectorNumElements();
5005 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5009 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5010 return (Index == 0) ? V.getOperand(0)
5011 : DAG.getUNDEF(VT.getVectorElementType());
5013 if (V.getOpcode() == ISD::BUILD_VECTOR)
5014 return V.getOperand(Index);
5019 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5020 /// shuffle operation which come from a consecutively from a zero. The
5021 /// search can start in two different directions, from left or right.
5022 /// We count undefs as zeros until PreferredNum is reached.
5023 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5024 unsigned NumElems, bool ZerosFromLeft,
5026 unsigned PreferredNum = -1U) {
5027 unsigned NumZeros = 0;
5028 for (unsigned i = 0; i != NumElems; ++i) {
5029 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5030 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5034 if (X86::isZeroNode(Elt))
5036 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5037 NumZeros = std::min(NumZeros + 1, PreferredNum);
5045 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5046 /// correspond consecutively to elements from one of the vector operands,
5047 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5049 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5050 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5051 unsigned NumElems, unsigned &OpNum) {
5052 bool SeenV1 = false;
5053 bool SeenV2 = false;
5055 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5056 int Idx = SVOp->getMaskElt(i);
5057 // Ignore undef indicies
5061 if (Idx < (int)NumElems)
5066 // Only accept consecutive elements from the same vector
5067 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5071 OpNum = SeenV1 ? 0 : 1;
5075 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5076 /// logical left shift of a vector.
5077 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5078 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5080 SVOp->getSimpleValueType(0).getVectorNumElements();
5081 unsigned NumZeros = getNumOfConsecutiveZeros(
5082 SVOp, NumElems, false /* check zeros from right */, DAG,
5083 SVOp->getMaskElt(0));
5089 // Considering the elements in the mask that are not consecutive zeros,
5090 // check if they consecutively come from only one of the source vectors.
5092 // V1 = {X, A, B, C} 0
5094 // vector_shuffle V1, V2 <1, 2, 3, X>
5096 if (!isShuffleMaskConsecutive(SVOp,
5097 0, // Mask Start Index
5098 NumElems-NumZeros, // Mask End Index(exclusive)
5099 NumZeros, // Where to start looking in the src vector
5100 NumElems, // Number of elements in vector
5101 OpSrc)) // Which source operand ?
5106 ShVal = SVOp->getOperand(OpSrc);
5110 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5111 /// logical left shift of a vector.
5112 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5113 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5115 SVOp->getSimpleValueType(0).getVectorNumElements();
5116 unsigned NumZeros = getNumOfConsecutiveZeros(
5117 SVOp, NumElems, true /* check zeros from left */, DAG,
5118 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5124 // Considering the elements in the mask that are not consecutive zeros,
5125 // check if they consecutively come from only one of the source vectors.
5127 // 0 { A, B, X, X } = V2
5129 // vector_shuffle V1, V2 <X, X, 4, 5>
5131 if (!isShuffleMaskConsecutive(SVOp,
5132 NumZeros, // Mask Start Index
5133 NumElems, // Mask End Index(exclusive)
5134 0, // Where to start looking in the src vector
5135 NumElems, // Number of elements in vector
5136 OpSrc)) // Which source operand ?
5141 ShVal = SVOp->getOperand(OpSrc);
5145 /// isVectorShift - Returns true if the shuffle can be implemented as a
5146 /// logical left or right shift of a vector.
5147 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5148 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5149 // Although the logic below support any bitwidth size, there are no
5150 // shift instructions which handle more than 128-bit vectors.
5151 if (!SVOp->getSimpleValueType(0).is128BitVector())
5154 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5155 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5161 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5163 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5164 unsigned NumNonZero, unsigned NumZero,
5166 const X86Subtarget* Subtarget,
5167 const TargetLowering &TLI) {
5174 for (unsigned i = 0; i < 16; ++i) {
5175 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5176 if (ThisIsNonZero && First) {
5178 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5180 V = DAG.getUNDEF(MVT::v8i16);
5185 SDValue ThisElt(0, 0), LastElt(0, 0);
5186 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5187 if (LastIsNonZero) {
5188 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5189 MVT::i16, Op.getOperand(i-1));
5191 if (ThisIsNonZero) {
5192 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5193 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5194 ThisElt, DAG.getConstant(8, MVT::i8));
5196 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5200 if (ThisElt.getNode())
5201 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5202 DAG.getIntPtrConstant(i/2));
5206 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5209 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5211 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5212 unsigned NumNonZero, unsigned NumZero,
5214 const X86Subtarget* Subtarget,
5215 const TargetLowering &TLI) {
5222 for (unsigned i = 0; i < 8; ++i) {
5223 bool isNonZero = (NonZeros & (1 << i)) != 0;
5227 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5229 V = DAG.getUNDEF(MVT::v8i16);
5232 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5233 MVT::v8i16, V, Op.getOperand(i),
5234 DAG.getIntPtrConstant(i));
5241 /// getVShift - Return a vector logical shift node.
5243 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5244 unsigned NumBits, SelectionDAG &DAG,
5245 const TargetLowering &TLI, SDLoc dl) {
5246 assert(VT.is128BitVector() && "Unknown type for VShift");
5247 EVT ShVT = MVT::v2i64;
5248 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5249 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5250 return DAG.getNode(ISD::BITCAST, dl, VT,
5251 DAG.getNode(Opc, dl, ShVT, SrcOp,
5252 DAG.getConstant(NumBits,
5253 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5257 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5258 SelectionDAG &DAG) const {
5260 // Check if the scalar load can be widened into a vector load. And if
5261 // the address is "base + cst" see if the cst can be "absorbed" into
5262 // the shuffle mask.
5263 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5264 SDValue Ptr = LD->getBasePtr();
5265 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5267 EVT PVT = LD->getValueType(0);
5268 if (PVT != MVT::i32 && PVT != MVT::f32)
5273 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5274 FI = FINode->getIndex();
5276 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5277 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5278 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5279 Offset = Ptr.getConstantOperandVal(1);
5280 Ptr = Ptr.getOperand(0);
5285 // FIXME: 256-bit vector instructions don't require a strict alignment,
5286 // improve this code to support it better.
5287 unsigned RequiredAlign = VT.getSizeInBits()/8;
5288 SDValue Chain = LD->getChain();
5289 // Make sure the stack object alignment is at least 16 or 32.
5290 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5291 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5292 if (MFI->isFixedObjectIndex(FI)) {
5293 // Can't change the alignment. FIXME: It's possible to compute
5294 // the exact stack offset and reference FI + adjust offset instead.
5295 // If someone *really* cares about this. That's the way to implement it.
5298 MFI->setObjectAlignment(FI, RequiredAlign);
5302 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5303 // Ptr + (Offset & ~15).
5306 if ((Offset % RequiredAlign) & 3)
5308 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5310 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5311 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5313 int EltNo = (Offset - StartOffset) >> 2;
5314 unsigned NumElems = VT.getVectorNumElements();
5316 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5317 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5318 LD->getPointerInfo().getWithOffset(StartOffset),
5319 false, false, false, 0);
5321 SmallVector<int, 8> Mask;
5322 for (unsigned i = 0; i != NumElems; ++i)
5323 Mask.push_back(EltNo);
5325 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5331 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5332 /// vector of type 'VT', see if the elements can be replaced by a single large
5333 /// load which has the same value as a build_vector whose operands are 'elts'.
5335 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5337 /// FIXME: we'd also like to handle the case where the last elements are zero
5338 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5339 /// There's even a handy isZeroNode for that purpose.
5340 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5341 SDLoc &DL, SelectionDAG &DAG) {
5342 EVT EltVT = VT.getVectorElementType();
5343 unsigned NumElems = Elts.size();
5345 LoadSDNode *LDBase = NULL;
5346 unsigned LastLoadedElt = -1U;
5348 // For each element in the initializer, see if we've found a load or an undef.
5349 // If we don't find an initial load element, or later load elements are
5350 // non-consecutive, bail out.
5351 for (unsigned i = 0; i < NumElems; ++i) {
5352 SDValue Elt = Elts[i];
5354 if (!Elt.getNode() ||
5355 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5358 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5360 LDBase = cast<LoadSDNode>(Elt.getNode());
5364 if (Elt.getOpcode() == ISD::UNDEF)
5367 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5368 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5373 // If we have found an entire vector of loads and undefs, then return a large
5374 // load of the entire vector width starting at the base pointer. If we found
5375 // consecutive loads for the low half, generate a vzext_load node.
5376 if (LastLoadedElt == NumElems - 1) {
5377 SDValue NewLd = SDValue();
5378 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5379 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5380 LDBase->getPointerInfo(),
5381 LDBase->isVolatile(), LDBase->isNonTemporal(),
5382 LDBase->isInvariant(), 0);
5383 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5384 LDBase->getPointerInfo(),
5385 LDBase->isVolatile(), LDBase->isNonTemporal(),
5386 LDBase->isInvariant(), LDBase->getAlignment());
5388 if (LDBase->hasAnyUseOfValue(1)) {
5389 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5391 SDValue(NewLd.getNode(), 1));
5392 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5393 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5394 SDValue(NewLd.getNode(), 1));
5399 if (NumElems == 4 && LastLoadedElt == 1 &&
5400 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5401 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5402 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5404 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5405 array_lengthof(Ops), MVT::i64,
5406 LDBase->getPointerInfo(),
5407 LDBase->getAlignment(),
5408 false/*isVolatile*/, true/*ReadMem*/,
5411 // Make sure the newly-created LOAD is in the same position as LDBase in
5412 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5413 // update uses of LDBase's output chain to use the TokenFactor.
5414 if (LDBase->hasAnyUseOfValue(1)) {
5415 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5416 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5417 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5418 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5419 SDValue(ResNode.getNode(), 1));
5422 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5427 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5428 /// to generate a splat value for the following cases:
5429 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5430 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5431 /// a scalar load, or a constant.
5432 /// The VBROADCAST node is returned when a pattern is found,
5433 /// or SDValue() otherwise.
5434 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5435 SelectionDAG &DAG) {
5436 if (!Subtarget->hasFp256())
5439 MVT VT = Op.getSimpleValueType();
5442 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5443 "Unsupported vector type for broadcast.");
5448 switch (Op.getOpcode()) {
5450 // Unknown pattern found.
5453 case ISD::BUILD_VECTOR: {
5454 // The BUILD_VECTOR node must be a splat.
5455 if (!isSplatVector(Op.getNode()))
5458 Ld = Op.getOperand(0);
5459 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5460 Ld.getOpcode() == ISD::ConstantFP);
5462 // The suspected load node has several users. Make sure that all
5463 // of its users are from the BUILD_VECTOR node.
5464 // Constants may have multiple users.
5465 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5470 case ISD::VECTOR_SHUFFLE: {
5471 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5473 // Shuffles must have a splat mask where the first element is
5475 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5478 SDValue Sc = Op.getOperand(0);
5479 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5480 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5482 if (!Subtarget->hasInt256())
5485 // Use the register form of the broadcast instruction available on AVX2.
5486 if (VT.getSizeInBits() >= 256)
5487 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5488 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5491 Ld = Sc.getOperand(0);
5492 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5493 Ld.getOpcode() == ISD::ConstantFP);
5495 // The scalar_to_vector node and the suspected
5496 // load node must have exactly one user.
5497 // Constants may have multiple users.
5499 // AVX-512 has register version of the broadcast
5500 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5501 Ld.getValueType().getSizeInBits() >= 32;
5502 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5509 bool IsGE256 = (VT.getSizeInBits() >= 256);
5511 // Handle the broadcasting a single constant scalar from the constant pool
5512 // into a vector. On Sandybridge it is still better to load a constant vector
5513 // from the constant pool and not to broadcast it from a scalar.
5514 if (ConstSplatVal && Subtarget->hasInt256()) {
5515 EVT CVT = Ld.getValueType();
5516 assert(!CVT.isVector() && "Must not broadcast a vector type");
5517 unsigned ScalarSize = CVT.getSizeInBits();
5519 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5520 const Constant *C = 0;
5521 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5522 C = CI->getConstantIntValue();
5523 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5524 C = CF->getConstantFPValue();
5526 assert(C && "Invalid constant type");
5528 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5529 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5530 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5531 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5532 MachinePointerInfo::getConstantPool(),
5533 false, false, false, Alignment);
5535 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5539 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5540 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5542 // Handle AVX2 in-register broadcasts.
5543 if (!IsLoad && Subtarget->hasInt256() &&
5544 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5545 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5547 // The scalar source must be a normal load.
5551 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5552 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5554 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5555 // double since there is no vbroadcastsd xmm
5556 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5557 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5558 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5561 // Unsupported broadcast.
5565 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5566 MVT VT = Op.getSimpleValueType();
5568 // Skip if insert_vec_elt is not supported.
5569 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5570 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5574 unsigned NumElems = Op.getNumOperands();
5578 SmallVector<unsigned, 4> InsertIndices;
5579 SmallVector<int, 8> Mask(NumElems, -1);
5581 for (unsigned i = 0; i != NumElems; ++i) {
5582 unsigned Opc = Op.getOperand(i).getOpcode();
5584 if (Opc == ISD::UNDEF)
5587 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5588 // Quit if more than 1 elements need inserting.
5589 if (InsertIndices.size() > 1)
5592 InsertIndices.push_back(i);
5596 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5597 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5599 // Quit if extracted from vector of different type.
5600 if (ExtractedFromVec.getValueType() != VT)
5603 // Quit if non-constant index.
5604 if (!isa<ConstantSDNode>(ExtIdx))
5607 if (VecIn1.getNode() == 0)
5608 VecIn1 = ExtractedFromVec;
5609 else if (VecIn1 != ExtractedFromVec) {
5610 if (VecIn2.getNode() == 0)
5611 VecIn2 = ExtractedFromVec;
5612 else if (VecIn2 != ExtractedFromVec)
5613 // Quit if more than 2 vectors to shuffle
5617 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5619 if (ExtractedFromVec == VecIn1)
5621 else if (ExtractedFromVec == VecIn2)
5622 Mask[i] = Idx + NumElems;
5625 if (VecIn1.getNode() == 0)
5628 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5629 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5630 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5631 unsigned Idx = InsertIndices[i];
5632 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5633 DAG.getIntPtrConstant(Idx));
5639 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5641 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5643 MVT VT = Op.getSimpleValueType();
5644 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5645 "Unexpected type in LowerBUILD_VECTORvXi1!");
5648 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5649 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5650 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5651 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5652 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5653 Ops, VT.getVectorNumElements());
5656 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5657 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5658 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5659 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5660 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5661 Ops, VT.getVectorNumElements());
5664 bool AllContants = true;
5665 uint64_t Immediate = 0;
5666 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5667 SDValue In = Op.getOperand(idx);
5668 if (In.getOpcode() == ISD::UNDEF)
5670 if (!isa<ConstantSDNode>(In)) {
5671 AllContants = false;
5674 if (cast<ConstantSDNode>(In)->getZExtValue())
5675 Immediate |= (1ULL << idx);
5679 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5680 DAG.getConstant(Immediate, MVT::i16));
5681 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5682 DAG.getIntPtrConstant(0));
5685 if (!isSplatVector(Op.getNode()))
5686 llvm_unreachable("Unsupported predicate operation");
5688 SDValue In = Op.getOperand(0);
5689 SDValue EFLAGS, X86CC;
5690 if (In.getOpcode() == ISD::SETCC) {
5691 SDValue Op0 = In.getOperand(0);
5692 SDValue Op1 = In.getOperand(1);
5693 ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5694 bool isFP = Op1.getValueType().isFloatingPoint();
5695 unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5697 assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5699 X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5700 EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5701 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5702 } else if (In.getOpcode() == X86ISD::SETCC) {
5703 X86CC = In.getOperand(0);
5704 EFLAGS = In.getOperand(1);
5713 // res = allOnes ### CMOVNE -1, %res
5716 MVT InVT = In.getSimpleValueType();
5717 SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5718 EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5719 X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5722 if (VT == MVT::v16i1) {
5723 SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5724 SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5725 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5726 Cst0, Cst1, X86CC, EFLAGS);
5727 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5730 if (VT == MVT::v8i1) {
5731 SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5732 SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5733 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5734 Cst0, Cst1, X86CC, EFLAGS);
5735 CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5736 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5738 llvm_unreachable("Unsupported predicate operation");
5742 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5745 MVT VT = Op.getSimpleValueType();
5746 MVT ExtVT = VT.getVectorElementType();
5747 unsigned NumElems = Op.getNumOperands();
5749 // Generate vectors for predicate vectors.
5750 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5751 return LowerBUILD_VECTORvXi1(Op, DAG);
5753 // Vectors containing all zeros can be matched by pxor and xorps later
5754 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5755 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5756 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5757 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5760 return getZeroVector(VT, Subtarget, DAG, dl);
5763 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5764 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5765 // vpcmpeqd on 256-bit vectors.
5766 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5767 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5770 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5773 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5774 if (Broadcast.getNode())
5777 unsigned EVTBits = ExtVT.getSizeInBits();
5779 unsigned NumZero = 0;
5780 unsigned NumNonZero = 0;
5781 unsigned NonZeros = 0;
5782 bool IsAllConstants = true;
5783 SmallSet<SDValue, 8> Values;
5784 for (unsigned i = 0; i < NumElems; ++i) {
5785 SDValue Elt = Op.getOperand(i);
5786 if (Elt.getOpcode() == ISD::UNDEF)
5789 if (Elt.getOpcode() != ISD::Constant &&
5790 Elt.getOpcode() != ISD::ConstantFP)
5791 IsAllConstants = false;
5792 if (X86::isZeroNode(Elt))
5795 NonZeros |= (1 << i);
5800 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5801 if (NumNonZero == 0)
5802 return DAG.getUNDEF(VT);
5804 // Special case for single non-zero, non-undef, element.
5805 if (NumNonZero == 1) {
5806 unsigned Idx = countTrailingZeros(NonZeros);
5807 SDValue Item = Op.getOperand(Idx);
5809 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5810 // the value are obviously zero, truncate the value to i32 and do the
5811 // insertion that way. Only do this if the value is non-constant or if the
5812 // value is a constant being inserted into element 0. It is cheaper to do
5813 // a constant pool load than it is to do a movd + shuffle.
5814 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5815 (!IsAllConstants || Idx == 0)) {
5816 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5818 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5819 EVT VecVT = MVT::v4i32;
5820 unsigned VecElts = 4;
5822 // Truncate the value (which may itself be a constant) to i32, and
5823 // convert it to a vector with movd (S2V+shuffle to zero extend).
5824 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5825 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5826 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5828 // Now we have our 32-bit value zero extended in the low element of
5829 // a vector. If Idx != 0, swizzle it into place.
5831 SmallVector<int, 4> Mask;
5832 Mask.push_back(Idx);
5833 for (unsigned i = 1; i != VecElts; ++i)
5835 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5838 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5842 // If we have a constant or non-constant insertion into the low element of
5843 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5844 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5845 // depending on what the source datatype is.
5848 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5850 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5851 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5852 if (VT.is256BitVector()) {
5853 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5854 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5855 Item, DAG.getIntPtrConstant(0));
5857 assert(VT.is128BitVector() && "Expected an SSE value type!");
5858 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5859 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5860 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5863 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5864 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5865 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5866 if (VT.is256BitVector()) {
5867 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5868 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5870 assert(VT.is128BitVector() && "Expected an SSE value type!");
5871 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5873 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5877 // Is it a vector logical left shift?
5878 if (NumElems == 2 && Idx == 1 &&
5879 X86::isZeroNode(Op.getOperand(0)) &&
5880 !X86::isZeroNode(Op.getOperand(1))) {
5881 unsigned NumBits = VT.getSizeInBits();
5882 return getVShift(true, VT,
5883 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5884 VT, Op.getOperand(1)),
5885 NumBits/2, DAG, *this, dl);
5888 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5891 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5892 // is a non-constant being inserted into an element other than the low one,
5893 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5894 // movd/movss) to move this into the low element, then shuffle it into
5896 if (EVTBits == 32) {
5897 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5899 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5900 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5901 SmallVector<int, 8> MaskVec;
5902 for (unsigned i = 0; i != NumElems; ++i)
5903 MaskVec.push_back(i == Idx ? 0 : 1);
5904 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5908 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5909 if (Values.size() == 1) {
5910 if (EVTBits == 32) {
5911 // Instead of a shuffle like this:
5912 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5913 // Check if it's possible to issue this instead.
5914 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5915 unsigned Idx = countTrailingZeros(NonZeros);
5916 SDValue Item = Op.getOperand(Idx);
5917 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5918 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5923 // A vector full of immediates; various special cases are already
5924 // handled, so this is best done with a single constant-pool load.
5928 // For AVX-length vectors, build the individual 128-bit pieces and use
5929 // shuffles to put them in place.
5930 if (VT.is256BitVector()) {
5931 SmallVector<SDValue, 32> V;
5932 for (unsigned i = 0; i != NumElems; ++i)
5933 V.push_back(Op.getOperand(i));
5935 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5937 // Build both the lower and upper subvector.
5938 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5939 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5942 // Recreate the wider vector with the lower and upper part.
5943 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5946 // Let legalizer expand 2-wide build_vectors.
5947 if (EVTBits == 64) {
5948 if (NumNonZero == 1) {
5949 // One half is zero or undef.
5950 unsigned Idx = countTrailingZeros(NonZeros);
5951 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5952 Op.getOperand(Idx));
5953 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5958 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5959 if (EVTBits == 8 && NumElems == 16) {
5960 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5962 if (V.getNode()) return V;
5965 if (EVTBits == 16 && NumElems == 8) {
5966 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5968 if (V.getNode()) return V;
5971 // If element VT is == 32 bits, turn it into a number of shuffles.
5972 SmallVector<SDValue, 8> V(NumElems);
5973 if (NumElems == 4 && NumZero > 0) {
5974 for (unsigned i = 0; i < 4; ++i) {
5975 bool isZero = !(NonZeros & (1 << i));
5977 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5979 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5982 for (unsigned i = 0; i < 2; ++i) {
5983 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5986 V[i] = V[i*2]; // Must be a zero vector.
5989 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5992 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5995 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6000 bool Reverse1 = (NonZeros & 0x3) == 2;
6001 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6005 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6006 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6008 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6011 if (Values.size() > 1 && VT.is128BitVector()) {
6012 // Check for a build vector of consecutive loads.
6013 for (unsigned i = 0; i < NumElems; ++i)
6014 V[i] = Op.getOperand(i);
6016 // Check for elements which are consecutive loads.
6017 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
6021 // Check for a build vector from mostly shuffle plus few inserting.
6022 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6026 // For SSE 4.1, use insertps to put the high elements into the low element.
6027 if (getSubtarget()->hasSSE41()) {
6029 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6030 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6032 Result = DAG.getUNDEF(VT);
6034 for (unsigned i = 1; i < NumElems; ++i) {
6035 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6036 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6037 Op.getOperand(i), DAG.getIntPtrConstant(i));
6042 // Otherwise, expand into a number of unpckl*, start by extending each of
6043 // our (non-undef) elements to the full vector width with the element in the
6044 // bottom slot of the vector (which generates no code for SSE).
6045 for (unsigned i = 0; i < NumElems; ++i) {
6046 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6047 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6049 V[i] = DAG.getUNDEF(VT);
6052 // Next, we iteratively mix elements, e.g. for v4f32:
6053 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6054 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6055 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6056 unsigned EltStride = NumElems >> 1;
6057 while (EltStride != 0) {
6058 for (unsigned i = 0; i < EltStride; ++i) {
6059 // If V[i+EltStride] is undef and this is the first round of mixing,
6060 // then it is safe to just drop this shuffle: V[i] is already in the
6061 // right place, the one element (since it's the first round) being
6062 // inserted as undef can be dropped. This isn't safe for successive
6063 // rounds because they will permute elements within both vectors.
6064 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6065 EltStride == NumElems/2)
6068 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6077 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6078 // to create 256-bit vectors from two other 128-bit ones.
6079 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6081 MVT ResVT = Op.getSimpleValueType();
6083 assert((ResVT.is256BitVector() ||
6084 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6086 SDValue V1 = Op.getOperand(0);
6087 SDValue V2 = Op.getOperand(1);
6088 unsigned NumElems = ResVT.getVectorNumElements();
6089 if(ResVT.is256BitVector())
6090 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6092 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6095 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6096 assert(Op.getNumOperands() == 2);
6098 // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
6099 // from two other 128-bit ones.
6100 return LowerAVXCONCAT_VECTORS(Op, DAG);
6103 // Try to lower a shuffle node into a simple blend instruction.
6105 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6106 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6107 SDValue V1 = SVOp->getOperand(0);
6108 SDValue V2 = SVOp->getOperand(1);
6110 MVT VT = SVOp->getSimpleValueType(0);
6111 MVT EltVT = VT.getVectorElementType();
6112 unsigned NumElems = VT.getVectorNumElements();
6114 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6116 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6119 // Check the mask for BLEND and build the value.
6120 unsigned MaskValue = 0;
6121 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6122 unsigned NumLanes = (NumElems-1)/8 + 1;
6123 unsigned NumElemsInLane = NumElems / NumLanes;
6125 // Blend for v16i16 should be symetric for the both lanes.
6126 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6128 int SndLaneEltIdx = (NumLanes == 2) ?
6129 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6130 int EltIdx = SVOp->getMaskElt(i);
6132 if ((EltIdx < 0 || EltIdx == (int)i) &&
6133 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6136 if (((unsigned)EltIdx == (i + NumElems)) &&
6137 (SndLaneEltIdx < 0 ||
6138 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6139 MaskValue |= (1<<i);
6144 // Convert i32 vectors to floating point if it is not AVX2.
6145 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6147 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6148 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6150 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6151 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6154 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6155 DAG.getConstant(MaskValue, MVT::i32));
6156 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6159 // v8i16 shuffles - Prefer shuffles in the following order:
6160 // 1. [all] pshuflw, pshufhw, optional move
6161 // 2. [ssse3] 1 x pshufb
6162 // 3. [ssse3] 2 x pshufb + 1 x por
6163 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6165 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6166 SelectionDAG &DAG) {
6167 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6168 SDValue V1 = SVOp->getOperand(0);
6169 SDValue V2 = SVOp->getOperand(1);
6171 SmallVector<int, 8> MaskVals;
6173 // Determine if more than 1 of the words in each of the low and high quadwords
6174 // of the result come from the same quadword of one of the two inputs. Undef
6175 // mask values count as coming from any quadword, for better codegen.
6176 unsigned LoQuad[] = { 0, 0, 0, 0 };
6177 unsigned HiQuad[] = { 0, 0, 0, 0 };
6178 std::bitset<4> InputQuads;
6179 for (unsigned i = 0; i < 8; ++i) {
6180 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6181 int EltIdx = SVOp->getMaskElt(i);
6182 MaskVals.push_back(EltIdx);
6191 InputQuads.set(EltIdx / 4);
6194 int BestLoQuad = -1;
6195 unsigned MaxQuad = 1;
6196 for (unsigned i = 0; i < 4; ++i) {
6197 if (LoQuad[i] > MaxQuad) {
6199 MaxQuad = LoQuad[i];
6203 int BestHiQuad = -1;
6205 for (unsigned i = 0; i < 4; ++i) {
6206 if (HiQuad[i] > MaxQuad) {
6208 MaxQuad = HiQuad[i];
6212 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6213 // of the two input vectors, shuffle them into one input vector so only a
6214 // single pshufb instruction is necessary. If There are more than 2 input
6215 // quads, disable the next transformation since it does not help SSSE3.
6216 bool V1Used = InputQuads[0] || InputQuads[1];
6217 bool V2Used = InputQuads[2] || InputQuads[3];
6218 if (Subtarget->hasSSSE3()) {
6219 if (InputQuads.count() == 2 && V1Used && V2Used) {
6220 BestLoQuad = InputQuads[0] ? 0 : 1;
6221 BestHiQuad = InputQuads[2] ? 2 : 3;
6223 if (InputQuads.count() > 2) {
6229 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6230 // the shuffle mask. If a quad is scored as -1, that means that it contains
6231 // words from all 4 input quadwords.
6233 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6235 BestLoQuad < 0 ? 0 : BestLoQuad,
6236 BestHiQuad < 0 ? 1 : BestHiQuad
6238 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6239 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6240 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6241 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6243 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6244 // source words for the shuffle, to aid later transformations.
6245 bool AllWordsInNewV = true;
6246 bool InOrder[2] = { true, true };
6247 for (unsigned i = 0; i != 8; ++i) {
6248 int idx = MaskVals[i];
6250 InOrder[i/4] = false;
6251 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6253 AllWordsInNewV = false;
6257 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6258 if (AllWordsInNewV) {
6259 for (int i = 0; i != 8; ++i) {
6260 int idx = MaskVals[i];
6263 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6264 if ((idx != i) && idx < 4)
6266 if ((idx != i) && idx > 3)
6275 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6276 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6277 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6278 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6279 unsigned TargetMask = 0;
6280 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6281 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6282 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6283 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6284 getShufflePSHUFLWImmediate(SVOp);
6285 V1 = NewV.getOperand(0);
6286 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6290 // Promote splats to a larger type which usually leads to more efficient code.
6291 // FIXME: Is this true if pshufb is available?
6292 if (SVOp->isSplat())
6293 return PromoteSplat(SVOp, DAG);
6295 // If we have SSSE3, and all words of the result are from 1 input vector,
6296 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6297 // is present, fall back to case 4.
6298 if (Subtarget->hasSSSE3()) {
6299 SmallVector<SDValue,16> pshufbMask;
6301 // If we have elements from both input vectors, set the high bit of the
6302 // shuffle mask element to zero out elements that come from V2 in the V1
6303 // mask, and elements that come from V1 in the V2 mask, so that the two
6304 // results can be OR'd together.
6305 bool TwoInputs = V1Used && V2Used;
6306 for (unsigned i = 0; i != 8; ++i) {
6307 int EltIdx = MaskVals[i] * 2;
6308 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6309 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6310 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6311 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6313 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6314 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6315 DAG.getNode(ISD::BUILD_VECTOR, dl,
6316 MVT::v16i8, &pshufbMask[0], 16));
6318 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6320 // Calculate the shuffle mask for the second input, shuffle it, and
6321 // OR it with the first shuffled input.
6323 for (unsigned i = 0; i != 8; ++i) {
6324 int EltIdx = MaskVals[i] * 2;
6325 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6326 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6327 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6328 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6330 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6331 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6332 DAG.getNode(ISD::BUILD_VECTOR, dl,
6333 MVT::v16i8, &pshufbMask[0], 16));
6334 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6335 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6338 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6339 // and update MaskVals with new element order.
6340 std::bitset<8> InOrder;
6341 if (BestLoQuad >= 0) {
6342 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6343 for (int i = 0; i != 4; ++i) {
6344 int idx = MaskVals[i];
6347 } else if ((idx / 4) == BestLoQuad) {
6352 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6355 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6356 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6357 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6359 getShufflePSHUFLWImmediate(SVOp), DAG);
6363 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6364 // and update MaskVals with the new element order.
6365 if (BestHiQuad >= 0) {
6366 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6367 for (unsigned i = 4; i != 8; ++i) {
6368 int idx = MaskVals[i];
6371 } else if ((idx / 4) == BestHiQuad) {
6372 MaskV[i] = (idx & 3) + 4;
6376 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6379 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6380 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6381 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6383 getShufflePSHUFHWImmediate(SVOp), DAG);
6387 // In case BestHi & BestLo were both -1, which means each quadword has a word
6388 // from each of the four input quadwords, calculate the InOrder bitvector now
6389 // before falling through to the insert/extract cleanup.
6390 if (BestLoQuad == -1 && BestHiQuad == -1) {
6392 for (int i = 0; i != 8; ++i)
6393 if (MaskVals[i] < 0 || MaskVals[i] == i)
6397 // The other elements are put in the right place using pextrw and pinsrw.
6398 for (unsigned i = 0; i != 8; ++i) {
6401 int EltIdx = MaskVals[i];
6404 SDValue ExtOp = (EltIdx < 8) ?
6405 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6406 DAG.getIntPtrConstant(EltIdx)) :
6407 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6408 DAG.getIntPtrConstant(EltIdx - 8));
6409 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6410 DAG.getIntPtrConstant(i));
6415 // v16i8 shuffles - Prefer shuffles in the following order:
6416 // 1. [ssse3] 1 x pshufb
6417 // 2. [ssse3] 2 x pshufb + 1 x por
6418 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6419 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6420 const X86Subtarget* Subtarget,
6421 SelectionDAG &DAG) {
6422 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6423 SDValue V1 = SVOp->getOperand(0);
6424 SDValue V2 = SVOp->getOperand(1);
6426 ArrayRef<int> MaskVals = SVOp->getMask();
6428 // Promote splats to a larger type which usually leads to more efficient code.
6429 // FIXME: Is this true if pshufb is available?
6430 if (SVOp->isSplat())
6431 return PromoteSplat(SVOp, DAG);
6433 // If we have SSSE3, case 1 is generated when all result bytes come from
6434 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6435 // present, fall back to case 3.
6437 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6438 if (Subtarget->hasSSSE3()) {
6439 SmallVector<SDValue,16> pshufbMask;
6441 // If all result elements are from one input vector, then only translate
6442 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6444 // Otherwise, we have elements from both input vectors, and must zero out
6445 // elements that come from V2 in the first mask, and V1 in the second mask
6446 // so that we can OR them together.
6447 for (unsigned i = 0; i != 16; ++i) {
6448 int EltIdx = MaskVals[i];
6449 if (EltIdx < 0 || EltIdx >= 16)
6451 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6453 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6454 DAG.getNode(ISD::BUILD_VECTOR, dl,
6455 MVT::v16i8, &pshufbMask[0], 16));
6457 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6458 // the 2nd operand if it's undefined or zero.
6459 if (V2.getOpcode() == ISD::UNDEF ||
6460 ISD::isBuildVectorAllZeros(V2.getNode()))
6463 // Calculate the shuffle mask for the second input, shuffle it, and
6464 // OR it with the first shuffled input.
6466 for (unsigned i = 0; i != 16; ++i) {
6467 int EltIdx = MaskVals[i];
6468 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6469 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6471 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6472 DAG.getNode(ISD::BUILD_VECTOR, dl,
6473 MVT::v16i8, &pshufbMask[0], 16));
6474 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6477 // No SSSE3 - Calculate in place words and then fix all out of place words
6478 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6479 // the 16 different words that comprise the two doublequadword input vectors.
6480 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6481 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6483 for (int i = 0; i != 8; ++i) {
6484 int Elt0 = MaskVals[i*2];
6485 int Elt1 = MaskVals[i*2+1];
6487 // This word of the result is all undef, skip it.
6488 if (Elt0 < 0 && Elt1 < 0)
6491 // This word of the result is already in the correct place, skip it.
6492 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6495 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6496 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6499 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6500 // using a single extract together, load it and store it.
6501 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6502 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6503 DAG.getIntPtrConstant(Elt1 / 2));
6504 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6505 DAG.getIntPtrConstant(i));
6509 // If Elt1 is defined, extract it from the appropriate source. If the
6510 // source byte is not also odd, shift the extracted word left 8 bits
6511 // otherwise clear the bottom 8 bits if we need to do an or.
6513 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6514 DAG.getIntPtrConstant(Elt1 / 2));
6515 if ((Elt1 & 1) == 0)
6516 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6518 TLI.getShiftAmountTy(InsElt.getValueType())));
6520 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6521 DAG.getConstant(0xFF00, MVT::i16));
6523 // If Elt0 is defined, extract it from the appropriate source. If the
6524 // source byte is not also even, shift the extracted word right 8 bits. If
6525 // Elt1 was also defined, OR the extracted values together before
6526 // inserting them in the result.
6528 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6529 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6530 if ((Elt0 & 1) != 0)
6531 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6533 TLI.getShiftAmountTy(InsElt0.getValueType())));
6535 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6536 DAG.getConstant(0x00FF, MVT::i16));
6537 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6540 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6541 DAG.getIntPtrConstant(i));
6543 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6546 // v32i8 shuffles - Translate to VPSHUFB if possible.
6548 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6549 const X86Subtarget *Subtarget,
6550 SelectionDAG &DAG) {
6551 MVT VT = SVOp->getSimpleValueType(0);
6552 SDValue V1 = SVOp->getOperand(0);
6553 SDValue V2 = SVOp->getOperand(1);
6555 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6557 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6558 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6559 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6561 // VPSHUFB may be generated if
6562 // (1) one of input vector is undefined or zeroinitializer.
6563 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6564 // And (2) the mask indexes don't cross the 128-bit lane.
6565 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6566 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6569 if (V1IsAllZero && !V2IsAllZero) {
6570 CommuteVectorShuffleMask(MaskVals, 32);
6573 SmallVector<SDValue, 32> pshufbMask;
6574 for (unsigned i = 0; i != 32; i++) {
6575 int EltIdx = MaskVals[i];
6576 if (EltIdx < 0 || EltIdx >= 32)
6579 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6580 // Cross lane is not allowed.
6584 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6586 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6587 DAG.getNode(ISD::BUILD_VECTOR, dl,
6588 MVT::v32i8, &pshufbMask[0], 32));
6591 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6592 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6593 /// done when every pair / quad of shuffle mask elements point to elements in
6594 /// the right sequence. e.g.
6595 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6597 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6598 SelectionDAG &DAG) {
6599 MVT VT = SVOp->getSimpleValueType(0);
6601 unsigned NumElems = VT.getVectorNumElements();
6604 switch (VT.SimpleTy) {
6605 default: llvm_unreachable("Unexpected!");
6606 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6607 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6608 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6609 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6610 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6611 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6614 SmallVector<int, 8> MaskVec;
6615 for (unsigned i = 0; i != NumElems; i += Scale) {
6617 for (unsigned j = 0; j != Scale; ++j) {
6618 int EltIdx = SVOp->getMaskElt(i+j);
6622 StartIdx = (EltIdx / Scale);
6623 if (EltIdx != (int)(StartIdx*Scale + j))
6626 MaskVec.push_back(StartIdx);
6629 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6630 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6631 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6634 /// getVZextMovL - Return a zero-extending vector move low node.
6636 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6637 SDValue SrcOp, SelectionDAG &DAG,
6638 const X86Subtarget *Subtarget, SDLoc dl) {
6639 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6640 LoadSDNode *LD = NULL;
6641 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6642 LD = dyn_cast<LoadSDNode>(SrcOp);
6644 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6646 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6647 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6648 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6649 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6650 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6652 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6653 return DAG.getNode(ISD::BITCAST, dl, VT,
6654 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6655 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6663 return DAG.getNode(ISD::BITCAST, dl, VT,
6664 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6665 DAG.getNode(ISD::BITCAST, dl,
6669 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6670 /// which could not be matched by any known target speficic shuffle
6672 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6674 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6675 if (NewOp.getNode())
6678 MVT VT = SVOp->getSimpleValueType(0);
6680 unsigned NumElems = VT.getVectorNumElements();
6681 unsigned NumLaneElems = NumElems / 2;
6684 MVT EltVT = VT.getVectorElementType();
6685 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6688 SmallVector<int, 16> Mask;
6689 for (unsigned l = 0; l < 2; ++l) {
6690 // Build a shuffle mask for the output, discovering on the fly which
6691 // input vectors to use as shuffle operands (recorded in InputUsed).
6692 // If building a suitable shuffle vector proves too hard, then bail
6693 // out with UseBuildVector set.
6694 bool UseBuildVector = false;
6695 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6696 unsigned LaneStart = l * NumLaneElems;
6697 for (unsigned i = 0; i != NumLaneElems; ++i) {
6698 // The mask element. This indexes into the input.
6699 int Idx = SVOp->getMaskElt(i+LaneStart);
6701 // the mask element does not index into any input vector.
6706 // The input vector this mask element indexes into.
6707 int Input = Idx / NumLaneElems;
6709 // Turn the index into an offset from the start of the input vector.
6710 Idx -= Input * NumLaneElems;
6712 // Find or create a shuffle vector operand to hold this input.
6714 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6715 if (InputUsed[OpNo] == Input)
6716 // This input vector is already an operand.
6718 if (InputUsed[OpNo] < 0) {
6719 // Create a new operand for this input vector.
6720 InputUsed[OpNo] = Input;
6725 if (OpNo >= array_lengthof(InputUsed)) {
6726 // More than two input vectors used! Give up on trying to create a
6727 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6728 UseBuildVector = true;
6732 // Add the mask index for the new shuffle vector.
6733 Mask.push_back(Idx + OpNo * NumLaneElems);
6736 if (UseBuildVector) {
6737 SmallVector<SDValue, 16> SVOps;
6738 for (unsigned i = 0; i != NumLaneElems; ++i) {
6739 // The mask element. This indexes into the input.
6740 int Idx = SVOp->getMaskElt(i+LaneStart);
6742 SVOps.push_back(DAG.getUNDEF(EltVT));
6746 // The input vector this mask element indexes into.
6747 int Input = Idx / NumElems;
6749 // Turn the index into an offset from the start of the input vector.
6750 Idx -= Input * NumElems;
6752 // Extract the vector element by hand.
6753 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6754 SVOp->getOperand(Input),
6755 DAG.getIntPtrConstant(Idx)));
6758 // Construct the output using a BUILD_VECTOR.
6759 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6761 } else if (InputUsed[0] < 0) {
6762 // No input vectors were used! The result is undefined.
6763 Output[l] = DAG.getUNDEF(NVT);
6765 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6766 (InputUsed[0] % 2) * NumLaneElems,
6768 // If only one input was used, use an undefined vector for the other.
6769 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6770 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6771 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6772 // At least one input vector was used. Create a new shuffle vector.
6773 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6779 // Concatenate the result back
6780 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6783 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6784 /// 4 elements, and match them with several different shuffle types.
6786 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6787 SDValue V1 = SVOp->getOperand(0);
6788 SDValue V2 = SVOp->getOperand(1);
6790 MVT VT = SVOp->getSimpleValueType(0);
6792 assert(VT.is128BitVector() && "Unsupported vector size");
6794 std::pair<int, int> Locs[4];
6795 int Mask1[] = { -1, -1, -1, -1 };
6796 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6800 for (unsigned i = 0; i != 4; ++i) {
6801 int Idx = PermMask[i];
6803 Locs[i] = std::make_pair(-1, -1);
6805 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6807 Locs[i] = std::make_pair(0, NumLo);
6811 Locs[i] = std::make_pair(1, NumHi);
6813 Mask1[2+NumHi] = Idx;
6819 if (NumLo <= 2 && NumHi <= 2) {
6820 // If no more than two elements come from either vector. This can be
6821 // implemented with two shuffles. First shuffle gather the elements.
6822 // The second shuffle, which takes the first shuffle as both of its
6823 // vector operands, put the elements into the right order.
6824 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6826 int Mask2[] = { -1, -1, -1, -1 };
6828 for (unsigned i = 0; i != 4; ++i)
6829 if (Locs[i].first != -1) {
6830 unsigned Idx = (i < 2) ? 0 : 4;
6831 Idx += Locs[i].first * 2 + Locs[i].second;
6835 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6838 if (NumLo == 3 || NumHi == 3) {
6839 // Otherwise, we must have three elements from one vector, call it X, and
6840 // one element from the other, call it Y. First, use a shufps to build an
6841 // intermediate vector with the one element from Y and the element from X
6842 // that will be in the same half in the final destination (the indexes don't
6843 // matter). Then, use a shufps to build the final vector, taking the half
6844 // containing the element from Y from the intermediate, and the other half
6847 // Normalize it so the 3 elements come from V1.
6848 CommuteVectorShuffleMask(PermMask, 4);
6852 // Find the element from V2.
6854 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6855 int Val = PermMask[HiIndex];
6862 Mask1[0] = PermMask[HiIndex];
6864 Mask1[2] = PermMask[HiIndex^1];
6866 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6869 Mask1[0] = PermMask[0];
6870 Mask1[1] = PermMask[1];
6871 Mask1[2] = HiIndex & 1 ? 6 : 4;
6872 Mask1[3] = HiIndex & 1 ? 4 : 6;
6873 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6876 Mask1[0] = HiIndex & 1 ? 2 : 0;
6877 Mask1[1] = HiIndex & 1 ? 0 : 2;
6878 Mask1[2] = PermMask[2];
6879 Mask1[3] = PermMask[3];
6884 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6887 // Break it into (shuffle shuffle_hi, shuffle_lo).
6888 int LoMask[] = { -1, -1, -1, -1 };
6889 int HiMask[] = { -1, -1, -1, -1 };
6891 int *MaskPtr = LoMask;
6892 unsigned MaskIdx = 0;
6895 for (unsigned i = 0; i != 4; ++i) {
6902 int Idx = PermMask[i];
6904 Locs[i] = std::make_pair(-1, -1);
6905 } else if (Idx < 4) {
6906 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6907 MaskPtr[LoIdx] = Idx;
6910 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6911 MaskPtr[HiIdx] = Idx;
6916 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6917 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6918 int MaskOps[] = { -1, -1, -1, -1 };
6919 for (unsigned i = 0; i != 4; ++i)
6920 if (Locs[i].first != -1)
6921 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6922 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6925 static bool MayFoldVectorLoad(SDValue V) {
6926 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6927 V = V.getOperand(0);
6929 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6930 V = V.getOperand(0);
6931 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6932 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6933 // BUILD_VECTOR (load), undef
6934 V = V.getOperand(0);
6936 return MayFoldLoad(V);
6940 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6941 EVT VT = Op.getValueType();
6943 // Canonizalize to v2f64.
6944 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6945 return DAG.getNode(ISD::BITCAST, dl, VT,
6946 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6951 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6953 SDValue V1 = Op.getOperand(0);
6954 SDValue V2 = Op.getOperand(1);
6955 EVT VT = Op.getValueType();
6957 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6959 if (HasSSE2 && VT == MVT::v2f64)
6960 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6962 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6963 return DAG.getNode(ISD::BITCAST, dl, VT,
6964 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6965 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6966 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6970 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6971 SDValue V1 = Op.getOperand(0);
6972 SDValue V2 = Op.getOperand(1);
6973 EVT VT = Op.getValueType();
6975 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6976 "unsupported shuffle type");
6978 if (V2.getOpcode() == ISD::UNDEF)
6982 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6986 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6987 SDValue V1 = Op.getOperand(0);
6988 SDValue V2 = Op.getOperand(1);
6989 EVT VT = Op.getValueType();
6990 unsigned NumElems = VT.getVectorNumElements();
6992 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6993 // operand of these instructions is only memory, so check if there's a
6994 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6996 bool CanFoldLoad = false;
6998 // Trivial case, when V2 comes from a load.
6999 if (MayFoldVectorLoad(V2))
7002 // When V1 is a load, it can be folded later into a store in isel, example:
7003 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7005 // (MOVLPSmr addr:$src1, VR128:$src2)
7006 // So, recognize this potential and also use MOVLPS or MOVLPD
7007 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7010 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7012 if (HasSSE2 && NumElems == 2)
7013 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7016 // If we don't care about the second element, proceed to use movss.
7017 if (SVOp->getMaskElt(1) != -1)
7018 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7021 // movl and movlp will both match v2i64, but v2i64 is never matched by
7022 // movl earlier because we make it strict to avoid messing with the movlp load
7023 // folding logic (see the code above getMOVLP call). Match it here then,
7024 // this is horrible, but will stay like this until we move all shuffle
7025 // matching to x86 specific nodes. Note that for the 1st condition all
7026 // types are matched with movsd.
7028 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7029 // as to remove this logic from here, as much as possible
7030 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7031 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7032 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7035 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7037 // Invert the operand order and use SHUFPS to match it.
7038 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7039 getShuffleSHUFImmediate(SVOp), DAG);
7042 // Reduce a vector shuffle to zext.
7043 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7044 SelectionDAG &DAG) {
7045 // PMOVZX is only available from SSE41.
7046 if (!Subtarget->hasSSE41())
7049 EVT VT = Op.getValueType();
7051 // Only AVX2 support 256-bit vector integer extending.
7052 if (!Subtarget->hasInt256() && VT.is256BitVector())
7055 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7057 SDValue V1 = Op.getOperand(0);
7058 SDValue V2 = Op.getOperand(1);
7059 unsigned NumElems = VT.getVectorNumElements();
7061 // Extending is an unary operation and the element type of the source vector
7062 // won't be equal to or larger than i64.
7063 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7064 VT.getVectorElementType() == MVT::i64)
7067 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7068 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7069 while ((1U << Shift) < NumElems) {
7070 if (SVOp->getMaskElt(1U << Shift) == 1)
7073 // The maximal ratio is 8, i.e. from i8 to i64.
7078 // Check the shuffle mask.
7079 unsigned Mask = (1U << Shift) - 1;
7080 for (unsigned i = 0; i != NumElems; ++i) {
7081 int EltIdx = SVOp->getMaskElt(i);
7082 if ((i & Mask) != 0 && EltIdx != -1)
7084 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7088 LLVMContext *Context = DAG.getContext();
7089 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7090 EVT NeVT = EVT::getIntegerVT(*Context, NBits);
7091 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
7093 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7096 // Simplify the operand as it's prepared to be fed into shuffle.
7097 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7098 if (V1.getOpcode() == ISD::BITCAST &&
7099 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7100 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7102 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
7103 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7104 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7105 ConstantSDNode *CIdx =
7106 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7107 // If it's foldable, i.e. normal load with single use, we will let code
7108 // selection to fold it. Otherwise, we will short the conversion sequence.
7109 if (CIdx && CIdx->getZExtValue() == 0 &&
7110 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7111 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
7112 // The "ext_vec_elt" node is wider than the result node.
7113 // In this case we should extract subvector from V.
7114 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7115 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
7116 EVT FullVT = V.getValueType();
7117 EVT SubVecVT = EVT::getVectorVT(*Context,
7118 FullVT.getVectorElementType(),
7119 FullVT.getVectorNumElements()/Ratio);
7120 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7121 DAG.getIntPtrConstant(0));
7123 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
7127 return DAG.getNode(ISD::BITCAST, DL, VT,
7128 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7132 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7133 SelectionDAG &DAG) {
7134 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7135 MVT VT = Op.getSimpleValueType();
7137 SDValue V1 = Op.getOperand(0);
7138 SDValue V2 = Op.getOperand(1);
7140 if (isZeroShuffle(SVOp))
7141 return getZeroVector(VT, Subtarget, DAG, dl);
7143 // Handle splat operations
7144 if (SVOp->isSplat()) {
7145 // Use vbroadcast whenever the splat comes from a foldable load
7146 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7147 if (Broadcast.getNode())
7151 // Check integer expanding shuffles.
7152 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7153 if (NewOp.getNode())
7156 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7158 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7159 VT == MVT::v16i16 || VT == MVT::v32i8) {
7160 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7161 if (NewOp.getNode())
7162 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7163 } else if ((VT == MVT::v4i32 ||
7164 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7165 // FIXME: Figure out a cleaner way to do this.
7166 // Try to make use of movq to zero out the top part.
7167 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7168 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7169 if (NewOp.getNode()) {
7170 MVT NewVT = NewOp.getSimpleValueType();
7171 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7172 NewVT, true, false))
7173 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7174 DAG, Subtarget, dl);
7176 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7177 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7178 if (NewOp.getNode()) {
7179 MVT NewVT = NewOp.getSimpleValueType();
7180 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7181 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7182 DAG, Subtarget, dl);
7190 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7191 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7192 SDValue V1 = Op.getOperand(0);
7193 SDValue V2 = Op.getOperand(1);
7194 MVT VT = Op.getSimpleValueType();
7196 unsigned NumElems = VT.getVectorNumElements();
7197 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7198 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7199 bool V1IsSplat = false;
7200 bool V2IsSplat = false;
7201 bool HasSSE2 = Subtarget->hasSSE2();
7202 bool HasFp256 = Subtarget->hasFp256();
7203 bool HasInt256 = Subtarget->hasInt256();
7204 MachineFunction &MF = DAG.getMachineFunction();
7205 bool OptForSize = MF.getFunction()->getAttributes().
7206 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7208 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7210 if (V1IsUndef && V2IsUndef)
7211 return DAG.getUNDEF(VT);
7213 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7215 // Vector shuffle lowering takes 3 steps:
7217 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7218 // narrowing and commutation of operands should be handled.
7219 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7221 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7222 // so the shuffle can be broken into other shuffles and the legalizer can
7223 // try the lowering again.
7225 // The general idea is that no vector_shuffle operation should be left to
7226 // be matched during isel, all of them must be converted to a target specific
7229 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7230 // narrowing and commutation of operands should be handled. The actual code
7231 // doesn't include all of those, work in progress...
7232 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7233 if (NewOp.getNode())
7236 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7238 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7239 // unpckh_undef). Only use pshufd if speed is more important than size.
7240 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7241 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7242 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7243 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7245 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7246 V2IsUndef && MayFoldVectorLoad(V1))
7247 return getMOVDDup(Op, dl, V1, DAG);
7249 if (isMOVHLPS_v_undef_Mask(M, VT))
7250 return getMOVHighToLow(Op, dl, DAG);
7252 // Use to match splats
7253 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7254 (VT == MVT::v2f64 || VT == MVT::v2i64))
7255 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7257 if (isPSHUFDMask(M, VT)) {
7258 // The actual implementation will match the mask in the if above and then
7259 // during isel it can match several different instructions, not only pshufd
7260 // as its name says, sad but true, emulate the behavior for now...
7261 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7262 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7264 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7266 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7267 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7269 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7270 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7273 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7277 if (isPALIGNRMask(M, VT, Subtarget))
7278 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7279 getShufflePALIGNRImmediate(SVOp),
7282 // Check if this can be converted into a logical shift.
7283 bool isLeft = false;
7286 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7287 if (isShift && ShVal.hasOneUse()) {
7288 // If the shifted value has multiple uses, it may be cheaper to use
7289 // v_set0 + movlhps or movhlps, etc.
7290 MVT EltVT = VT.getVectorElementType();
7291 ShAmt *= EltVT.getSizeInBits();
7292 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7295 if (isMOVLMask(M, VT)) {
7296 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7297 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7298 if (!isMOVLPMask(M, VT)) {
7299 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7300 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7302 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7303 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7307 // FIXME: fold these into legal mask.
7308 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7309 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7311 if (isMOVHLPSMask(M, VT))
7312 return getMOVHighToLow(Op, dl, DAG);
7314 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7315 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7317 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7318 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7320 if (isMOVLPMask(M, VT))
7321 return getMOVLP(Op, dl, DAG, HasSSE2);
7323 if (ShouldXformToMOVHLPS(M, VT) ||
7324 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7325 return CommuteVectorShuffle(SVOp, DAG);
7328 // No better options. Use a vshldq / vsrldq.
7329 MVT EltVT = VT.getVectorElementType();
7330 ShAmt *= EltVT.getSizeInBits();
7331 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7334 bool Commuted = false;
7335 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7336 // 1,1,1,1 -> v8i16 though.
7337 V1IsSplat = isSplatVector(V1.getNode());
7338 V2IsSplat = isSplatVector(V2.getNode());
7340 // Canonicalize the splat or undef, if present, to be on the RHS.
7341 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7342 CommuteVectorShuffleMask(M, NumElems);
7344 std::swap(V1IsSplat, V2IsSplat);
7348 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7349 // Shuffling low element of v1 into undef, just return v1.
7352 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7353 // the instruction selector will not match, so get a canonical MOVL with
7354 // swapped operands to undo the commute.
7355 return getMOVL(DAG, dl, VT, V2, V1);
7358 if (isUNPCKLMask(M, VT, HasInt256))
7359 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7361 if (isUNPCKHMask(M, VT, HasInt256))
7362 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7365 // Normalize mask so all entries that point to V2 points to its first
7366 // element then try to match unpck{h|l} again. If match, return a
7367 // new vector_shuffle with the corrected mask.p
7368 SmallVector<int, 8> NewMask(M.begin(), M.end());
7369 NormalizeMask(NewMask, NumElems);
7370 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7371 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7372 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7373 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7377 // Commute is back and try unpck* again.
7378 // FIXME: this seems wrong.
7379 CommuteVectorShuffleMask(M, NumElems);
7381 std::swap(V1IsSplat, V2IsSplat);
7384 if (isUNPCKLMask(M, VT, HasInt256))
7385 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7387 if (isUNPCKHMask(M, VT, HasInt256))
7388 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7391 // Normalize the node to match x86 shuffle ops if needed
7392 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7393 return CommuteVectorShuffle(SVOp, DAG);
7395 // The checks below are all present in isShuffleMaskLegal, but they are
7396 // inlined here right now to enable us to directly emit target specific
7397 // nodes, and remove one by one until they don't return Op anymore.
7399 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7400 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7401 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7402 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7405 if (isPSHUFHWMask(M, VT, HasInt256))
7406 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7407 getShufflePSHUFHWImmediate(SVOp),
7410 if (isPSHUFLWMask(M, VT, HasInt256))
7411 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7412 getShufflePSHUFLWImmediate(SVOp),
7415 if (isSHUFPMask(M, VT, HasFp256))
7416 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7417 getShuffleSHUFImmediate(SVOp), DAG);
7419 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7420 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7421 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7422 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7424 //===--------------------------------------------------------------------===//
7425 // Generate target specific nodes for 128 or 256-bit shuffles only
7426 // supported in the AVX instruction set.
7429 // Handle VMOVDDUPY permutations
7430 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7431 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7433 // Handle VPERMILPS/D* permutations
7434 if (isVPERMILPMask(M, VT, HasFp256)) {
7435 if (HasInt256 && VT == MVT::v8i32)
7436 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7437 getShuffleSHUFImmediate(SVOp), DAG);
7438 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7439 getShuffleSHUFImmediate(SVOp), DAG);
7442 // Handle VPERM2F128/VPERM2I128 permutations
7443 if (isVPERM2X128Mask(M, VT, HasFp256))
7444 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7445 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7447 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7448 if (BlendOp.getNode())
7452 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7453 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7455 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7456 VT.is512BitVector()) {
7457 EVT MaskEltVT = EVT::getIntegerVT(*DAG.getContext(),
7458 VT.getVectorElementType().getSizeInBits());
7460 EVT::getVectorVT(*DAG.getContext(),MaskEltVT, NumElems);
7461 SmallVector<SDValue, 16> permclMask;
7462 for (unsigned i = 0; i != NumElems; ++i) {
7463 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7466 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7467 &permclMask[0], NumElems);
7469 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7470 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7471 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7472 return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7473 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7476 //===--------------------------------------------------------------------===//
7477 // Since no target specific shuffle was selected for this generic one,
7478 // lower it into other known shuffles. FIXME: this isn't true yet, but
7479 // this is the plan.
7482 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7483 if (VT == MVT::v8i16) {
7484 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7485 if (NewOp.getNode())
7489 if (VT == MVT::v16i8) {
7490 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7491 if (NewOp.getNode())
7495 if (VT == MVT::v32i8) {
7496 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7497 if (NewOp.getNode())
7501 // Handle all 128-bit wide vectors with 4 elements, and match them with
7502 // several different shuffle types.
7503 if (NumElems == 4 && VT.is128BitVector())
7504 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7506 // Handle general 256-bit shuffles
7507 if (VT.is256BitVector())
7508 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7513 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7514 MVT VT = Op.getSimpleValueType();
7517 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7520 if (VT.getSizeInBits() == 8) {
7521 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7522 Op.getOperand(0), Op.getOperand(1));
7523 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7524 DAG.getValueType(VT));
7525 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7528 if (VT.getSizeInBits() == 16) {
7529 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7530 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7532 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7533 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7534 DAG.getNode(ISD::BITCAST, dl,
7538 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7539 Op.getOperand(0), Op.getOperand(1));
7540 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7541 DAG.getValueType(VT));
7542 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7545 if (VT == MVT::f32) {
7546 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7547 // the result back to FR32 register. It's only worth matching if the
7548 // result has a single use which is a store or a bitcast to i32. And in
7549 // the case of a store, it's not worth it if the index is a constant 0,
7550 // because a MOVSSmr can be used instead, which is smaller and faster.
7551 if (!Op.hasOneUse())
7553 SDNode *User = *Op.getNode()->use_begin();
7554 if ((User->getOpcode() != ISD::STORE ||
7555 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7556 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7557 (User->getOpcode() != ISD::BITCAST ||
7558 User->getValueType(0) != MVT::i32))
7560 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7561 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7564 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7567 if (VT == MVT::i32 || VT == MVT::i64) {
7568 // ExtractPS/pextrq works with constant index.
7569 if (isa<ConstantSDNode>(Op.getOperand(1)))
7576 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7577 SelectionDAG &DAG) const {
7579 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7582 SDValue Vec = Op.getOperand(0);
7583 MVT VecVT = Vec.getSimpleValueType();
7585 // If this is a 256-bit vector result, first extract the 128-bit vector and
7586 // then extract the element from the 128-bit vector.
7587 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7588 SDValue Idx = Op.getOperand(1);
7589 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7591 // Get the 128-bit vector.
7592 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7593 EVT EltVT = VecVT.getVectorElementType();
7595 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7597 //if (IdxVal >= NumElems/2)
7598 // IdxVal -= NumElems/2;
7599 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7600 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7601 DAG.getConstant(IdxVal, MVT::i32));
7604 assert(VecVT.is128BitVector() && "Unexpected vector length");
7606 if (Subtarget->hasSSE41()) {
7607 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7612 MVT VT = Op.getSimpleValueType();
7613 // TODO: handle v16i8.
7614 if (VT.getSizeInBits() == 16) {
7615 SDValue Vec = Op.getOperand(0);
7616 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7618 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7619 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7620 DAG.getNode(ISD::BITCAST, dl,
7623 // Transform it so it match pextrw which produces a 32-bit result.
7624 MVT EltVT = MVT::i32;
7625 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7626 Op.getOperand(0), Op.getOperand(1));
7627 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7628 DAG.getValueType(VT));
7629 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7632 if (VT.getSizeInBits() == 32) {
7633 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7637 // SHUFPS the element to the lowest double word, then movss.
7638 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7639 MVT VVT = Op.getOperand(0).getSimpleValueType();
7640 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7641 DAG.getUNDEF(VVT), Mask);
7642 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7643 DAG.getIntPtrConstant(0));
7646 if (VT.getSizeInBits() == 64) {
7647 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7648 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7649 // to match extract_elt for f64.
7650 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7654 // UNPCKHPD the element to the lowest double word, then movsd.
7655 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7656 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7657 int Mask[2] = { 1, -1 };
7658 MVT VVT = Op.getOperand(0).getSimpleValueType();
7659 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7660 DAG.getUNDEF(VVT), Mask);
7661 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7662 DAG.getIntPtrConstant(0));
7668 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7669 MVT VT = Op.getSimpleValueType();
7670 MVT EltVT = VT.getVectorElementType();
7673 SDValue N0 = Op.getOperand(0);
7674 SDValue N1 = Op.getOperand(1);
7675 SDValue N2 = Op.getOperand(2);
7677 if (!VT.is128BitVector())
7680 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7681 isa<ConstantSDNode>(N2)) {
7683 if (VT == MVT::v8i16)
7684 Opc = X86ISD::PINSRW;
7685 else if (VT == MVT::v16i8)
7686 Opc = X86ISD::PINSRB;
7688 Opc = X86ISD::PINSRB;
7690 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7692 if (N1.getValueType() != MVT::i32)
7693 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7694 if (N2.getValueType() != MVT::i32)
7695 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7696 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7699 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7700 // Bits [7:6] of the constant are the source select. This will always be
7701 // zero here. The DAG Combiner may combine an extract_elt index into these
7702 // bits. For example (insert (extract, 3), 2) could be matched by putting
7703 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7704 // Bits [5:4] of the constant are the destination select. This is the
7705 // value of the incoming immediate.
7706 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7707 // combine either bitwise AND or insert of float 0.0 to set these bits.
7708 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7709 // Create this as a scalar to vector..
7710 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7711 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7714 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7715 // PINSR* works with constant index.
7722 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7723 MVT VT = Op.getSimpleValueType();
7724 MVT EltVT = VT.getVectorElementType();
7727 SDValue N0 = Op.getOperand(0);
7728 SDValue N1 = Op.getOperand(1);
7729 SDValue N2 = Op.getOperand(2);
7731 // If this is a 256-bit vector result, first extract the 128-bit vector,
7732 // insert the element into the extracted half and then place it back.
7733 if (VT.is256BitVector() || VT.is512BitVector()) {
7734 if (!isa<ConstantSDNode>(N2))
7737 // Get the desired 128-bit vector half.
7738 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7739 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7741 // Insert the element into the desired half.
7742 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7743 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7745 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7746 DAG.getConstant(IdxIn128, MVT::i32));
7748 // Insert the changed part back to the 256-bit vector
7749 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7752 if (Subtarget->hasSSE41())
7753 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7755 if (EltVT == MVT::i8)
7758 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7759 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7760 // as its second argument.
7761 if (N1.getValueType() != MVT::i32)
7762 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7763 if (N2.getValueType() != MVT::i32)
7764 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7765 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7770 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7771 LLVMContext *Context = DAG.getContext();
7773 MVT OpVT = Op.getSimpleValueType();
7775 // If this is a 256-bit vector result, first insert into a 128-bit
7776 // vector and then insert into the 256-bit vector.
7777 if (!OpVT.is128BitVector()) {
7778 // Insert into a 128-bit vector.
7779 unsigned SizeFactor = OpVT.getSizeInBits()/128;
7780 EVT VT128 = EVT::getVectorVT(*Context,
7781 OpVT.getVectorElementType(),
7782 OpVT.getVectorNumElements() / SizeFactor);
7784 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7786 // Insert the 128-bit vector.
7787 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7790 if (OpVT == MVT::v1i64 &&
7791 Op.getOperand(0).getValueType() == MVT::i64)
7792 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7794 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7795 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7796 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7797 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7800 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7801 // a simple subregister reference or explicit instructions to grab
7802 // upper bits of a vector.
7803 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7804 SelectionDAG &DAG) {
7806 SDValue In = Op.getOperand(0);
7807 SDValue Idx = Op.getOperand(1);
7808 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7809 EVT ResVT = Op.getValueType();
7810 EVT InVT = In.getValueType();
7812 if (Subtarget->hasFp256()) {
7813 if (ResVT.is128BitVector() &&
7814 (InVT.is256BitVector() || InVT.is512BitVector()) &&
7815 isa<ConstantSDNode>(Idx)) {
7816 return Extract128BitVector(In, IdxVal, DAG, dl);
7818 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7819 isa<ConstantSDNode>(Idx)) {
7820 return Extract256BitVector(In, IdxVal, DAG, dl);
7826 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7827 // simple superregister reference or explicit instructions to insert
7828 // the upper bits of a vector.
7829 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7830 SelectionDAG &DAG) {
7831 if (Subtarget->hasFp256()) {
7832 SDLoc dl(Op.getNode());
7833 SDValue Vec = Op.getNode()->getOperand(0);
7834 SDValue SubVec = Op.getNode()->getOperand(1);
7835 SDValue Idx = Op.getNode()->getOperand(2);
7837 if ((Op.getNode()->getValueType(0).is256BitVector() ||
7838 Op.getNode()->getValueType(0).is512BitVector()) &&
7839 SubVec.getNode()->getValueType(0).is128BitVector() &&
7840 isa<ConstantSDNode>(Idx)) {
7841 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7842 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7845 if (Op.getNode()->getValueType(0).is512BitVector() &&
7846 SubVec.getNode()->getValueType(0).is256BitVector() &&
7847 isa<ConstantSDNode>(Idx)) {
7848 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7849 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7855 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7856 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7857 // one of the above mentioned nodes. It has to be wrapped because otherwise
7858 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7859 // be used to form addressing mode. These wrapped nodes will be selected
7862 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7863 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7865 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7867 unsigned char OpFlag = 0;
7868 unsigned WrapperKind = X86ISD::Wrapper;
7869 CodeModel::Model M = getTargetMachine().getCodeModel();
7871 if (Subtarget->isPICStyleRIPRel() &&
7872 (M == CodeModel::Small || M == CodeModel::Kernel))
7873 WrapperKind = X86ISD::WrapperRIP;
7874 else if (Subtarget->isPICStyleGOT())
7875 OpFlag = X86II::MO_GOTOFF;
7876 else if (Subtarget->isPICStyleStubPIC())
7877 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7879 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7881 CP->getOffset(), OpFlag);
7883 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7884 // With PIC, the address is actually $g + Offset.
7886 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7887 DAG.getNode(X86ISD::GlobalBaseReg,
7888 SDLoc(), getPointerTy()),
7895 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7896 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7898 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7900 unsigned char OpFlag = 0;
7901 unsigned WrapperKind = X86ISD::Wrapper;
7902 CodeModel::Model M = getTargetMachine().getCodeModel();
7904 if (Subtarget->isPICStyleRIPRel() &&
7905 (M == CodeModel::Small || M == CodeModel::Kernel))
7906 WrapperKind = X86ISD::WrapperRIP;
7907 else if (Subtarget->isPICStyleGOT())
7908 OpFlag = X86II::MO_GOTOFF;
7909 else if (Subtarget->isPICStyleStubPIC())
7910 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7912 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7915 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7917 // With PIC, the address is actually $g + Offset.
7919 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7920 DAG.getNode(X86ISD::GlobalBaseReg,
7921 SDLoc(), getPointerTy()),
7928 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7929 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7931 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7933 unsigned char OpFlag = 0;
7934 unsigned WrapperKind = X86ISD::Wrapper;
7935 CodeModel::Model M = getTargetMachine().getCodeModel();
7937 if (Subtarget->isPICStyleRIPRel() &&
7938 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7939 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7940 OpFlag = X86II::MO_GOTPCREL;
7941 WrapperKind = X86ISD::WrapperRIP;
7942 } else if (Subtarget->isPICStyleGOT()) {
7943 OpFlag = X86II::MO_GOT;
7944 } else if (Subtarget->isPICStyleStubPIC()) {
7945 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7946 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7947 OpFlag = X86II::MO_DARWIN_NONLAZY;
7950 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7953 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7955 // With PIC, the address is actually $g + Offset.
7956 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7957 !Subtarget->is64Bit()) {
7958 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7959 DAG.getNode(X86ISD::GlobalBaseReg,
7960 SDLoc(), getPointerTy()),
7964 // For symbols that require a load from a stub to get the address, emit the
7966 if (isGlobalStubReference(OpFlag))
7967 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7968 MachinePointerInfo::getGOT(), false, false, false, 0);
7974 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7975 // Create the TargetBlockAddressAddress node.
7976 unsigned char OpFlags =
7977 Subtarget->ClassifyBlockAddressReference();
7978 CodeModel::Model M = getTargetMachine().getCodeModel();
7979 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7980 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7982 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7985 if (Subtarget->isPICStyleRIPRel() &&
7986 (M == CodeModel::Small || M == CodeModel::Kernel))
7987 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7989 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7991 // With PIC, the address is actually $g + Offset.
7992 if (isGlobalRelativeToPICBase(OpFlags)) {
7993 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7994 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8002 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8003 int64_t Offset, SelectionDAG &DAG) const {
8004 // Create the TargetGlobalAddress node, folding in the constant
8005 // offset if it is legal.
8006 unsigned char OpFlags =
8007 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8008 CodeModel::Model M = getTargetMachine().getCodeModel();
8010 if (OpFlags == X86II::MO_NO_FLAG &&
8011 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8012 // A direct static reference to a global.
8013 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8016 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8019 if (Subtarget->isPICStyleRIPRel() &&
8020 (M == CodeModel::Small || M == CodeModel::Kernel))
8021 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8023 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8025 // With PIC, the address is actually $g + Offset.
8026 if (isGlobalRelativeToPICBase(OpFlags)) {
8027 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8028 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8032 // For globals that require a load from a stub to get the address, emit the
8034 if (isGlobalStubReference(OpFlags))
8035 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8036 MachinePointerInfo::getGOT(), false, false, false, 0);
8038 // If there was a non-zero offset that we didn't fold, create an explicit
8041 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8042 DAG.getConstant(Offset, getPointerTy()));
8048 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8049 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8050 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8051 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8055 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8056 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8057 unsigned char OperandFlags, bool LocalDynamic = false) {
8058 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8059 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8061 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8062 GA->getValueType(0),
8066 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8070 SDValue Ops[] = { Chain, TGA, *InFlag };
8071 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8073 SDValue Ops[] = { Chain, TGA };
8074 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8077 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8078 MFI->setAdjustsStack(true);
8080 SDValue Flag = Chain.getValue(1);
8081 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8084 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8086 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8089 SDLoc dl(GA); // ? function entry point might be better
8090 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8091 DAG.getNode(X86ISD::GlobalBaseReg,
8092 SDLoc(), PtrVT), InFlag);
8093 InFlag = Chain.getValue(1);
8095 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8098 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8100 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8102 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8103 X86::RAX, X86II::MO_TLSGD);
8106 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8112 // Get the start address of the TLS block for this module.
8113 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8114 .getInfo<X86MachineFunctionInfo>();
8115 MFI->incNumLocalDynamicTLSAccesses();
8119 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8120 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8123 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8124 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8125 InFlag = Chain.getValue(1);
8126 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8127 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8130 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8134 unsigned char OperandFlags = X86II::MO_DTPOFF;
8135 unsigned WrapperKind = X86ISD::Wrapper;
8136 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8137 GA->getValueType(0),
8138 GA->getOffset(), OperandFlags);
8139 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8141 // Add x@dtpoff with the base.
8142 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8145 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8146 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8147 const EVT PtrVT, TLSModel::Model model,
8148 bool is64Bit, bool isPIC) {
8151 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8152 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8153 is64Bit ? 257 : 256));
8155 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8156 DAG.getIntPtrConstant(0),
8157 MachinePointerInfo(Ptr),
8158 false, false, false, 0);
8160 unsigned char OperandFlags = 0;
8161 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8163 unsigned WrapperKind = X86ISD::Wrapper;
8164 if (model == TLSModel::LocalExec) {
8165 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8166 } else if (model == TLSModel::InitialExec) {
8168 OperandFlags = X86II::MO_GOTTPOFF;
8169 WrapperKind = X86ISD::WrapperRIP;
8171 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8174 llvm_unreachable("Unexpected model");
8177 // emit "addl x@ntpoff,%eax" (local exec)
8178 // or "addl x@indntpoff,%eax" (initial exec)
8179 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8180 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8181 GA->getValueType(0),
8182 GA->getOffset(), OperandFlags);
8183 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8185 if (model == TLSModel::InitialExec) {
8186 if (isPIC && !is64Bit) {
8187 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8188 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8192 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8193 MachinePointerInfo::getGOT(), false, false, false,
8197 // The address of the thread local variable is the add of the thread
8198 // pointer with the offset of the variable.
8199 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8203 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8205 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8206 const GlobalValue *GV = GA->getGlobal();
8208 if (Subtarget->isTargetELF()) {
8209 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8212 case TLSModel::GeneralDynamic:
8213 if (Subtarget->is64Bit())
8214 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8215 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8216 case TLSModel::LocalDynamic:
8217 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8218 Subtarget->is64Bit());
8219 case TLSModel::InitialExec:
8220 case TLSModel::LocalExec:
8221 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8222 Subtarget->is64Bit(),
8223 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8225 llvm_unreachable("Unknown TLS model.");
8228 if (Subtarget->isTargetDarwin()) {
8229 // Darwin only has one model of TLS. Lower to that.
8230 unsigned char OpFlag = 0;
8231 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8232 X86ISD::WrapperRIP : X86ISD::Wrapper;
8234 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8236 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8237 !Subtarget->is64Bit();
8239 OpFlag = X86II::MO_TLVP_PIC_BASE;
8241 OpFlag = X86II::MO_TLVP;
8243 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8244 GA->getValueType(0),
8245 GA->getOffset(), OpFlag);
8246 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8248 // With PIC32, the address is actually $g + Offset.
8250 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8251 DAG.getNode(X86ISD::GlobalBaseReg,
8252 SDLoc(), getPointerTy()),
8255 // Lowering the machine isd will make sure everything is in the right
8257 SDValue Chain = DAG.getEntryNode();
8258 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8259 SDValue Args[] = { Chain, Offset };
8260 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8262 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8263 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8264 MFI->setAdjustsStack(true);
8266 // And our return value (tls address) is in the standard call return value
8268 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8269 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8273 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8274 // Just use the implicit TLS architecture
8275 // Need to generate someting similar to:
8276 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8278 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8279 // mov rcx, qword [rdx+rcx*8]
8280 // mov eax, .tls$:tlsvar
8281 // [rax+rcx] contains the address
8282 // Windows 64bit: gs:0x58
8283 // Windows 32bit: fs:__tls_array
8285 // If GV is an alias then use the aliasee for determining
8286 // thread-localness.
8287 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8288 GV = GA->resolveAliasedGlobal(false);
8290 SDValue Chain = DAG.getEntryNode();
8292 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8293 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8294 // use its literal value of 0x2C.
8295 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8296 ? Type::getInt8PtrTy(*DAG.getContext(),
8298 : Type::getInt32PtrTy(*DAG.getContext(),
8301 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8302 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8303 DAG.getExternalSymbol("_tls_array", getPointerTy()));
8305 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8306 MachinePointerInfo(Ptr),
8307 false, false, false, 0);
8309 // Load the _tls_index variable
8310 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8311 if (Subtarget->is64Bit())
8312 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8313 IDX, MachinePointerInfo(), MVT::i32,
8316 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8317 false, false, false, 0);
8319 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8321 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8323 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8324 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8325 false, false, false, 0);
8327 // Get the offset of start of .tls section
8328 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8329 GA->getValueType(0),
8330 GA->getOffset(), X86II::MO_SECREL);
8331 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8333 // The address of the thread local variable is the add of the thread
8334 // pointer with the offset of the variable.
8335 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8338 llvm_unreachable("TLS not implemented for this target.");
8341 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8342 /// and take a 2 x i32 value to shift plus a shift amount.
8343 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8344 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8345 EVT VT = Op.getValueType();
8346 unsigned VTBits = VT.getSizeInBits();
8348 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8349 SDValue ShOpLo = Op.getOperand(0);
8350 SDValue ShOpHi = Op.getOperand(1);
8351 SDValue ShAmt = Op.getOperand(2);
8352 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8353 DAG.getConstant(VTBits - 1, MVT::i8))
8354 : DAG.getConstant(0, VT);
8357 if (Op.getOpcode() == ISD::SHL_PARTS) {
8358 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8359 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8361 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8362 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8365 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8366 DAG.getConstant(VTBits, MVT::i8));
8367 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8368 AndNode, DAG.getConstant(0, MVT::i8));
8371 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8372 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8373 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8375 if (Op.getOpcode() == ISD::SHL_PARTS) {
8376 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8377 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8379 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8380 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8383 SDValue Ops[2] = { Lo, Hi };
8384 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8387 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8388 SelectionDAG &DAG) const {
8389 EVT SrcVT = Op.getOperand(0).getValueType();
8391 if (SrcVT.isVector())
8394 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8395 "Unknown SINT_TO_FP to lower!");
8397 // These are really Legal; return the operand so the caller accepts it as
8399 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8401 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8402 Subtarget->is64Bit()) {
8407 unsigned Size = SrcVT.getSizeInBits()/8;
8408 MachineFunction &MF = DAG.getMachineFunction();
8409 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8410 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8411 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8413 MachinePointerInfo::getFixedStack(SSFI),
8415 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8418 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8420 SelectionDAG &DAG) const {
8424 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8426 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8428 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8430 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8432 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8433 MachineMemOperand *MMO;
8435 int SSFI = FI->getIndex();
8437 DAG.getMachineFunction()
8438 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8439 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8441 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8442 StackSlot = StackSlot.getOperand(1);
8444 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8445 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8447 Tys, Ops, array_lengthof(Ops),
8451 Chain = Result.getValue(1);
8452 SDValue InFlag = Result.getValue(2);
8454 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8455 // shouldn't be necessary except that RFP cannot be live across
8456 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8457 MachineFunction &MF = DAG.getMachineFunction();
8458 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8459 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8460 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8461 Tys = DAG.getVTList(MVT::Other);
8463 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8465 MachineMemOperand *MMO =
8466 DAG.getMachineFunction()
8467 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8468 MachineMemOperand::MOStore, SSFISize, SSFISize);
8470 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8471 Ops, array_lengthof(Ops),
8472 Op.getValueType(), MMO);
8473 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8474 MachinePointerInfo::getFixedStack(SSFI),
8475 false, false, false, 0);
8481 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8482 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8483 SelectionDAG &DAG) const {
8484 // This algorithm is not obvious. Here it is what we're trying to output:
8487 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8488 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8492 pshufd $0x4e, %xmm0, %xmm1
8498 LLVMContext *Context = DAG.getContext();
8500 // Build some magic constants.
8501 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8502 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8503 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8505 SmallVector<Constant*,2> CV1;
8507 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8508 APInt(64, 0x4330000000000000ULL))));
8510 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8511 APInt(64, 0x4530000000000000ULL))));
8512 Constant *C1 = ConstantVector::get(CV1);
8513 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8515 // Load the 64-bit value into an XMM register.
8516 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8518 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8519 MachinePointerInfo::getConstantPool(),
8520 false, false, false, 16);
8521 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8522 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8525 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8526 MachinePointerInfo::getConstantPool(),
8527 false, false, false, 16);
8528 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8529 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8532 if (Subtarget->hasSSE3()) {
8533 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8534 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8536 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8537 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8539 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8540 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8544 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8545 DAG.getIntPtrConstant(0));
8548 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8549 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8550 SelectionDAG &DAG) const {
8552 // FP constant to bias correct the final result.
8553 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8556 // Load the 32-bit value into an XMM register.
8557 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8560 // Zero out the upper parts of the register.
8561 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8563 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8564 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8565 DAG.getIntPtrConstant(0));
8567 // Or the load with the bias.
8568 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8569 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8570 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8572 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8573 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8574 MVT::v2f64, Bias)));
8575 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8576 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8577 DAG.getIntPtrConstant(0));
8579 // Subtract the bias.
8580 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8582 // Handle final rounding.
8583 EVT DestVT = Op.getValueType();
8585 if (DestVT.bitsLT(MVT::f64))
8586 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8587 DAG.getIntPtrConstant(0));
8588 if (DestVT.bitsGT(MVT::f64))
8589 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8591 // Handle final rounding.
8595 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8596 SelectionDAG &DAG) const {
8597 SDValue N0 = Op.getOperand(0);
8598 EVT SVT = N0.getValueType();
8601 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8602 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8603 "Custom UINT_TO_FP is not supported!");
8605 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8606 SVT.getVectorNumElements());
8607 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8608 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8611 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8612 SelectionDAG &DAG) const {
8613 SDValue N0 = Op.getOperand(0);
8616 if (Op.getValueType().isVector())
8617 return lowerUINT_TO_FP_vec(Op, DAG);
8619 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8620 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8621 // the optimization here.
8622 if (DAG.SignBitIsZero(N0))
8623 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8625 EVT SrcVT = N0.getValueType();
8626 EVT DstVT = Op.getValueType();
8627 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8628 return LowerUINT_TO_FP_i64(Op, DAG);
8629 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8630 return LowerUINT_TO_FP_i32(Op, DAG);
8631 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8634 // Make a 64-bit buffer, and use it to build an FILD.
8635 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8636 if (SrcVT == MVT::i32) {
8637 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8638 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8639 getPointerTy(), StackSlot, WordOff);
8640 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8641 StackSlot, MachinePointerInfo(),
8643 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8644 OffsetSlot, MachinePointerInfo(),
8646 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8650 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8651 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8652 StackSlot, MachinePointerInfo(),
8654 // For i64 source, we need to add the appropriate power of 2 if the input
8655 // was negative. This is the same as the optimization in
8656 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8657 // we must be careful to do the computation in x87 extended precision, not
8658 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8659 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8660 MachineMemOperand *MMO =
8661 DAG.getMachineFunction()
8662 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8663 MachineMemOperand::MOLoad, 8, 8);
8665 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8666 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8667 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8668 array_lengthof(Ops), MVT::i64, MMO);
8670 APInt FF(32, 0x5F800000ULL);
8672 // Check whether the sign bit is set.
8673 SDValue SignSet = DAG.getSetCC(dl,
8674 getSetCCResultType(*DAG.getContext(), MVT::i64),
8675 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8678 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8679 SDValue FudgePtr = DAG.getConstantPool(
8680 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8683 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8684 SDValue Zero = DAG.getIntPtrConstant(0);
8685 SDValue Four = DAG.getIntPtrConstant(4);
8686 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8688 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8690 // Load the value out, extending it from f32 to f80.
8691 // FIXME: Avoid the extend by constructing the right constant pool?
8692 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8693 FudgePtr, MachinePointerInfo::getConstantPool(),
8694 MVT::f32, false, false, 4);
8695 // Extend everything to 80 bits to force it to be done on x87.
8696 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8697 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8700 std::pair<SDValue,SDValue>
8701 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8702 bool IsSigned, bool IsReplace) const {
8705 EVT DstTy = Op.getValueType();
8707 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8708 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8712 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8713 DstTy.getSimpleVT() >= MVT::i16 &&
8714 "Unknown FP_TO_INT to lower!");
8716 // These are really Legal.
8717 if (DstTy == MVT::i32 &&
8718 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8719 return std::make_pair(SDValue(), SDValue());
8720 if (Subtarget->is64Bit() &&
8721 DstTy == MVT::i64 &&
8722 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8723 return std::make_pair(SDValue(), SDValue());
8725 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8726 // stack slot, or into the FTOL runtime function.
8727 MachineFunction &MF = DAG.getMachineFunction();
8728 unsigned MemSize = DstTy.getSizeInBits()/8;
8729 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8730 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8733 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8734 Opc = X86ISD::WIN_FTOL;
8736 switch (DstTy.getSimpleVT().SimpleTy) {
8737 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8738 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8739 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8740 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8743 SDValue Chain = DAG.getEntryNode();
8744 SDValue Value = Op.getOperand(0);
8745 EVT TheVT = Op.getOperand(0).getValueType();
8746 // FIXME This causes a redundant load/store if the SSE-class value is already
8747 // in memory, such as if it is on the callstack.
8748 if (isScalarFPTypeInSSEReg(TheVT)) {
8749 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8750 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8751 MachinePointerInfo::getFixedStack(SSFI),
8753 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8755 Chain, StackSlot, DAG.getValueType(TheVT)
8758 MachineMemOperand *MMO =
8759 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8760 MachineMemOperand::MOLoad, MemSize, MemSize);
8761 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8762 array_lengthof(Ops), DstTy, MMO);
8763 Chain = Value.getValue(1);
8764 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8765 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8768 MachineMemOperand *MMO =
8769 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8770 MachineMemOperand::MOStore, MemSize, MemSize);
8772 if (Opc != X86ISD::WIN_FTOL) {
8773 // Build the FP_TO_INT*_IN_MEM
8774 SDValue Ops[] = { Chain, Value, StackSlot };
8775 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8776 Ops, array_lengthof(Ops), DstTy,
8778 return std::make_pair(FIST, StackSlot);
8780 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8781 DAG.getVTList(MVT::Other, MVT::Glue),
8783 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8784 MVT::i32, ftol.getValue(1));
8785 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8786 MVT::i32, eax.getValue(2));
8787 SDValue Ops[] = { eax, edx };
8788 SDValue pair = IsReplace
8789 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8790 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8791 return std::make_pair(pair, SDValue());
8795 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8796 const X86Subtarget *Subtarget) {
8797 MVT VT = Op->getSimpleValueType(0);
8798 SDValue In = Op->getOperand(0);
8799 MVT InVT = In.getSimpleValueType();
8802 // Optimize vectors in AVX mode:
8805 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8806 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8807 // Concat upper and lower parts.
8810 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8811 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8812 // Concat upper and lower parts.
8815 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8816 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8819 if (Subtarget->hasInt256())
8820 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8822 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8823 SDValue Undef = DAG.getUNDEF(InVT);
8824 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8825 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8826 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8828 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8829 VT.getVectorNumElements()/2);
8831 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8832 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8834 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8837 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8838 SelectionDAG &DAG) const {
8839 if (Subtarget->hasFp256()) {
8840 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8847 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8848 SelectionDAG &DAG) const {
8850 MVT VT = Op.getSimpleValueType();
8851 SDValue In = Op.getOperand(0);
8852 MVT SVT = In.getSimpleValueType();
8854 if (Subtarget->hasFp256()) {
8855 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8860 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8861 VT.getVectorNumElements() != SVT.getVectorNumElements())
8864 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8866 // AVX2 has better support of integer extending.
8867 if (Subtarget->hasInt256())
8868 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8870 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8871 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8872 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8873 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8874 DAG.getUNDEF(MVT::v8i16),
8877 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8880 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8882 MVT VT = Op.getSimpleValueType();
8883 SDValue In = Op.getOperand(0);
8884 MVT SVT = In.getSimpleValueType();
8886 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8887 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8888 if (Subtarget->hasInt256()) {
8889 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8890 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8891 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8893 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8894 DAG.getIntPtrConstant(0));
8897 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8898 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8899 DAG.getIntPtrConstant(0));
8900 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8901 DAG.getIntPtrConstant(2));
8903 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8904 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8907 static const int ShufMask1[] = {0, 2, 0, 0};
8908 SDValue Undef = DAG.getUNDEF(VT);
8909 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8910 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8912 // The MOVLHPS mask:
8913 static const int ShufMask2[] = {0, 1, 4, 5};
8914 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8917 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8918 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8919 if (Subtarget->hasInt256()) {
8920 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8922 SmallVector<SDValue,32> pshufbMask;
8923 for (unsigned i = 0; i < 2; ++i) {
8924 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8925 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8926 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8927 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8928 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8929 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8930 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8931 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8932 for (unsigned j = 0; j < 8; ++j)
8933 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8935 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8936 &pshufbMask[0], 32);
8937 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8938 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8940 static const int ShufMask[] = {0, 2, -1, -1};
8941 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8943 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8944 DAG.getIntPtrConstant(0));
8945 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8948 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8949 DAG.getIntPtrConstant(0));
8951 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8952 DAG.getIntPtrConstant(4));
8954 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8955 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8958 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8959 -1, -1, -1, -1, -1, -1, -1, -1};
8961 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8962 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8963 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8965 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8966 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8968 // The MOVLHPS Mask:
8969 static const int ShufMask2[] = {0, 1, 4, 5};
8970 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8971 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8974 // Handle truncation of V256 to V128 using shuffles.
8975 if (!VT.is128BitVector() || !SVT.is256BitVector())
8978 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8980 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8982 unsigned NumElems = VT.getVectorNumElements();
8983 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8986 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8987 // Prepare truncation shuffle mask
8988 for (unsigned i = 0; i != NumElems; ++i)
8990 SDValue V = DAG.getVectorShuffle(NVT, DL,
8991 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8992 DAG.getUNDEF(NVT), &MaskVec[0]);
8993 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8994 DAG.getIntPtrConstant(0));
8997 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8998 SelectionDAG &DAG) const {
8999 MVT VT = Op.getSimpleValueType();
9000 if (VT.isVector()) {
9001 if (VT == MVT::v8i16)
9002 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9003 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9004 MVT::v8i32, Op.getOperand(0)));
9008 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9009 /*IsSigned=*/ true, /*IsReplace=*/ false);
9010 SDValue FIST = Vals.first, StackSlot = Vals.second;
9011 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9012 if (FIST.getNode() == 0) return Op;
9014 if (StackSlot.getNode())
9016 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9017 FIST, StackSlot, MachinePointerInfo(),
9018 false, false, false, 0);
9020 // The node is the result.
9024 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9025 SelectionDAG &DAG) const {
9026 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9027 /*IsSigned=*/ false, /*IsReplace=*/ false);
9028 SDValue FIST = Vals.first, StackSlot = Vals.second;
9029 assert(FIST.getNode() && "Unexpected failure");
9031 if (StackSlot.getNode())
9033 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9034 FIST, StackSlot, MachinePointerInfo(),
9035 false, false, false, 0);
9037 // The node is the result.
9041 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9043 MVT VT = Op.getSimpleValueType();
9044 SDValue In = Op.getOperand(0);
9045 MVT SVT = In.getSimpleValueType();
9047 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9049 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9050 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9051 In, DAG.getUNDEF(SVT)));
9054 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9055 LLVMContext *Context = DAG.getContext();
9057 MVT VT = Op.getSimpleValueType();
9059 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9060 if (VT.isVector()) {
9061 EltVT = VT.getVectorElementType();
9062 NumElts = VT.getVectorNumElements();
9065 if (EltVT == MVT::f64)
9066 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9067 APInt(64, ~(1ULL << 63))));
9069 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9070 APInt(32, ~(1U << 31))));
9071 C = ConstantVector::getSplat(NumElts, C);
9072 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9073 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9074 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9075 MachinePointerInfo::getConstantPool(),
9076 false, false, false, Alignment);
9077 if (VT.isVector()) {
9078 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9079 return DAG.getNode(ISD::BITCAST, dl, VT,
9080 DAG.getNode(ISD::AND, dl, ANDVT,
9081 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9083 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9085 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9088 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9089 LLVMContext *Context = DAG.getContext();
9091 MVT VT = Op.getSimpleValueType();
9093 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9094 if (VT.isVector()) {
9095 EltVT = VT.getVectorElementType();
9096 NumElts = VT.getVectorNumElements();
9099 if (EltVT == MVT::f64)
9100 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9101 APInt(64, 1ULL << 63)));
9103 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9104 APInt(32, 1U << 31)));
9105 C = ConstantVector::getSplat(NumElts, C);
9106 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9107 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9108 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9109 MachinePointerInfo::getConstantPool(),
9110 false, false, false, Alignment);
9111 if (VT.isVector()) {
9112 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9113 return DAG.getNode(ISD::BITCAST, dl, VT,
9114 DAG.getNode(ISD::XOR, dl, XORVT,
9115 DAG.getNode(ISD::BITCAST, dl, XORVT,
9117 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9120 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9123 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9124 LLVMContext *Context = DAG.getContext();
9125 SDValue Op0 = Op.getOperand(0);
9126 SDValue Op1 = Op.getOperand(1);
9128 MVT VT = Op.getSimpleValueType();
9129 MVT SrcVT = Op1.getSimpleValueType();
9131 // If second operand is smaller, extend it first.
9132 if (SrcVT.bitsLT(VT)) {
9133 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9136 // And if it is bigger, shrink it first.
9137 if (SrcVT.bitsGT(VT)) {
9138 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9142 // At this point the operands and the result should have the same
9143 // type, and that won't be f80 since that is not custom lowered.
9145 // First get the sign bit of second operand.
9146 SmallVector<Constant*,4> CV;
9147 if (SrcVT == MVT::f64) {
9148 const fltSemantics &Sem = APFloat::IEEEdouble;
9149 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9150 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9152 const fltSemantics &Sem = APFloat::IEEEsingle;
9153 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9154 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9155 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9156 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9158 Constant *C = ConstantVector::get(CV);
9159 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9160 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9161 MachinePointerInfo::getConstantPool(),
9162 false, false, false, 16);
9163 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9165 // Shift sign bit right or left if the two operands have different types.
9166 if (SrcVT.bitsGT(VT)) {
9167 // Op0 is MVT::f32, Op1 is MVT::f64.
9168 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9169 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9170 DAG.getConstant(32, MVT::i32));
9171 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9172 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9173 DAG.getIntPtrConstant(0));
9176 // Clear first operand sign bit.
9178 if (VT == MVT::f64) {
9179 const fltSemantics &Sem = APFloat::IEEEdouble;
9180 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9181 APInt(64, ~(1ULL << 63)))));
9182 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9184 const fltSemantics &Sem = APFloat::IEEEsingle;
9185 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9186 APInt(32, ~(1U << 31)))));
9187 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9188 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9189 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9191 C = ConstantVector::get(CV);
9192 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9193 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9194 MachinePointerInfo::getConstantPool(),
9195 false, false, false, 16);
9196 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9198 // Or the value with the sign bit.
9199 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9202 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9203 SDValue N0 = Op.getOperand(0);
9205 MVT VT = Op.getSimpleValueType();
9207 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9208 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9209 DAG.getConstant(1, VT));
9210 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9213 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9215 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9216 SelectionDAG &DAG) {
9217 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9219 if (!Subtarget->hasSSE41())
9222 if (!Op->hasOneUse())
9225 SDNode *N = Op.getNode();
9228 SmallVector<SDValue, 8> Opnds;
9229 DenseMap<SDValue, unsigned> VecInMap;
9230 EVT VT = MVT::Other;
9232 // Recognize a special case where a vector is casted into wide integer to
9234 Opnds.push_back(N->getOperand(0));
9235 Opnds.push_back(N->getOperand(1));
9237 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9238 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9239 // BFS traverse all OR'd operands.
9240 if (I->getOpcode() == ISD::OR) {
9241 Opnds.push_back(I->getOperand(0));
9242 Opnds.push_back(I->getOperand(1));
9243 // Re-evaluate the number of nodes to be traversed.
9244 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9248 // Quit if a non-EXTRACT_VECTOR_ELT
9249 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9252 // Quit if without a constant index.
9253 SDValue Idx = I->getOperand(1);
9254 if (!isa<ConstantSDNode>(Idx))
9257 SDValue ExtractedFromVec = I->getOperand(0);
9258 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9259 if (M == VecInMap.end()) {
9260 VT = ExtractedFromVec.getValueType();
9261 // Quit if not 128/256-bit vector.
9262 if (!VT.is128BitVector() && !VT.is256BitVector())
9264 // Quit if not the same type.
9265 if (VecInMap.begin() != VecInMap.end() &&
9266 VT != VecInMap.begin()->first.getValueType())
9268 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9270 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9273 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9274 "Not extracted from 128-/256-bit vector.");
9276 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9277 SmallVector<SDValue, 8> VecIns;
9279 for (DenseMap<SDValue, unsigned>::const_iterator
9280 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9281 // Quit if not all elements are used.
9282 if (I->second != FullMask)
9284 VecIns.push_back(I->first);
9287 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9289 // Cast all vectors into TestVT for PTEST.
9290 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9291 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9293 // If more than one full vectors are evaluated, OR them first before PTEST.
9294 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9295 // Each iteration will OR 2 nodes and append the result until there is only
9296 // 1 node left, i.e. the final OR'd value of all vectors.
9297 SDValue LHS = VecIns[Slot];
9298 SDValue RHS = VecIns[Slot + 1];
9299 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9302 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9303 VecIns.back(), VecIns.back());
9306 /// Emit nodes that will be selected as "test Op0,Op0", or something
9308 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9309 SelectionDAG &DAG) const {
9312 // CF and OF aren't always set the way we want. Determine which
9313 // of these we need.
9314 bool NeedCF = false;
9315 bool NeedOF = false;
9318 case X86::COND_A: case X86::COND_AE:
9319 case X86::COND_B: case X86::COND_BE:
9322 case X86::COND_G: case X86::COND_GE:
9323 case X86::COND_L: case X86::COND_LE:
9324 case X86::COND_O: case X86::COND_NO:
9329 // See if we can use the EFLAGS value from the operand instead of
9330 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9331 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9332 if (Op.getResNo() != 0 || NeedOF || NeedCF)
9333 // Emit a CMP with 0, which is the TEST pattern.
9334 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9335 DAG.getConstant(0, Op.getValueType()));
9337 unsigned Opcode = 0;
9338 unsigned NumOperands = 0;
9340 // Truncate operations may prevent the merge of the SETCC instruction
9341 // and the arithmetic intruction before it. Attempt to truncate the operands
9342 // of the arithmetic instruction and use a reduced bit-width instruction.
9343 bool NeedTruncation = false;
9344 SDValue ArithOp = Op;
9345 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9346 SDValue Arith = Op->getOperand(0);
9347 // Both the trunc and the arithmetic op need to have one user each.
9348 if (Arith->hasOneUse())
9349 switch (Arith.getOpcode()) {
9356 NeedTruncation = true;
9362 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9363 // which may be the result of a CAST. We use the variable 'Op', which is the
9364 // non-casted variable when we check for possible users.
9365 switch (ArithOp.getOpcode()) {
9367 // Due to an isel shortcoming, be conservative if this add is likely to be
9368 // selected as part of a load-modify-store instruction. When the root node
9369 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9370 // uses of other nodes in the match, such as the ADD in this case. This
9371 // leads to the ADD being left around and reselected, with the result being
9372 // two adds in the output. Alas, even if none our users are stores, that
9373 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9374 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9375 // climbing the DAG back to the root, and it doesn't seem to be worth the
9377 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9378 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9379 if (UI->getOpcode() != ISD::CopyToReg &&
9380 UI->getOpcode() != ISD::SETCC &&
9381 UI->getOpcode() != ISD::STORE)
9384 if (ConstantSDNode *C =
9385 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9386 // An add of one will be selected as an INC.
9387 if (C->getAPIntValue() == 1) {
9388 Opcode = X86ISD::INC;
9393 // An add of negative one (subtract of one) will be selected as a DEC.
9394 if (C->getAPIntValue().isAllOnesValue()) {
9395 Opcode = X86ISD::DEC;
9401 // Otherwise use a regular EFLAGS-setting add.
9402 Opcode = X86ISD::ADD;
9406 // If the primary and result isn't used, don't bother using X86ISD::AND,
9407 // because a TEST instruction will be better.
9408 bool NonFlagUse = false;
9409 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9410 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9412 unsigned UOpNo = UI.getOperandNo();
9413 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9414 // Look pass truncate.
9415 UOpNo = User->use_begin().getOperandNo();
9416 User = *User->use_begin();
9419 if (User->getOpcode() != ISD::BRCOND &&
9420 User->getOpcode() != ISD::SETCC &&
9421 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9434 // Due to the ISEL shortcoming noted above, be conservative if this op is
9435 // likely to be selected as part of a load-modify-store instruction.
9436 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9437 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9438 if (UI->getOpcode() == ISD::STORE)
9441 // Otherwise use a regular EFLAGS-setting instruction.
9442 switch (ArithOp.getOpcode()) {
9443 default: llvm_unreachable("unexpected operator!");
9444 case ISD::SUB: Opcode = X86ISD::SUB; break;
9445 case ISD::XOR: Opcode = X86ISD::XOR; break;
9446 case ISD::AND: Opcode = X86ISD::AND; break;
9448 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9449 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9450 if (EFLAGS.getNode())
9453 Opcode = X86ISD::OR;
9467 return SDValue(Op.getNode(), 1);
9473 // If we found that truncation is beneficial, perform the truncation and
9475 if (NeedTruncation) {
9476 EVT VT = Op.getValueType();
9477 SDValue WideVal = Op->getOperand(0);
9478 EVT WideVT = WideVal.getValueType();
9479 unsigned ConvertedOp = 0;
9480 // Use a target machine opcode to prevent further DAGCombine
9481 // optimizations that may separate the arithmetic operations
9482 // from the setcc node.
9483 switch (WideVal.getOpcode()) {
9485 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9486 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9487 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9488 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9489 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9493 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9494 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9495 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9496 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9497 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9503 // Emit a CMP with 0, which is the TEST pattern.
9504 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9505 DAG.getConstant(0, Op.getValueType()));
9507 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9508 SmallVector<SDValue, 4> Ops;
9509 for (unsigned i = 0; i != NumOperands; ++i)
9510 Ops.push_back(Op.getOperand(i));
9512 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9513 DAG.ReplaceAllUsesWith(Op, New);
9514 return SDValue(New.getNode(), 1);
9517 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9519 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9520 SelectionDAG &DAG) const {
9521 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9522 if (C->getAPIntValue() == 0)
9523 return EmitTest(Op0, X86CC, DAG);
9526 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9527 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9528 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9529 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9530 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9532 return SDValue(Sub.getNode(), 1);
9534 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9537 /// Convert a comparison if required by the subtarget.
9538 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9539 SelectionDAG &DAG) const {
9540 // If the subtarget does not support the FUCOMI instruction, floating-point
9541 // comparisons have to be converted.
9542 if (Subtarget->hasCMov() ||
9543 Cmp.getOpcode() != X86ISD::CMP ||
9544 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9545 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9548 // The instruction selector will select an FUCOM instruction instead of
9549 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9550 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9551 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9553 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9554 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9555 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9556 DAG.getConstant(8, MVT::i8));
9557 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9558 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9561 static bool isAllOnes(SDValue V) {
9562 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9563 return C && C->isAllOnesValue();
9566 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9567 /// if it's possible.
9568 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9569 SDLoc dl, SelectionDAG &DAG) const {
9570 SDValue Op0 = And.getOperand(0);
9571 SDValue Op1 = And.getOperand(1);
9572 if (Op0.getOpcode() == ISD::TRUNCATE)
9573 Op0 = Op0.getOperand(0);
9574 if (Op1.getOpcode() == ISD::TRUNCATE)
9575 Op1 = Op1.getOperand(0);
9578 if (Op1.getOpcode() == ISD::SHL)
9579 std::swap(Op0, Op1);
9580 if (Op0.getOpcode() == ISD::SHL) {
9581 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9582 if (And00C->getZExtValue() == 1) {
9583 // If we looked past a truncate, check that it's only truncating away
9585 unsigned BitWidth = Op0.getValueSizeInBits();
9586 unsigned AndBitWidth = And.getValueSizeInBits();
9587 if (BitWidth > AndBitWidth) {
9589 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9590 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9594 RHS = Op0.getOperand(1);
9596 } else if (Op1.getOpcode() == ISD::Constant) {
9597 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9598 uint64_t AndRHSVal = AndRHS->getZExtValue();
9599 SDValue AndLHS = Op0;
9601 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9602 LHS = AndLHS.getOperand(0);
9603 RHS = AndLHS.getOperand(1);
9606 // Use BT if the immediate can't be encoded in a TEST instruction.
9607 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9609 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9613 if (LHS.getNode()) {
9614 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9615 // instruction. Since the shift amount is in-range-or-undefined, we know
9616 // that doing a bittest on the i32 value is ok. We extend to i32 because
9617 // the encoding for the i16 version is larger than the i32 version.
9618 // Also promote i16 to i32 for performance / code size reason.
9619 if (LHS.getValueType() == MVT::i8 ||
9620 LHS.getValueType() == MVT::i16)
9621 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9623 // If the operand types disagree, extend the shift amount to match. Since
9624 // BT ignores high bits (like shifts) we can use anyextend.
9625 if (LHS.getValueType() != RHS.getValueType())
9626 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9628 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9629 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9630 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9631 DAG.getConstant(Cond, MVT::i8), BT);
9637 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9639 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9644 // SSE Condition code mapping:
9653 switch (SetCCOpcode) {
9654 default: llvm_unreachable("Unexpected SETCC condition");
9656 case ISD::SETEQ: SSECC = 0; break;
9658 case ISD::SETGT: Swap = true; // Fallthrough
9660 case ISD::SETOLT: SSECC = 1; break;
9662 case ISD::SETGE: Swap = true; // Fallthrough
9664 case ISD::SETOLE: SSECC = 2; break;
9665 case ISD::SETUO: SSECC = 3; break;
9667 case ISD::SETNE: SSECC = 4; break;
9668 case ISD::SETULE: Swap = true; // Fallthrough
9669 case ISD::SETUGE: SSECC = 5; break;
9670 case ISD::SETULT: Swap = true; // Fallthrough
9671 case ISD::SETUGT: SSECC = 6; break;
9672 case ISD::SETO: SSECC = 7; break;
9674 case ISD::SETONE: SSECC = 8; break;
9677 std::swap(Op0, Op1);
9682 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9683 // ones, and then concatenate the result back.
9684 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9685 MVT VT = Op.getSimpleValueType();
9687 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9688 "Unsupported value type for operation");
9690 unsigned NumElems = VT.getVectorNumElements();
9692 SDValue CC = Op.getOperand(2);
9694 // Extract the LHS vectors
9695 SDValue LHS = Op.getOperand(0);
9696 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9697 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9699 // Extract the RHS vectors
9700 SDValue RHS = Op.getOperand(1);
9701 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9702 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9704 // Issue the operation on the smaller types and concatenate the result back
9705 MVT EltVT = VT.getVectorElementType();
9706 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9707 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9708 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9709 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9712 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9714 SDValue Op0 = Op.getOperand(0);
9715 SDValue Op1 = Op.getOperand(1);
9716 SDValue CC = Op.getOperand(2);
9717 MVT VT = Op.getSimpleValueType();
9719 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9720 Op.getValueType().getScalarType() == MVT::i1 &&
9721 "Cannot set masked compare for this operation");
9723 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9726 bool Unsigned = false;
9728 switch (SetCCOpcode) {
9729 default: llvm_unreachable("Unexpected SETCC condition");
9730 case ISD::SETNE: SSECC = 4; break;
9731 case ISD::SETEQ: SSECC = 0; break;
9732 case ISD::SETUGT: Unsigned = true;
9733 case ISD::SETGT: SSECC = 6; break; // NLE
9734 case ISD::SETULT: Unsigned = true;
9735 case ISD::SETLT: SSECC = 1; break;
9736 case ISD::SETUGE: Unsigned = true;
9737 case ISD::SETGE: SSECC = 5; break; // NLT
9738 case ISD::SETULE: Unsigned = true;
9739 case ISD::SETLE: SSECC = 2; break;
9741 unsigned Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9742 return DAG.getNode(Opc, dl, VT, Op0, Op1,
9743 DAG.getConstant(SSECC, MVT::i8));
9747 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9748 SelectionDAG &DAG) {
9750 SDValue Op0 = Op.getOperand(0);
9751 SDValue Op1 = Op.getOperand(1);
9752 SDValue CC = Op.getOperand(2);
9753 MVT VT = Op.getSimpleValueType();
9754 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9755 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
9760 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
9761 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9764 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9765 unsigned Opc = X86ISD::CMPP;
9766 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
9767 assert(VT.getVectorNumElements() <= 16);
9770 // In the two special cases we can't handle, emit two comparisons.
9773 unsigned CombineOpc;
9774 if (SetCCOpcode == ISD::SETUEQ) {
9775 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9777 assert(SetCCOpcode == ISD::SETONE);
9778 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9781 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9782 DAG.getConstant(CC0, MVT::i8));
9783 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9784 DAG.getConstant(CC1, MVT::i8));
9785 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9787 // Handle all other FP comparisons here.
9788 return DAG.getNode(Opc, dl, VT, Op0, Op1,
9789 DAG.getConstant(SSECC, MVT::i8));
9792 // Break 256-bit integer vector compare into smaller ones.
9793 if (VT.is256BitVector() && !Subtarget->hasInt256())
9794 return Lower256IntVSETCC(Op, DAG);
9796 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
9797 EVT OpVT = Op1.getValueType();
9798 if (Subtarget->hasAVX512()) {
9799 if (Op1.getValueType().is512BitVector() ||
9800 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
9801 return LowerIntVSETCC_AVX512(Op, DAG);
9803 // In AVX-512 architecture setcc returns mask with i1 elements,
9804 // But there is no compare instruction for i8 and i16 elements.
9805 // We are not talking about 512-bit operands in this case, these
9806 // types are illegal.
9808 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
9809 OpVT.getVectorElementType().getSizeInBits() >= 8))
9810 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9811 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
9814 // We are handling one of the integer comparisons here. Since SSE only has
9815 // GT and EQ comparisons for integer, swapping operands and multiple
9816 // operations may be required for some comparisons.
9818 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9820 switch (SetCCOpcode) {
9821 default: llvm_unreachable("Unexpected SETCC condition");
9822 case ISD::SETNE: Invert = true;
9823 case ISD::SETEQ: Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
9824 case ISD::SETLT: Swap = true;
9825 case ISD::SETGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
9826 case ISD::SETGE: Swap = true;
9827 case ISD::SETLE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9828 Invert = true; break;
9829 case ISD::SETULT: Swap = true;
9830 case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9831 FlipSigns = true; break;
9832 case ISD::SETUGE: Swap = true;
9833 case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9834 FlipSigns = true; Invert = true; break;
9837 // Special case: Use min/max operations for SETULE/SETUGE
9838 MVT VET = VT.getVectorElementType();
9840 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9841 || (Subtarget->hasSSE2() && (VET == MVT::i8));
9844 switch (SetCCOpcode) {
9846 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9847 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9850 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9854 std::swap(Op0, Op1);
9856 // Check that the operation in question is available (most are plain SSE2,
9857 // but PCMPGTQ and PCMPEQQ have different requirements).
9858 if (VT == MVT::v2i64) {
9859 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9860 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9862 // First cast everything to the right type.
9863 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9864 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9866 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9867 // bits of the inputs before performing those operations. The lower
9868 // compare is always unsigned.
9871 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9873 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9874 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9875 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9876 Sign, Zero, Sign, Zero);
9878 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9879 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9881 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9882 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9883 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9885 // Create masks for only the low parts/high parts of the 64 bit integers.
9886 static const int MaskHi[] = { 1, 1, 3, 3 };
9887 static const int MaskLo[] = { 0, 0, 2, 2 };
9888 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9889 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9890 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9892 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9893 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9896 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9898 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9901 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9902 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9903 // pcmpeqd + pshufd + pand.
9904 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9906 // First cast everything to the right type.
9907 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9908 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9911 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9913 // Make sure the lower and upper halves are both all-ones.
9914 static const int Mask[] = { 1, 0, 3, 2 };
9915 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9916 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9919 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9921 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9925 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9926 // bits of the inputs before performing those operations.
9928 EVT EltVT = VT.getVectorElementType();
9929 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9930 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9931 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9934 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9936 // If the logical-not of the result is required, perform that now.
9938 Result = DAG.getNOT(dl, Result, VT);
9941 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9946 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9948 MVT VT = Op.getSimpleValueType();
9950 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9952 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9953 SDValue Op0 = Op.getOperand(0);
9954 SDValue Op1 = Op.getOperand(1);
9956 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9958 // Optimize to BT if possible.
9959 // Lower (X & (1 << N)) == 0 to BT(X, N).
9960 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9961 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9962 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9963 Op1.getOpcode() == ISD::Constant &&
9964 cast<ConstantSDNode>(Op1)->isNullValue() &&
9965 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9966 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9967 if (NewSetCC.getNode())
9971 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9973 if (Op1.getOpcode() == ISD::Constant &&
9974 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9975 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9976 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9978 // If the input is a setcc, then reuse the input setcc or use a new one with
9979 // the inverted condition.
9980 if (Op0.getOpcode() == X86ISD::SETCC) {
9981 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9982 bool Invert = (CC == ISD::SETNE) ^
9983 cast<ConstantSDNode>(Op1)->isNullValue();
9984 if (!Invert) return Op0;
9986 CCode = X86::GetOppositeBranchCondition(CCode);
9987 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9988 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9992 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
9993 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9994 if (X86CC == X86::COND_INVALID)
9997 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9998 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9999 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10000 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10003 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10004 static bool isX86LogicalCmp(SDValue Op) {
10005 unsigned Opc = Op.getNode()->getOpcode();
10006 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10007 Opc == X86ISD::SAHF)
10009 if (Op.getResNo() == 1 &&
10010 (Opc == X86ISD::ADD ||
10011 Opc == X86ISD::SUB ||
10012 Opc == X86ISD::ADC ||
10013 Opc == X86ISD::SBB ||
10014 Opc == X86ISD::SMUL ||
10015 Opc == X86ISD::UMUL ||
10016 Opc == X86ISD::INC ||
10017 Opc == X86ISD::DEC ||
10018 Opc == X86ISD::OR ||
10019 Opc == X86ISD::XOR ||
10020 Opc == X86ISD::AND))
10023 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10029 static bool isZero(SDValue V) {
10030 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10031 return C && C->isNullValue();
10034 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10035 if (V.getOpcode() != ISD::TRUNCATE)
10038 SDValue VOp0 = V.getOperand(0);
10039 unsigned InBits = VOp0.getValueSizeInBits();
10040 unsigned Bits = V.getValueSizeInBits();
10041 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10044 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10045 bool addTest = true;
10046 SDValue Cond = Op.getOperand(0);
10047 SDValue Op1 = Op.getOperand(1);
10048 SDValue Op2 = Op.getOperand(2);
10050 EVT VT = Op1.getValueType();
10053 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10054 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10055 // sequence later on.
10056 if (Cond.getOpcode() == ISD::SETCC &&
10057 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10058 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10059 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10060 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10061 int SSECC = translateX86FSETCC(
10062 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10065 unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
10066 SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
10067 DAG.getConstant(SSECC, MVT::i8));
10068 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10069 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10070 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10074 if (Cond.getOpcode() == ISD::SETCC) {
10075 SDValue NewCond = LowerSETCC(Cond, DAG);
10076 if (NewCond.getNode())
10080 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10081 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10082 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10083 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10084 if (Cond.getOpcode() == X86ISD::SETCC &&
10085 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10086 isZero(Cond.getOperand(1).getOperand(1))) {
10087 SDValue Cmp = Cond.getOperand(1);
10089 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10091 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10092 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10093 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10095 SDValue CmpOp0 = Cmp.getOperand(0);
10096 // Apply further optimizations for special cases
10097 // (select (x != 0), -1, 0) -> neg & sbb
10098 // (select (x == 0), 0, -1) -> neg & sbb
10099 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10100 if (YC->isNullValue() &&
10101 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10102 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10103 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10104 DAG.getConstant(0, CmpOp0.getValueType()),
10106 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10107 DAG.getConstant(X86::COND_B, MVT::i8),
10108 SDValue(Neg.getNode(), 1));
10112 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10113 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10114 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10116 SDValue Res = // Res = 0 or -1.
10117 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10118 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10120 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10121 Res = DAG.getNOT(DL, Res, Res.getValueType());
10123 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10124 if (N2C == 0 || !N2C->isNullValue())
10125 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10130 // Look past (and (setcc_carry (cmp ...)), 1).
10131 if (Cond.getOpcode() == ISD::AND &&
10132 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10133 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10134 if (C && C->getAPIntValue() == 1)
10135 Cond = Cond.getOperand(0);
10138 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10139 // setting operand in place of the X86ISD::SETCC.
10140 unsigned CondOpcode = Cond.getOpcode();
10141 if (CondOpcode == X86ISD::SETCC ||
10142 CondOpcode == X86ISD::SETCC_CARRY) {
10143 CC = Cond.getOperand(0);
10145 SDValue Cmp = Cond.getOperand(1);
10146 unsigned Opc = Cmp.getOpcode();
10147 MVT VT = Op.getSimpleValueType();
10149 bool IllegalFPCMov = false;
10150 if (VT.isFloatingPoint() && !VT.isVector() &&
10151 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10152 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10154 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10155 Opc == X86ISD::BT) { // FIXME
10159 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10160 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10161 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10162 Cond.getOperand(0).getValueType() != MVT::i8)) {
10163 SDValue LHS = Cond.getOperand(0);
10164 SDValue RHS = Cond.getOperand(1);
10165 unsigned X86Opcode;
10168 switch (CondOpcode) {
10169 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10170 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10171 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10172 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10173 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10174 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10175 default: llvm_unreachable("unexpected overflowing operator");
10177 if (CondOpcode == ISD::UMULO)
10178 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10181 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10183 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10185 if (CondOpcode == ISD::UMULO)
10186 Cond = X86Op.getValue(2);
10188 Cond = X86Op.getValue(1);
10190 CC = DAG.getConstant(X86Cond, MVT::i8);
10195 // Look pass the truncate if the high bits are known zero.
10196 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10197 Cond = Cond.getOperand(0);
10199 // We know the result of AND is compared against zero. Try to match
10201 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10202 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10203 if (NewSetCC.getNode()) {
10204 CC = NewSetCC.getOperand(0);
10205 Cond = NewSetCC.getOperand(1);
10212 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10213 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10216 // a < b ? -1 : 0 -> RES = ~setcc_carry
10217 // a < b ? 0 : -1 -> RES = setcc_carry
10218 // a >= b ? -1 : 0 -> RES = setcc_carry
10219 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10220 if (Cond.getOpcode() == X86ISD::SUB) {
10221 Cond = ConvertCmpIfNecessary(Cond, DAG);
10222 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10224 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10225 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10226 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10227 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10228 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10229 return DAG.getNOT(DL, Res, Res.getValueType());
10234 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10235 // widen the cmov and push the truncate through. This avoids introducing a new
10236 // branch during isel and doesn't add any extensions.
10237 if (Op.getValueType() == MVT::i8 &&
10238 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10239 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10240 if (T1.getValueType() == T2.getValueType() &&
10241 // Blacklist CopyFromReg to avoid partial register stalls.
10242 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10243 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10244 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10245 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10249 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10250 // condition is true.
10251 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10252 SDValue Ops[] = { Op2, Op1, CC, Cond };
10253 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10256 SDValue X86TargetLowering::LowerSIGN_EXTEND_AVX512(SDValue Op,
10257 SelectionDAG &DAG) const {
10258 EVT VT = Op->getValueType(0);
10259 SDValue In = Op->getOperand(0);
10260 EVT InVT = In.getValueType();
10263 if (InVT.getVectorElementType().getSizeInBits() >=8 &&
10264 VT.getVectorElementType().getSizeInBits() >= 32)
10265 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10267 if (InVT.getVectorElementType() == MVT::i1) {
10268 unsigned int NumElts = InVT.getVectorNumElements();
10269 assert ((NumElts == 8 || NumElts == 16) &&
10270 "Unsupported SIGN_EXTEND operation");
10271 if (VT.getVectorElementType().getSizeInBits() >= 32) {
10273 ConstantInt::get(*DAG.getContext(),
10274 (NumElts == 8)? APInt(64, ~0ULL): APInt(32, ~0U));
10275 SDValue CP = DAG.getConstantPool(C, getPointerTy());
10276 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10277 SDValue Ld = DAG.getLoad(VT.getScalarType(), dl, DAG.getEntryNode(), CP,
10278 MachinePointerInfo::getConstantPool(),
10279 false, false, false, Alignment);
10280 return DAG.getNode(X86ISD::VBROADCASTM, dl, VT, In, Ld);
10286 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10287 SelectionDAG &DAG) const {
10288 MVT VT = Op->getSimpleValueType(0);
10289 SDValue In = Op->getOperand(0);
10290 MVT InVT = In.getSimpleValueType();
10293 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10294 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10296 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10297 (VT != MVT::v8i32 || InVT != MVT::v8i16))
10300 if (Subtarget->hasInt256())
10301 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10303 // Optimize vectors in AVX mode
10304 // Sign extend v8i16 to v8i32 and
10307 // Divide input vector into two parts
10308 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10309 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10310 // concat the vectors to original VT
10312 unsigned NumElems = InVT.getVectorNumElements();
10313 SDValue Undef = DAG.getUNDEF(InVT);
10315 SmallVector<int,8> ShufMask1(NumElems, -1);
10316 for (unsigned i = 0; i != NumElems/2; ++i)
10319 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10321 SmallVector<int,8> ShufMask2(NumElems, -1);
10322 for (unsigned i = 0; i != NumElems/2; ++i)
10323 ShufMask2[i] = i + NumElems/2;
10325 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10327 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10328 VT.getVectorNumElements()/2);
10330 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10331 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10333 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10336 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10337 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10338 // from the AND / OR.
10339 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10340 Opc = Op.getOpcode();
10341 if (Opc != ISD::OR && Opc != ISD::AND)
10343 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10344 Op.getOperand(0).hasOneUse() &&
10345 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10346 Op.getOperand(1).hasOneUse());
10349 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10350 // 1 and that the SETCC node has a single use.
10351 static bool isXor1OfSetCC(SDValue Op) {
10352 if (Op.getOpcode() != ISD::XOR)
10354 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10355 if (N1C && N1C->getAPIntValue() == 1) {
10356 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10357 Op.getOperand(0).hasOneUse();
10362 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10363 bool addTest = true;
10364 SDValue Chain = Op.getOperand(0);
10365 SDValue Cond = Op.getOperand(1);
10366 SDValue Dest = Op.getOperand(2);
10369 bool Inverted = false;
10371 if (Cond.getOpcode() == ISD::SETCC) {
10372 // Check for setcc([su]{add,sub,mul}o == 0).
10373 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10374 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10375 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10376 Cond.getOperand(0).getResNo() == 1 &&
10377 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10378 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10379 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10380 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10381 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10382 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10384 Cond = Cond.getOperand(0);
10386 SDValue NewCond = LowerSETCC(Cond, DAG);
10387 if (NewCond.getNode())
10392 // FIXME: LowerXALUO doesn't handle these!!
10393 else if (Cond.getOpcode() == X86ISD::ADD ||
10394 Cond.getOpcode() == X86ISD::SUB ||
10395 Cond.getOpcode() == X86ISD::SMUL ||
10396 Cond.getOpcode() == X86ISD::UMUL)
10397 Cond = LowerXALUO(Cond, DAG);
10400 // Look pass (and (setcc_carry (cmp ...)), 1).
10401 if (Cond.getOpcode() == ISD::AND &&
10402 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10403 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10404 if (C && C->getAPIntValue() == 1)
10405 Cond = Cond.getOperand(0);
10408 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10409 // setting operand in place of the X86ISD::SETCC.
10410 unsigned CondOpcode = Cond.getOpcode();
10411 if (CondOpcode == X86ISD::SETCC ||
10412 CondOpcode == X86ISD::SETCC_CARRY) {
10413 CC = Cond.getOperand(0);
10415 SDValue Cmp = Cond.getOperand(1);
10416 unsigned Opc = Cmp.getOpcode();
10417 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10418 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10422 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10426 // These can only come from an arithmetic instruction with overflow,
10427 // e.g. SADDO, UADDO.
10428 Cond = Cond.getNode()->getOperand(1);
10434 CondOpcode = Cond.getOpcode();
10435 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10436 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10437 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10438 Cond.getOperand(0).getValueType() != MVT::i8)) {
10439 SDValue LHS = Cond.getOperand(0);
10440 SDValue RHS = Cond.getOperand(1);
10441 unsigned X86Opcode;
10444 switch (CondOpcode) {
10445 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10446 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10447 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10448 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10449 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10450 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10451 default: llvm_unreachable("unexpected overflowing operator");
10454 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10455 if (CondOpcode == ISD::UMULO)
10456 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10459 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10461 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10463 if (CondOpcode == ISD::UMULO)
10464 Cond = X86Op.getValue(2);
10466 Cond = X86Op.getValue(1);
10468 CC = DAG.getConstant(X86Cond, MVT::i8);
10472 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10473 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10474 if (CondOpc == ISD::OR) {
10475 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10476 // two branches instead of an explicit OR instruction with a
10478 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10479 isX86LogicalCmp(Cmp)) {
10480 CC = Cond.getOperand(0).getOperand(0);
10481 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10482 Chain, Dest, CC, Cmp);
10483 CC = Cond.getOperand(1).getOperand(0);
10487 } else { // ISD::AND
10488 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10489 // two branches instead of an explicit AND instruction with a
10490 // separate test. However, we only do this if this block doesn't
10491 // have a fall-through edge, because this requires an explicit
10492 // jmp when the condition is false.
10493 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10494 isX86LogicalCmp(Cmp) &&
10495 Op.getNode()->hasOneUse()) {
10496 X86::CondCode CCode =
10497 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10498 CCode = X86::GetOppositeBranchCondition(CCode);
10499 CC = DAG.getConstant(CCode, MVT::i8);
10500 SDNode *User = *Op.getNode()->use_begin();
10501 // Look for an unconditional branch following this conditional branch.
10502 // We need this because we need to reverse the successors in order
10503 // to implement FCMP_OEQ.
10504 if (User->getOpcode() == ISD::BR) {
10505 SDValue FalseBB = User->getOperand(1);
10507 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10508 assert(NewBR == User);
10512 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10513 Chain, Dest, CC, Cmp);
10514 X86::CondCode CCode =
10515 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10516 CCode = X86::GetOppositeBranchCondition(CCode);
10517 CC = DAG.getConstant(CCode, MVT::i8);
10523 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10524 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10525 // It should be transformed during dag combiner except when the condition
10526 // is set by a arithmetics with overflow node.
10527 X86::CondCode CCode =
10528 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10529 CCode = X86::GetOppositeBranchCondition(CCode);
10530 CC = DAG.getConstant(CCode, MVT::i8);
10531 Cond = Cond.getOperand(0).getOperand(1);
10533 } else if (Cond.getOpcode() == ISD::SETCC &&
10534 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10535 // For FCMP_OEQ, we can emit
10536 // two branches instead of an explicit AND instruction with a
10537 // separate test. However, we only do this if this block doesn't
10538 // have a fall-through edge, because this requires an explicit
10539 // jmp when the condition is false.
10540 if (Op.getNode()->hasOneUse()) {
10541 SDNode *User = *Op.getNode()->use_begin();
10542 // Look for an unconditional branch following this conditional branch.
10543 // We need this because we need to reverse the successors in order
10544 // to implement FCMP_OEQ.
10545 if (User->getOpcode() == ISD::BR) {
10546 SDValue FalseBB = User->getOperand(1);
10548 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10549 assert(NewBR == User);
10553 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10554 Cond.getOperand(0), Cond.getOperand(1));
10555 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10556 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10557 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10558 Chain, Dest, CC, Cmp);
10559 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10564 } else if (Cond.getOpcode() == ISD::SETCC &&
10565 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10566 // For FCMP_UNE, we can emit
10567 // two branches instead of an explicit AND instruction with a
10568 // separate test. However, we only do this if this block doesn't
10569 // have a fall-through edge, because this requires an explicit
10570 // jmp when the condition is false.
10571 if (Op.getNode()->hasOneUse()) {
10572 SDNode *User = *Op.getNode()->use_begin();
10573 // Look for an unconditional branch following this conditional branch.
10574 // We need this because we need to reverse the successors in order
10575 // to implement FCMP_UNE.
10576 if (User->getOpcode() == ISD::BR) {
10577 SDValue FalseBB = User->getOperand(1);
10579 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10580 assert(NewBR == User);
10583 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10584 Cond.getOperand(0), Cond.getOperand(1));
10585 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10586 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10587 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10588 Chain, Dest, CC, Cmp);
10589 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10599 // Look pass the truncate if the high bits are known zero.
10600 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10601 Cond = Cond.getOperand(0);
10603 // We know the result of AND is compared against zero. Try to match
10605 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10606 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10607 if (NewSetCC.getNode()) {
10608 CC = NewSetCC.getOperand(0);
10609 Cond = NewSetCC.getOperand(1);
10616 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10617 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10619 Cond = ConvertCmpIfNecessary(Cond, DAG);
10620 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10621 Chain, Dest, CC, Cond);
10624 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10625 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10626 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10627 // that the guard pages used by the OS virtual memory manager are allocated in
10628 // correct sequence.
10630 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10631 SelectionDAG &DAG) const {
10632 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10633 getTargetMachine().Options.EnableSegmentedStacks) &&
10634 "This should be used only on Windows targets or when segmented stacks "
10636 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10640 SDValue Chain = Op.getOperand(0);
10641 SDValue Size = Op.getOperand(1);
10642 // FIXME: Ensure alignment here
10644 bool Is64Bit = Subtarget->is64Bit();
10645 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10647 if (getTargetMachine().Options.EnableSegmentedStacks) {
10648 MachineFunction &MF = DAG.getMachineFunction();
10649 MachineRegisterInfo &MRI = MF.getRegInfo();
10652 // The 64 bit implementation of segmented stacks needs to clobber both r10
10653 // r11. This makes it impossible to use it along with nested parameters.
10654 const Function *F = MF.getFunction();
10656 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10658 if (I->hasNestAttr())
10659 report_fatal_error("Cannot use segmented stacks with functions that "
10660 "have nested arguments.");
10663 const TargetRegisterClass *AddrRegClass =
10664 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10665 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10666 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10667 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10668 DAG.getRegister(Vreg, SPTy));
10669 SDValue Ops1[2] = { Value, Chain };
10670 return DAG.getMergeValues(Ops1, 2, dl);
10673 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10675 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10676 Flag = Chain.getValue(1);
10677 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10679 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10680 Flag = Chain.getValue(1);
10682 const X86RegisterInfo *RegInfo =
10683 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10684 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10687 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10688 return DAG.getMergeValues(Ops1, 2, dl);
10692 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10693 MachineFunction &MF = DAG.getMachineFunction();
10694 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10696 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10699 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10700 // vastart just stores the address of the VarArgsFrameIndex slot into the
10701 // memory location argument.
10702 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10704 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10705 MachinePointerInfo(SV), false, false, 0);
10709 // gp_offset (0 - 6 * 8)
10710 // fp_offset (48 - 48 + 8 * 16)
10711 // overflow_arg_area (point to parameters coming in memory).
10713 SmallVector<SDValue, 8> MemOps;
10714 SDValue FIN = Op.getOperand(1);
10716 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10717 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10719 FIN, MachinePointerInfo(SV), false, false, 0);
10720 MemOps.push_back(Store);
10723 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10724 FIN, DAG.getIntPtrConstant(4));
10725 Store = DAG.getStore(Op.getOperand(0), DL,
10726 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10728 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10729 MemOps.push_back(Store);
10731 // Store ptr to overflow_arg_area
10732 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10733 FIN, DAG.getIntPtrConstant(4));
10734 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10736 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10737 MachinePointerInfo(SV, 8),
10739 MemOps.push_back(Store);
10741 // Store ptr to reg_save_area.
10742 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10743 FIN, DAG.getIntPtrConstant(8));
10744 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10746 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10747 MachinePointerInfo(SV, 16), false, false, 0);
10748 MemOps.push_back(Store);
10749 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10750 &MemOps[0], MemOps.size());
10753 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10754 assert(Subtarget->is64Bit() &&
10755 "LowerVAARG only handles 64-bit va_arg!");
10756 assert((Subtarget->isTargetLinux() ||
10757 Subtarget->isTargetDarwin()) &&
10758 "Unhandled target in LowerVAARG");
10759 assert(Op.getNode()->getNumOperands() == 4);
10760 SDValue Chain = Op.getOperand(0);
10761 SDValue SrcPtr = Op.getOperand(1);
10762 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10763 unsigned Align = Op.getConstantOperandVal(3);
10766 EVT ArgVT = Op.getNode()->getValueType(0);
10767 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10768 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10771 // Decide which area this value should be read from.
10772 // TODO: Implement the AMD64 ABI in its entirety. This simple
10773 // selection mechanism works only for the basic types.
10774 if (ArgVT == MVT::f80) {
10775 llvm_unreachable("va_arg for f80 not yet implemented");
10776 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10777 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10778 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10779 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10781 llvm_unreachable("Unhandled argument type in LowerVAARG");
10784 if (ArgMode == 2) {
10785 // Sanity Check: Make sure using fp_offset makes sense.
10786 assert(!getTargetMachine().Options.UseSoftFloat &&
10787 !(DAG.getMachineFunction()
10788 .getFunction()->getAttributes()
10789 .hasAttribute(AttributeSet::FunctionIndex,
10790 Attribute::NoImplicitFloat)) &&
10791 Subtarget->hasSSE1());
10794 // Insert VAARG_64 node into the DAG
10795 // VAARG_64 returns two values: Variable Argument Address, Chain
10796 SmallVector<SDValue, 11> InstOps;
10797 InstOps.push_back(Chain);
10798 InstOps.push_back(SrcPtr);
10799 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10800 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10801 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10802 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10803 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10804 VTs, &InstOps[0], InstOps.size(),
10806 MachinePointerInfo(SV),
10808 /*Volatile=*/false,
10810 /*WriteMem=*/true);
10811 Chain = VAARG.getValue(1);
10813 // Load the next argument and return it
10814 return DAG.getLoad(ArgVT, dl,
10817 MachinePointerInfo(),
10818 false, false, false, 0);
10821 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10822 SelectionDAG &DAG) {
10823 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10824 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10825 SDValue Chain = Op.getOperand(0);
10826 SDValue DstPtr = Op.getOperand(1);
10827 SDValue SrcPtr = Op.getOperand(2);
10828 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10829 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10832 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10833 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10835 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10838 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10839 // may or may not be a constant. Takes immediate version of shift as input.
10840 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10841 SDValue SrcOp, SDValue ShAmt,
10842 SelectionDAG &DAG) {
10843 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10845 if (isa<ConstantSDNode>(ShAmt)) {
10846 // Constant may be a TargetConstant. Use a regular constant.
10847 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10849 default: llvm_unreachable("Unknown target vector shift node");
10850 case X86ISD::VSHLI:
10851 case X86ISD::VSRLI:
10852 case X86ISD::VSRAI:
10853 return DAG.getNode(Opc, dl, VT, SrcOp,
10854 DAG.getConstant(ShiftAmt, MVT::i32));
10858 // Change opcode to non-immediate version
10860 default: llvm_unreachable("Unknown target vector shift node");
10861 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10862 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10863 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10866 // Need to build a vector containing shift amount
10867 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10870 ShOps[1] = DAG.getConstant(0, MVT::i32);
10871 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10872 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10874 // The return type has to be a 128-bit type with the same element
10875 // type as the input type.
10876 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10877 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10879 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10880 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10883 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10885 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10887 default: return SDValue(); // Don't custom lower most intrinsics.
10888 // Comparison intrinsics.
10889 case Intrinsic::x86_sse_comieq_ss:
10890 case Intrinsic::x86_sse_comilt_ss:
10891 case Intrinsic::x86_sse_comile_ss:
10892 case Intrinsic::x86_sse_comigt_ss:
10893 case Intrinsic::x86_sse_comige_ss:
10894 case Intrinsic::x86_sse_comineq_ss:
10895 case Intrinsic::x86_sse_ucomieq_ss:
10896 case Intrinsic::x86_sse_ucomilt_ss:
10897 case Intrinsic::x86_sse_ucomile_ss:
10898 case Intrinsic::x86_sse_ucomigt_ss:
10899 case Intrinsic::x86_sse_ucomige_ss:
10900 case Intrinsic::x86_sse_ucomineq_ss:
10901 case Intrinsic::x86_sse2_comieq_sd:
10902 case Intrinsic::x86_sse2_comilt_sd:
10903 case Intrinsic::x86_sse2_comile_sd:
10904 case Intrinsic::x86_sse2_comigt_sd:
10905 case Intrinsic::x86_sse2_comige_sd:
10906 case Intrinsic::x86_sse2_comineq_sd:
10907 case Intrinsic::x86_sse2_ucomieq_sd:
10908 case Intrinsic::x86_sse2_ucomilt_sd:
10909 case Intrinsic::x86_sse2_ucomile_sd:
10910 case Intrinsic::x86_sse2_ucomigt_sd:
10911 case Intrinsic::x86_sse2_ucomige_sd:
10912 case Intrinsic::x86_sse2_ucomineq_sd: {
10916 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10917 case Intrinsic::x86_sse_comieq_ss:
10918 case Intrinsic::x86_sse2_comieq_sd:
10919 Opc = X86ISD::COMI;
10922 case Intrinsic::x86_sse_comilt_ss:
10923 case Intrinsic::x86_sse2_comilt_sd:
10924 Opc = X86ISD::COMI;
10927 case Intrinsic::x86_sse_comile_ss:
10928 case Intrinsic::x86_sse2_comile_sd:
10929 Opc = X86ISD::COMI;
10932 case Intrinsic::x86_sse_comigt_ss:
10933 case Intrinsic::x86_sse2_comigt_sd:
10934 Opc = X86ISD::COMI;
10937 case Intrinsic::x86_sse_comige_ss:
10938 case Intrinsic::x86_sse2_comige_sd:
10939 Opc = X86ISD::COMI;
10942 case Intrinsic::x86_sse_comineq_ss:
10943 case Intrinsic::x86_sse2_comineq_sd:
10944 Opc = X86ISD::COMI;
10947 case Intrinsic::x86_sse_ucomieq_ss:
10948 case Intrinsic::x86_sse2_ucomieq_sd:
10949 Opc = X86ISD::UCOMI;
10952 case Intrinsic::x86_sse_ucomilt_ss:
10953 case Intrinsic::x86_sse2_ucomilt_sd:
10954 Opc = X86ISD::UCOMI;
10957 case Intrinsic::x86_sse_ucomile_ss:
10958 case Intrinsic::x86_sse2_ucomile_sd:
10959 Opc = X86ISD::UCOMI;
10962 case Intrinsic::x86_sse_ucomigt_ss:
10963 case Intrinsic::x86_sse2_ucomigt_sd:
10964 Opc = X86ISD::UCOMI;
10967 case Intrinsic::x86_sse_ucomige_ss:
10968 case Intrinsic::x86_sse2_ucomige_sd:
10969 Opc = X86ISD::UCOMI;
10972 case Intrinsic::x86_sse_ucomineq_ss:
10973 case Intrinsic::x86_sse2_ucomineq_sd:
10974 Opc = X86ISD::UCOMI;
10979 SDValue LHS = Op.getOperand(1);
10980 SDValue RHS = Op.getOperand(2);
10981 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10982 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10983 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10984 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10985 DAG.getConstant(X86CC, MVT::i8), Cond);
10986 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10989 // Arithmetic intrinsics.
10990 case Intrinsic::x86_sse2_pmulu_dq:
10991 case Intrinsic::x86_avx2_pmulu_dq:
10992 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10993 Op.getOperand(1), Op.getOperand(2));
10995 // SSE2/AVX2 sub with unsigned saturation intrinsics
10996 case Intrinsic::x86_sse2_psubus_b:
10997 case Intrinsic::x86_sse2_psubus_w:
10998 case Intrinsic::x86_avx2_psubus_b:
10999 case Intrinsic::x86_avx2_psubus_w:
11000 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11001 Op.getOperand(1), Op.getOperand(2));
11003 // SSE3/AVX horizontal add/sub intrinsics
11004 case Intrinsic::x86_sse3_hadd_ps:
11005 case Intrinsic::x86_sse3_hadd_pd:
11006 case Intrinsic::x86_avx_hadd_ps_256:
11007 case Intrinsic::x86_avx_hadd_pd_256:
11008 case Intrinsic::x86_sse3_hsub_ps:
11009 case Intrinsic::x86_sse3_hsub_pd:
11010 case Intrinsic::x86_avx_hsub_ps_256:
11011 case Intrinsic::x86_avx_hsub_pd_256:
11012 case Intrinsic::x86_ssse3_phadd_w_128:
11013 case Intrinsic::x86_ssse3_phadd_d_128:
11014 case Intrinsic::x86_avx2_phadd_w:
11015 case Intrinsic::x86_avx2_phadd_d:
11016 case Intrinsic::x86_ssse3_phsub_w_128:
11017 case Intrinsic::x86_ssse3_phsub_d_128:
11018 case Intrinsic::x86_avx2_phsub_w:
11019 case Intrinsic::x86_avx2_phsub_d: {
11022 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11023 case Intrinsic::x86_sse3_hadd_ps:
11024 case Intrinsic::x86_sse3_hadd_pd:
11025 case Intrinsic::x86_avx_hadd_ps_256:
11026 case Intrinsic::x86_avx_hadd_pd_256:
11027 Opcode = X86ISD::FHADD;
11029 case Intrinsic::x86_sse3_hsub_ps:
11030 case Intrinsic::x86_sse3_hsub_pd:
11031 case Intrinsic::x86_avx_hsub_ps_256:
11032 case Intrinsic::x86_avx_hsub_pd_256:
11033 Opcode = X86ISD::FHSUB;
11035 case Intrinsic::x86_ssse3_phadd_w_128:
11036 case Intrinsic::x86_ssse3_phadd_d_128:
11037 case Intrinsic::x86_avx2_phadd_w:
11038 case Intrinsic::x86_avx2_phadd_d:
11039 Opcode = X86ISD::HADD;
11041 case Intrinsic::x86_ssse3_phsub_w_128:
11042 case Intrinsic::x86_ssse3_phsub_d_128:
11043 case Intrinsic::x86_avx2_phsub_w:
11044 case Intrinsic::x86_avx2_phsub_d:
11045 Opcode = X86ISD::HSUB;
11048 return DAG.getNode(Opcode, dl, Op.getValueType(),
11049 Op.getOperand(1), Op.getOperand(2));
11052 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11053 case Intrinsic::x86_sse2_pmaxu_b:
11054 case Intrinsic::x86_sse41_pmaxuw:
11055 case Intrinsic::x86_sse41_pmaxud:
11056 case Intrinsic::x86_avx2_pmaxu_b:
11057 case Intrinsic::x86_avx2_pmaxu_w:
11058 case Intrinsic::x86_avx2_pmaxu_d:
11059 case Intrinsic::x86_sse2_pminu_b:
11060 case Intrinsic::x86_sse41_pminuw:
11061 case Intrinsic::x86_sse41_pminud:
11062 case Intrinsic::x86_avx2_pminu_b:
11063 case Intrinsic::x86_avx2_pminu_w:
11064 case Intrinsic::x86_avx2_pminu_d:
11065 case Intrinsic::x86_sse41_pmaxsb:
11066 case Intrinsic::x86_sse2_pmaxs_w:
11067 case Intrinsic::x86_sse41_pmaxsd:
11068 case Intrinsic::x86_avx2_pmaxs_b:
11069 case Intrinsic::x86_avx2_pmaxs_w:
11070 case Intrinsic::x86_avx2_pmaxs_d:
11071 case Intrinsic::x86_sse41_pminsb:
11072 case Intrinsic::x86_sse2_pmins_w:
11073 case Intrinsic::x86_sse41_pminsd:
11074 case Intrinsic::x86_avx2_pmins_b:
11075 case Intrinsic::x86_avx2_pmins_w:
11076 case Intrinsic::x86_avx2_pmins_d: {
11079 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11080 case Intrinsic::x86_sse2_pmaxu_b:
11081 case Intrinsic::x86_sse41_pmaxuw:
11082 case Intrinsic::x86_sse41_pmaxud:
11083 case Intrinsic::x86_avx2_pmaxu_b:
11084 case Intrinsic::x86_avx2_pmaxu_w:
11085 case Intrinsic::x86_avx2_pmaxu_d:
11086 Opcode = X86ISD::UMAX;
11088 case Intrinsic::x86_sse2_pminu_b:
11089 case Intrinsic::x86_sse41_pminuw:
11090 case Intrinsic::x86_sse41_pminud:
11091 case Intrinsic::x86_avx2_pminu_b:
11092 case Intrinsic::x86_avx2_pminu_w:
11093 case Intrinsic::x86_avx2_pminu_d:
11094 Opcode = X86ISD::UMIN;
11096 case Intrinsic::x86_sse41_pmaxsb:
11097 case Intrinsic::x86_sse2_pmaxs_w:
11098 case Intrinsic::x86_sse41_pmaxsd:
11099 case Intrinsic::x86_avx2_pmaxs_b:
11100 case Intrinsic::x86_avx2_pmaxs_w:
11101 case Intrinsic::x86_avx2_pmaxs_d:
11102 Opcode = X86ISD::SMAX;
11104 case Intrinsic::x86_sse41_pminsb:
11105 case Intrinsic::x86_sse2_pmins_w:
11106 case Intrinsic::x86_sse41_pminsd:
11107 case Intrinsic::x86_avx2_pmins_b:
11108 case Intrinsic::x86_avx2_pmins_w:
11109 case Intrinsic::x86_avx2_pmins_d:
11110 Opcode = X86ISD::SMIN;
11113 return DAG.getNode(Opcode, dl, Op.getValueType(),
11114 Op.getOperand(1), Op.getOperand(2));
11117 // SSE/SSE2/AVX floating point max/min intrinsics.
11118 case Intrinsic::x86_sse_max_ps:
11119 case Intrinsic::x86_sse2_max_pd:
11120 case Intrinsic::x86_avx_max_ps_256:
11121 case Intrinsic::x86_avx_max_pd_256:
11122 case Intrinsic::x86_sse_min_ps:
11123 case Intrinsic::x86_sse2_min_pd:
11124 case Intrinsic::x86_avx_min_ps_256:
11125 case Intrinsic::x86_avx_min_pd_256: {
11128 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11129 case Intrinsic::x86_sse_max_ps:
11130 case Intrinsic::x86_sse2_max_pd:
11131 case Intrinsic::x86_avx_max_ps_256:
11132 case Intrinsic::x86_avx_max_pd_256:
11133 Opcode = X86ISD::FMAX;
11135 case Intrinsic::x86_sse_min_ps:
11136 case Intrinsic::x86_sse2_min_pd:
11137 case Intrinsic::x86_avx_min_ps_256:
11138 case Intrinsic::x86_avx_min_pd_256:
11139 Opcode = X86ISD::FMIN;
11142 return DAG.getNode(Opcode, dl, Op.getValueType(),
11143 Op.getOperand(1), Op.getOperand(2));
11146 // AVX2 variable shift intrinsics
11147 case Intrinsic::x86_avx2_psllv_d:
11148 case Intrinsic::x86_avx2_psllv_q:
11149 case Intrinsic::x86_avx2_psllv_d_256:
11150 case Intrinsic::x86_avx2_psllv_q_256:
11151 case Intrinsic::x86_avx2_psrlv_d:
11152 case Intrinsic::x86_avx2_psrlv_q:
11153 case Intrinsic::x86_avx2_psrlv_d_256:
11154 case Intrinsic::x86_avx2_psrlv_q_256:
11155 case Intrinsic::x86_avx2_psrav_d:
11156 case Intrinsic::x86_avx2_psrav_d_256: {
11159 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11160 case Intrinsic::x86_avx2_psllv_d:
11161 case Intrinsic::x86_avx2_psllv_q:
11162 case Intrinsic::x86_avx2_psllv_d_256:
11163 case Intrinsic::x86_avx2_psllv_q_256:
11166 case Intrinsic::x86_avx2_psrlv_d:
11167 case Intrinsic::x86_avx2_psrlv_q:
11168 case Intrinsic::x86_avx2_psrlv_d_256:
11169 case Intrinsic::x86_avx2_psrlv_q_256:
11172 case Intrinsic::x86_avx2_psrav_d:
11173 case Intrinsic::x86_avx2_psrav_d_256:
11177 return DAG.getNode(Opcode, dl, Op.getValueType(),
11178 Op.getOperand(1), Op.getOperand(2));
11181 case Intrinsic::x86_ssse3_pshuf_b_128:
11182 case Intrinsic::x86_avx2_pshuf_b:
11183 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11184 Op.getOperand(1), Op.getOperand(2));
11186 case Intrinsic::x86_ssse3_psign_b_128:
11187 case Intrinsic::x86_ssse3_psign_w_128:
11188 case Intrinsic::x86_ssse3_psign_d_128:
11189 case Intrinsic::x86_avx2_psign_b:
11190 case Intrinsic::x86_avx2_psign_w:
11191 case Intrinsic::x86_avx2_psign_d:
11192 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11193 Op.getOperand(1), Op.getOperand(2));
11195 case Intrinsic::x86_sse41_insertps:
11196 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11197 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11199 case Intrinsic::x86_avx_vperm2f128_ps_256:
11200 case Intrinsic::x86_avx_vperm2f128_pd_256:
11201 case Intrinsic::x86_avx_vperm2f128_si_256:
11202 case Intrinsic::x86_avx2_vperm2i128:
11203 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11204 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11206 case Intrinsic::x86_avx2_permd:
11207 case Intrinsic::x86_avx2_permps:
11208 // Operands intentionally swapped. Mask is last operand to intrinsic,
11209 // but second operand for node/intruction.
11210 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11211 Op.getOperand(2), Op.getOperand(1));
11213 case Intrinsic::x86_sse_sqrt_ps:
11214 case Intrinsic::x86_sse2_sqrt_pd:
11215 case Intrinsic::x86_avx_sqrt_ps_256:
11216 case Intrinsic::x86_avx_sqrt_pd_256:
11217 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11219 // ptest and testp intrinsics. The intrinsic these come from are designed to
11220 // return an integer value, not just an instruction so lower it to the ptest
11221 // or testp pattern and a setcc for the result.
11222 case Intrinsic::x86_sse41_ptestz:
11223 case Intrinsic::x86_sse41_ptestc:
11224 case Intrinsic::x86_sse41_ptestnzc:
11225 case Intrinsic::x86_avx_ptestz_256:
11226 case Intrinsic::x86_avx_ptestc_256:
11227 case Intrinsic::x86_avx_ptestnzc_256:
11228 case Intrinsic::x86_avx_vtestz_ps:
11229 case Intrinsic::x86_avx_vtestc_ps:
11230 case Intrinsic::x86_avx_vtestnzc_ps:
11231 case Intrinsic::x86_avx_vtestz_pd:
11232 case Intrinsic::x86_avx_vtestc_pd:
11233 case Intrinsic::x86_avx_vtestnzc_pd:
11234 case Intrinsic::x86_avx_vtestz_ps_256:
11235 case Intrinsic::x86_avx_vtestc_ps_256:
11236 case Intrinsic::x86_avx_vtestnzc_ps_256:
11237 case Intrinsic::x86_avx_vtestz_pd_256:
11238 case Intrinsic::x86_avx_vtestc_pd_256:
11239 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11240 bool IsTestPacked = false;
11243 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11244 case Intrinsic::x86_avx_vtestz_ps:
11245 case Intrinsic::x86_avx_vtestz_pd:
11246 case Intrinsic::x86_avx_vtestz_ps_256:
11247 case Intrinsic::x86_avx_vtestz_pd_256:
11248 IsTestPacked = true; // Fallthrough
11249 case Intrinsic::x86_sse41_ptestz:
11250 case Intrinsic::x86_avx_ptestz_256:
11252 X86CC = X86::COND_E;
11254 case Intrinsic::x86_avx_vtestc_ps:
11255 case Intrinsic::x86_avx_vtestc_pd:
11256 case Intrinsic::x86_avx_vtestc_ps_256:
11257 case Intrinsic::x86_avx_vtestc_pd_256:
11258 IsTestPacked = true; // Fallthrough
11259 case Intrinsic::x86_sse41_ptestc:
11260 case Intrinsic::x86_avx_ptestc_256:
11262 X86CC = X86::COND_B;
11264 case Intrinsic::x86_avx_vtestnzc_ps:
11265 case Intrinsic::x86_avx_vtestnzc_pd:
11266 case Intrinsic::x86_avx_vtestnzc_ps_256:
11267 case Intrinsic::x86_avx_vtestnzc_pd_256:
11268 IsTestPacked = true; // Fallthrough
11269 case Intrinsic::x86_sse41_ptestnzc:
11270 case Intrinsic::x86_avx_ptestnzc_256:
11272 X86CC = X86::COND_A;
11276 SDValue LHS = Op.getOperand(1);
11277 SDValue RHS = Op.getOperand(2);
11278 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11279 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11280 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11281 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11282 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11285 // SSE/AVX shift intrinsics
11286 case Intrinsic::x86_sse2_psll_w:
11287 case Intrinsic::x86_sse2_psll_d:
11288 case Intrinsic::x86_sse2_psll_q:
11289 case Intrinsic::x86_avx2_psll_w:
11290 case Intrinsic::x86_avx2_psll_d:
11291 case Intrinsic::x86_avx2_psll_q:
11292 case Intrinsic::x86_sse2_psrl_w:
11293 case Intrinsic::x86_sse2_psrl_d:
11294 case Intrinsic::x86_sse2_psrl_q:
11295 case Intrinsic::x86_avx2_psrl_w:
11296 case Intrinsic::x86_avx2_psrl_d:
11297 case Intrinsic::x86_avx2_psrl_q:
11298 case Intrinsic::x86_sse2_psra_w:
11299 case Intrinsic::x86_sse2_psra_d:
11300 case Intrinsic::x86_avx2_psra_w:
11301 case Intrinsic::x86_avx2_psra_d: {
11304 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11305 case Intrinsic::x86_sse2_psll_w:
11306 case Intrinsic::x86_sse2_psll_d:
11307 case Intrinsic::x86_sse2_psll_q:
11308 case Intrinsic::x86_avx2_psll_w:
11309 case Intrinsic::x86_avx2_psll_d:
11310 case Intrinsic::x86_avx2_psll_q:
11311 Opcode = X86ISD::VSHL;
11313 case Intrinsic::x86_sse2_psrl_w:
11314 case Intrinsic::x86_sse2_psrl_d:
11315 case Intrinsic::x86_sse2_psrl_q:
11316 case Intrinsic::x86_avx2_psrl_w:
11317 case Intrinsic::x86_avx2_psrl_d:
11318 case Intrinsic::x86_avx2_psrl_q:
11319 Opcode = X86ISD::VSRL;
11321 case Intrinsic::x86_sse2_psra_w:
11322 case Intrinsic::x86_sse2_psra_d:
11323 case Intrinsic::x86_avx2_psra_w:
11324 case Intrinsic::x86_avx2_psra_d:
11325 Opcode = X86ISD::VSRA;
11328 return DAG.getNode(Opcode, dl, Op.getValueType(),
11329 Op.getOperand(1), Op.getOperand(2));
11332 // SSE/AVX immediate shift intrinsics
11333 case Intrinsic::x86_sse2_pslli_w:
11334 case Intrinsic::x86_sse2_pslli_d:
11335 case Intrinsic::x86_sse2_pslli_q:
11336 case Intrinsic::x86_avx2_pslli_w:
11337 case Intrinsic::x86_avx2_pslli_d:
11338 case Intrinsic::x86_avx2_pslli_q:
11339 case Intrinsic::x86_sse2_psrli_w:
11340 case Intrinsic::x86_sse2_psrli_d:
11341 case Intrinsic::x86_sse2_psrli_q:
11342 case Intrinsic::x86_avx2_psrli_w:
11343 case Intrinsic::x86_avx2_psrli_d:
11344 case Intrinsic::x86_avx2_psrli_q:
11345 case Intrinsic::x86_sse2_psrai_w:
11346 case Intrinsic::x86_sse2_psrai_d:
11347 case Intrinsic::x86_avx2_psrai_w:
11348 case Intrinsic::x86_avx2_psrai_d: {
11351 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11352 case Intrinsic::x86_sse2_pslli_w:
11353 case Intrinsic::x86_sse2_pslli_d:
11354 case Intrinsic::x86_sse2_pslli_q:
11355 case Intrinsic::x86_avx2_pslli_w:
11356 case Intrinsic::x86_avx2_pslli_d:
11357 case Intrinsic::x86_avx2_pslli_q:
11358 Opcode = X86ISD::VSHLI;
11360 case Intrinsic::x86_sse2_psrli_w:
11361 case Intrinsic::x86_sse2_psrli_d:
11362 case Intrinsic::x86_sse2_psrli_q:
11363 case Intrinsic::x86_avx2_psrli_w:
11364 case Intrinsic::x86_avx2_psrli_d:
11365 case Intrinsic::x86_avx2_psrli_q:
11366 Opcode = X86ISD::VSRLI;
11368 case Intrinsic::x86_sse2_psrai_w:
11369 case Intrinsic::x86_sse2_psrai_d:
11370 case Intrinsic::x86_avx2_psrai_w:
11371 case Intrinsic::x86_avx2_psrai_d:
11372 Opcode = X86ISD::VSRAI;
11375 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11376 Op.getOperand(1), Op.getOperand(2), DAG);
11379 case Intrinsic::x86_sse42_pcmpistria128:
11380 case Intrinsic::x86_sse42_pcmpestria128:
11381 case Intrinsic::x86_sse42_pcmpistric128:
11382 case Intrinsic::x86_sse42_pcmpestric128:
11383 case Intrinsic::x86_sse42_pcmpistrio128:
11384 case Intrinsic::x86_sse42_pcmpestrio128:
11385 case Intrinsic::x86_sse42_pcmpistris128:
11386 case Intrinsic::x86_sse42_pcmpestris128:
11387 case Intrinsic::x86_sse42_pcmpistriz128:
11388 case Intrinsic::x86_sse42_pcmpestriz128: {
11392 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11393 case Intrinsic::x86_sse42_pcmpistria128:
11394 Opcode = X86ISD::PCMPISTRI;
11395 X86CC = X86::COND_A;
11397 case Intrinsic::x86_sse42_pcmpestria128:
11398 Opcode = X86ISD::PCMPESTRI;
11399 X86CC = X86::COND_A;
11401 case Intrinsic::x86_sse42_pcmpistric128:
11402 Opcode = X86ISD::PCMPISTRI;
11403 X86CC = X86::COND_B;
11405 case Intrinsic::x86_sse42_pcmpestric128:
11406 Opcode = X86ISD::PCMPESTRI;
11407 X86CC = X86::COND_B;
11409 case Intrinsic::x86_sse42_pcmpistrio128:
11410 Opcode = X86ISD::PCMPISTRI;
11411 X86CC = X86::COND_O;
11413 case Intrinsic::x86_sse42_pcmpestrio128:
11414 Opcode = X86ISD::PCMPESTRI;
11415 X86CC = X86::COND_O;
11417 case Intrinsic::x86_sse42_pcmpistris128:
11418 Opcode = X86ISD::PCMPISTRI;
11419 X86CC = X86::COND_S;
11421 case Intrinsic::x86_sse42_pcmpestris128:
11422 Opcode = X86ISD::PCMPESTRI;
11423 X86CC = X86::COND_S;
11425 case Intrinsic::x86_sse42_pcmpistriz128:
11426 Opcode = X86ISD::PCMPISTRI;
11427 X86CC = X86::COND_E;
11429 case Intrinsic::x86_sse42_pcmpestriz128:
11430 Opcode = X86ISD::PCMPESTRI;
11431 X86CC = X86::COND_E;
11434 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11435 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11436 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11437 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11438 DAG.getConstant(X86CC, MVT::i8),
11439 SDValue(PCMP.getNode(), 1));
11440 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11443 case Intrinsic::x86_sse42_pcmpistri128:
11444 case Intrinsic::x86_sse42_pcmpestri128: {
11446 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11447 Opcode = X86ISD::PCMPISTRI;
11449 Opcode = X86ISD::PCMPESTRI;
11451 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11452 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11453 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11455 case Intrinsic::x86_fma_vfmadd_ps:
11456 case Intrinsic::x86_fma_vfmadd_pd:
11457 case Intrinsic::x86_fma_vfmsub_ps:
11458 case Intrinsic::x86_fma_vfmsub_pd:
11459 case Intrinsic::x86_fma_vfnmadd_ps:
11460 case Intrinsic::x86_fma_vfnmadd_pd:
11461 case Intrinsic::x86_fma_vfnmsub_ps:
11462 case Intrinsic::x86_fma_vfnmsub_pd:
11463 case Intrinsic::x86_fma_vfmaddsub_ps:
11464 case Intrinsic::x86_fma_vfmaddsub_pd:
11465 case Intrinsic::x86_fma_vfmsubadd_ps:
11466 case Intrinsic::x86_fma_vfmsubadd_pd:
11467 case Intrinsic::x86_fma_vfmadd_ps_256:
11468 case Intrinsic::x86_fma_vfmadd_pd_256:
11469 case Intrinsic::x86_fma_vfmsub_ps_256:
11470 case Intrinsic::x86_fma_vfmsub_pd_256:
11471 case Intrinsic::x86_fma_vfnmadd_ps_256:
11472 case Intrinsic::x86_fma_vfnmadd_pd_256:
11473 case Intrinsic::x86_fma_vfnmsub_ps_256:
11474 case Intrinsic::x86_fma_vfnmsub_pd_256:
11475 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11476 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11477 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11478 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11481 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11482 case Intrinsic::x86_fma_vfmadd_ps:
11483 case Intrinsic::x86_fma_vfmadd_pd:
11484 case Intrinsic::x86_fma_vfmadd_ps_256:
11485 case Intrinsic::x86_fma_vfmadd_pd_256:
11486 Opc = X86ISD::FMADD;
11488 case Intrinsic::x86_fma_vfmsub_ps:
11489 case Intrinsic::x86_fma_vfmsub_pd:
11490 case Intrinsic::x86_fma_vfmsub_ps_256:
11491 case Intrinsic::x86_fma_vfmsub_pd_256:
11492 Opc = X86ISD::FMSUB;
11494 case Intrinsic::x86_fma_vfnmadd_ps:
11495 case Intrinsic::x86_fma_vfnmadd_pd:
11496 case Intrinsic::x86_fma_vfnmadd_ps_256:
11497 case Intrinsic::x86_fma_vfnmadd_pd_256:
11498 Opc = X86ISD::FNMADD;
11500 case Intrinsic::x86_fma_vfnmsub_ps:
11501 case Intrinsic::x86_fma_vfnmsub_pd:
11502 case Intrinsic::x86_fma_vfnmsub_ps_256:
11503 case Intrinsic::x86_fma_vfnmsub_pd_256:
11504 Opc = X86ISD::FNMSUB;
11506 case Intrinsic::x86_fma_vfmaddsub_ps:
11507 case Intrinsic::x86_fma_vfmaddsub_pd:
11508 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11509 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11510 Opc = X86ISD::FMADDSUB;
11512 case Intrinsic::x86_fma_vfmsubadd_ps:
11513 case Intrinsic::x86_fma_vfmsubadd_pd:
11514 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11515 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11516 Opc = X86ISD::FMSUBADD;
11520 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11521 Op.getOperand(2), Op.getOperand(3));
11526 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11528 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11530 default: return SDValue(); // Don't custom lower most intrinsics.
11532 // RDRAND/RDSEED intrinsics.
11533 case Intrinsic::x86_rdrand_16:
11534 case Intrinsic::x86_rdrand_32:
11535 case Intrinsic::x86_rdrand_64:
11536 case Intrinsic::x86_rdseed_16:
11537 case Intrinsic::x86_rdseed_32:
11538 case Intrinsic::x86_rdseed_64: {
11539 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11540 IntNo == Intrinsic::x86_rdseed_32 ||
11541 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11543 // Emit the node with the right value type.
11544 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11545 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11547 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11548 // Otherwise return the value from Rand, which is always 0, casted to i32.
11549 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11550 DAG.getConstant(1, Op->getValueType(1)),
11551 DAG.getConstant(X86::COND_B, MVT::i32),
11552 SDValue(Result.getNode(), 1) };
11553 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11554 DAG.getVTList(Op->getValueType(1), MVT::Glue),
11555 Ops, array_lengthof(Ops));
11557 // Return { result, isValid, chain }.
11558 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11559 SDValue(Result.getNode(), 2));
11562 // XTEST intrinsics.
11563 case Intrinsic::x86_xtest: {
11564 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11565 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11566 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11567 DAG.getConstant(X86::COND_NE, MVT::i8),
11569 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11570 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11571 Ret, SDValue(InTrans.getNode(), 1));
11576 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11577 SelectionDAG &DAG) const {
11578 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11579 MFI->setReturnAddressIsTaken(true);
11581 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11583 EVT PtrVT = getPointerTy();
11586 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11587 const X86RegisterInfo *RegInfo =
11588 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11589 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11590 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11591 DAG.getNode(ISD::ADD, dl, PtrVT,
11592 FrameAddr, Offset),
11593 MachinePointerInfo(), false, false, false, 0);
11596 // Just load the return address.
11597 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11598 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11599 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11602 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11603 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11604 MFI->setFrameAddressIsTaken(true);
11606 EVT VT = Op.getValueType();
11607 SDLoc dl(Op); // FIXME probably not meaningful
11608 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11609 const X86RegisterInfo *RegInfo =
11610 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11611 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11612 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11613 (FrameReg == X86::EBP && VT == MVT::i32)) &&
11614 "Invalid Frame Register!");
11615 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11617 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11618 MachinePointerInfo(),
11619 false, false, false, 0);
11623 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11624 SelectionDAG &DAG) const {
11625 const X86RegisterInfo *RegInfo =
11626 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11627 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11630 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11631 SDValue Chain = Op.getOperand(0);
11632 SDValue Offset = Op.getOperand(1);
11633 SDValue Handler = Op.getOperand(2);
11636 EVT PtrVT = getPointerTy();
11637 const X86RegisterInfo *RegInfo =
11638 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11639 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11640 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11641 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11642 "Invalid Frame Register!");
11643 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11644 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11646 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11647 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11648 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11649 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11651 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11653 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11654 DAG.getRegister(StoreAddrReg, PtrVT));
11657 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11658 SelectionDAG &DAG) const {
11660 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11661 DAG.getVTList(MVT::i32, MVT::Other),
11662 Op.getOperand(0), Op.getOperand(1));
11665 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11666 SelectionDAG &DAG) const {
11668 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11669 Op.getOperand(0), Op.getOperand(1));
11672 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11673 return Op.getOperand(0);
11676 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11677 SelectionDAG &DAG) const {
11678 SDValue Root = Op.getOperand(0);
11679 SDValue Trmp = Op.getOperand(1); // trampoline
11680 SDValue FPtr = Op.getOperand(2); // nested function
11681 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11684 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11685 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11687 if (Subtarget->is64Bit()) {
11688 SDValue OutChains[6];
11690 // Large code-model.
11691 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
11692 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11694 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11695 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11697 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11699 // Load the pointer to the nested function into R11.
11700 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11701 SDValue Addr = Trmp;
11702 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11703 Addr, MachinePointerInfo(TrmpAddr),
11706 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11707 DAG.getConstant(2, MVT::i64));
11708 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11709 MachinePointerInfo(TrmpAddr, 2),
11712 // Load the 'nest' parameter value into R10.
11713 // R10 is specified in X86CallingConv.td
11714 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11715 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11716 DAG.getConstant(10, MVT::i64));
11717 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11718 Addr, MachinePointerInfo(TrmpAddr, 10),
11721 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11722 DAG.getConstant(12, MVT::i64));
11723 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11724 MachinePointerInfo(TrmpAddr, 12),
11727 // Jump to the nested function.
11728 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11729 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11730 DAG.getConstant(20, MVT::i64));
11731 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11732 Addr, MachinePointerInfo(TrmpAddr, 20),
11735 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11736 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11737 DAG.getConstant(22, MVT::i64));
11738 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11739 MachinePointerInfo(TrmpAddr, 22),
11742 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11744 const Function *Func =
11745 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11746 CallingConv::ID CC = Func->getCallingConv();
11751 llvm_unreachable("Unsupported calling convention");
11752 case CallingConv::C:
11753 case CallingConv::X86_StdCall: {
11754 // Pass 'nest' parameter in ECX.
11755 // Must be kept in sync with X86CallingConv.td
11756 NestReg = X86::ECX;
11758 // Check that ECX wasn't needed by an 'inreg' parameter.
11759 FunctionType *FTy = Func->getFunctionType();
11760 const AttributeSet &Attrs = Func->getAttributes();
11762 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11763 unsigned InRegCount = 0;
11766 for (FunctionType::param_iterator I = FTy->param_begin(),
11767 E = FTy->param_end(); I != E; ++I, ++Idx)
11768 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11769 // FIXME: should only count parameters that are lowered to integers.
11770 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11772 if (InRegCount > 2) {
11773 report_fatal_error("Nest register in use - reduce number of inreg"
11779 case CallingConv::X86_FastCall:
11780 case CallingConv::X86_ThisCall:
11781 case CallingConv::Fast:
11782 // Pass 'nest' parameter in EAX.
11783 // Must be kept in sync with X86CallingConv.td
11784 NestReg = X86::EAX;
11788 SDValue OutChains[4];
11789 SDValue Addr, Disp;
11791 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11792 DAG.getConstant(10, MVT::i32));
11793 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11795 // This is storing the opcode for MOV32ri.
11796 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11797 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11798 OutChains[0] = DAG.getStore(Root, dl,
11799 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11800 Trmp, MachinePointerInfo(TrmpAddr),
11803 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11804 DAG.getConstant(1, MVT::i32));
11805 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11806 MachinePointerInfo(TrmpAddr, 1),
11809 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11810 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11811 DAG.getConstant(5, MVT::i32));
11812 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11813 MachinePointerInfo(TrmpAddr, 5),
11816 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11817 DAG.getConstant(6, MVT::i32));
11818 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11819 MachinePointerInfo(TrmpAddr, 6),
11822 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11826 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11827 SelectionDAG &DAG) const {
11829 The rounding mode is in bits 11:10 of FPSR, and has the following
11831 00 Round to nearest
11836 FLT_ROUNDS, on the other hand, expects the following:
11843 To perform the conversion, we do:
11844 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11847 MachineFunction &MF = DAG.getMachineFunction();
11848 const TargetMachine &TM = MF.getTarget();
11849 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11850 unsigned StackAlignment = TFI.getStackAlignment();
11851 EVT VT = Op.getValueType();
11854 // Save FP Control Word to stack slot
11855 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11856 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11858 MachineMemOperand *MMO =
11859 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11860 MachineMemOperand::MOStore, 2, 2);
11862 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11863 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11864 DAG.getVTList(MVT::Other),
11865 Ops, array_lengthof(Ops), MVT::i16,
11868 // Load FP Control Word from stack slot
11869 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11870 MachinePointerInfo(), false, false, false, 0);
11872 // Transform as necessary
11874 DAG.getNode(ISD::SRL, DL, MVT::i16,
11875 DAG.getNode(ISD::AND, DL, MVT::i16,
11876 CWD, DAG.getConstant(0x800, MVT::i16)),
11877 DAG.getConstant(11, MVT::i8));
11879 DAG.getNode(ISD::SRL, DL, MVT::i16,
11880 DAG.getNode(ISD::AND, DL, MVT::i16,
11881 CWD, DAG.getConstant(0x400, MVT::i16)),
11882 DAG.getConstant(9, MVT::i8));
11885 DAG.getNode(ISD::AND, DL, MVT::i16,
11886 DAG.getNode(ISD::ADD, DL, MVT::i16,
11887 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11888 DAG.getConstant(1, MVT::i16)),
11889 DAG.getConstant(3, MVT::i16));
11891 return DAG.getNode((VT.getSizeInBits() < 16 ?
11892 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11895 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11896 EVT VT = Op.getValueType();
11898 unsigned NumBits = VT.getSizeInBits();
11901 Op = Op.getOperand(0);
11902 if (VT == MVT::i8) {
11903 // Zero extend to i32 since there is not an i8 bsr.
11905 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11908 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11909 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11910 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11912 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11915 DAG.getConstant(NumBits+NumBits-1, OpVT),
11916 DAG.getConstant(X86::COND_E, MVT::i8),
11919 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11921 // Finally xor with NumBits-1.
11922 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11925 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11929 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11930 EVT VT = Op.getValueType();
11932 unsigned NumBits = VT.getSizeInBits();
11935 Op = Op.getOperand(0);
11936 if (VT == MVT::i8) {
11937 // Zero extend to i32 since there is not an i8 bsr.
11939 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11942 // Issue a bsr (scan bits in reverse).
11943 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11944 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11946 // And xor with NumBits-1.
11947 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11950 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11954 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11955 EVT VT = Op.getValueType();
11956 unsigned NumBits = VT.getSizeInBits();
11958 Op = Op.getOperand(0);
11960 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11961 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11962 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11964 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11967 DAG.getConstant(NumBits, VT),
11968 DAG.getConstant(X86::COND_E, MVT::i8),
11971 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11974 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11975 // ones, and then concatenate the result back.
11976 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11977 EVT VT = Op.getValueType();
11979 assert(VT.is256BitVector() && VT.isInteger() &&
11980 "Unsupported value type for operation");
11982 unsigned NumElems = VT.getVectorNumElements();
11985 // Extract the LHS vectors
11986 SDValue LHS = Op.getOperand(0);
11987 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11988 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11990 // Extract the RHS vectors
11991 SDValue RHS = Op.getOperand(1);
11992 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11993 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11995 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11996 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11998 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11999 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12000 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12003 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12004 assert(Op.getValueType().is256BitVector() &&
12005 Op.getValueType().isInteger() &&
12006 "Only handle AVX 256-bit vector integer operation");
12007 return Lower256IntArith(Op, DAG);
12010 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12011 assert(Op.getValueType().is256BitVector() &&
12012 Op.getValueType().isInteger() &&
12013 "Only handle AVX 256-bit vector integer operation");
12014 return Lower256IntArith(Op, DAG);
12017 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12018 SelectionDAG &DAG) {
12020 EVT VT = Op.getValueType();
12022 // Decompose 256-bit ops into smaller 128-bit ops.
12023 if (VT.is256BitVector() && !Subtarget->hasInt256())
12024 return Lower256IntArith(Op, DAG);
12026 SDValue A = Op.getOperand(0);
12027 SDValue B = Op.getOperand(1);
12029 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12030 if (VT == MVT::v4i32) {
12031 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12032 "Should not custom lower when pmuldq is available!");
12034 // Extract the odd parts.
12035 static const int UnpackMask[] = { 1, -1, 3, -1 };
12036 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12037 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12039 // Multiply the even parts.
12040 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12041 // Now multiply odd parts.
12042 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12044 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12045 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12047 // Merge the two vectors back together with a shuffle. This expands into 2
12049 static const int ShufMask[] = { 0, 4, 2, 6 };
12050 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12053 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
12054 "Only know how to lower V2I64/V4I64 multiply");
12056 // Ahi = psrlqi(a, 32);
12057 // Bhi = psrlqi(b, 32);
12059 // AloBlo = pmuludq(a, b);
12060 // AloBhi = pmuludq(a, Bhi);
12061 // AhiBlo = pmuludq(Ahi, b);
12063 // AloBhi = psllqi(AloBhi, 32);
12064 // AhiBlo = psllqi(AhiBlo, 32);
12065 // return AloBlo + AloBhi + AhiBlo;
12067 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
12069 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
12070 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
12072 // Bit cast to 32-bit vectors for MULUDQ
12073 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
12074 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12075 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12076 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12077 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12079 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12080 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12081 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12083 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
12084 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
12086 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12087 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12090 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12091 EVT VT = Op.getValueType();
12092 EVT EltTy = VT.getVectorElementType();
12093 unsigned NumElts = VT.getVectorNumElements();
12094 SDValue N0 = Op.getOperand(0);
12097 // Lower sdiv X, pow2-const.
12098 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12102 APInt SplatValue, SplatUndef;
12103 unsigned SplatBitSize;
12105 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12107 EltTy.getSizeInBits() < SplatBitSize)
12110 if ((SplatValue != 0) &&
12111 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12112 unsigned lg2 = SplatValue.countTrailingZeros();
12113 // Splat the sign bit.
12114 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
12115 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
12116 // Add (N0 < 0) ? abs2 - 1 : 0;
12117 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
12118 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
12119 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12120 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
12121 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
12123 // If we're dividing by a positive value, we're done. Otherwise, we must
12124 // negate the result.
12125 if (SplatValue.isNonNegative())
12128 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12129 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12130 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12135 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12136 const X86Subtarget *Subtarget) {
12137 EVT VT = Op.getValueType();
12139 SDValue R = Op.getOperand(0);
12140 SDValue Amt = Op.getOperand(1);
12142 // Optimize shl/srl/sra with constant shift amount.
12143 if (isSplatVector(Amt.getNode())) {
12144 SDValue SclrAmt = Amt->getOperand(0);
12145 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12146 uint64_t ShiftAmt = C->getZExtValue();
12148 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12149 (Subtarget->hasInt256() &&
12150 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
12151 if (Op.getOpcode() == ISD::SHL)
12152 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12153 DAG.getConstant(ShiftAmt, MVT::i32));
12154 if (Op.getOpcode() == ISD::SRL)
12155 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12156 DAG.getConstant(ShiftAmt, MVT::i32));
12157 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12158 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12159 DAG.getConstant(ShiftAmt, MVT::i32));
12162 if (VT == MVT::v16i8) {
12163 if (Op.getOpcode() == ISD::SHL) {
12164 // Make a large shift.
12165 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
12166 DAG.getConstant(ShiftAmt, MVT::i32));
12167 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12168 // Zero out the rightmost bits.
12169 SmallVector<SDValue, 16> V(16,
12170 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12172 return DAG.getNode(ISD::AND, dl, VT, SHL,
12173 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12175 if (Op.getOpcode() == ISD::SRL) {
12176 // Make a large shift.
12177 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
12178 DAG.getConstant(ShiftAmt, MVT::i32));
12179 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12180 // Zero out the leftmost bits.
12181 SmallVector<SDValue, 16> V(16,
12182 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12184 return DAG.getNode(ISD::AND, dl, VT, SRL,
12185 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12187 if (Op.getOpcode() == ISD::SRA) {
12188 if (ShiftAmt == 7) {
12189 // R s>> 7 === R s< 0
12190 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12191 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12194 // R s>> a === ((R u>> a) ^ m) - m
12195 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12196 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12198 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12199 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12200 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12203 llvm_unreachable("Unknown shift opcode.");
12206 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12207 if (Op.getOpcode() == ISD::SHL) {
12208 // Make a large shift.
12209 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
12210 DAG.getConstant(ShiftAmt, MVT::i32));
12211 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12212 // Zero out the rightmost bits.
12213 SmallVector<SDValue, 32> V(32,
12214 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12216 return DAG.getNode(ISD::AND, dl, VT, SHL,
12217 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12219 if (Op.getOpcode() == ISD::SRL) {
12220 // Make a large shift.
12221 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
12222 DAG.getConstant(ShiftAmt, MVT::i32));
12223 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12224 // Zero out the leftmost bits.
12225 SmallVector<SDValue, 32> V(32,
12226 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12228 return DAG.getNode(ISD::AND, dl, VT, SRL,
12229 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12231 if (Op.getOpcode() == ISD::SRA) {
12232 if (ShiftAmt == 7) {
12233 // R s>> 7 === R s< 0
12234 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12235 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12238 // R s>> a === ((R u>> a) ^ m) - m
12239 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12240 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12242 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12243 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12244 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12247 llvm_unreachable("Unknown shift opcode.");
12252 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12253 if (!Subtarget->is64Bit() &&
12254 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12255 Amt.getOpcode() == ISD::BITCAST &&
12256 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12257 Amt = Amt.getOperand(0);
12258 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12259 VT.getVectorNumElements();
12260 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12261 uint64_t ShiftAmt = 0;
12262 for (unsigned i = 0; i != Ratio; ++i) {
12263 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12267 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12269 // Check remaining shift amounts.
12270 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12271 uint64_t ShAmt = 0;
12272 for (unsigned j = 0; j != Ratio; ++j) {
12273 ConstantSDNode *C =
12274 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12278 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12280 if (ShAmt != ShiftAmt)
12283 switch (Op.getOpcode()) {
12285 llvm_unreachable("Unknown shift opcode!");
12287 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12288 DAG.getConstant(ShiftAmt, MVT::i32));
12290 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12291 DAG.getConstant(ShiftAmt, MVT::i32));
12293 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12294 DAG.getConstant(ShiftAmt, MVT::i32));
12301 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12302 const X86Subtarget* Subtarget) {
12303 EVT VT = Op.getValueType();
12305 SDValue R = Op.getOperand(0);
12306 SDValue Amt = Op.getOperand(1);
12308 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12309 VT == MVT::v4i32 || VT == MVT::v8i16 ||
12310 (Subtarget->hasInt256() &&
12311 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12312 VT == MVT::v8i32 || VT == MVT::v16i16))) {
12314 EVT EltVT = VT.getVectorElementType();
12316 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12317 unsigned NumElts = VT.getVectorNumElements();
12319 for (i = 0; i != NumElts; ++i) {
12320 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12324 for (j = i; j != NumElts; ++j) {
12325 SDValue Arg = Amt.getOperand(j);
12326 if (Arg.getOpcode() == ISD::UNDEF) continue;
12327 if (Arg != Amt.getOperand(i))
12330 if (i != NumElts && j == NumElts)
12331 BaseShAmt = Amt.getOperand(i);
12333 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12334 Amt = Amt.getOperand(0);
12335 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12336 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12337 SDValue InVec = Amt.getOperand(0);
12338 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12339 unsigned NumElts = InVec.getValueType().getVectorNumElements();
12341 for (; i != NumElts; ++i) {
12342 SDValue Arg = InVec.getOperand(i);
12343 if (Arg.getOpcode() == ISD::UNDEF) continue;
12347 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12348 if (ConstantSDNode *C =
12349 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12350 unsigned SplatIdx =
12351 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12352 if (C->getZExtValue() == SplatIdx)
12353 BaseShAmt = InVec.getOperand(1);
12356 if (BaseShAmt.getNode() == 0)
12357 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12358 DAG.getIntPtrConstant(0));
12362 if (BaseShAmt.getNode()) {
12363 if (EltVT.bitsGT(MVT::i32))
12364 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12365 else if (EltVT.bitsLT(MVT::i32))
12366 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12368 switch (Op.getOpcode()) {
12370 llvm_unreachable("Unknown shift opcode!");
12372 switch (VT.getSimpleVT().SimpleTy) {
12373 default: return SDValue();
12380 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12383 switch (VT.getSimpleVT().SimpleTy) {
12384 default: return SDValue();
12389 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12392 switch (VT.getSimpleVT().SimpleTy) {
12393 default: return SDValue();
12400 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12406 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12407 if (!Subtarget->is64Bit() &&
12408 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12409 Amt.getOpcode() == ISD::BITCAST &&
12410 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12411 Amt = Amt.getOperand(0);
12412 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12413 VT.getVectorNumElements();
12414 std::vector<SDValue> Vals(Ratio);
12415 for (unsigned i = 0; i != Ratio; ++i)
12416 Vals[i] = Amt.getOperand(i);
12417 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12418 for (unsigned j = 0; j != Ratio; ++j)
12419 if (Vals[j] != Amt.getOperand(i + j))
12422 switch (Op.getOpcode()) {
12424 llvm_unreachable("Unknown shift opcode!");
12426 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12428 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12430 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12437 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
12438 SelectionDAG &DAG) {
12440 EVT VT = Op.getValueType();
12442 SDValue R = Op.getOperand(0);
12443 SDValue Amt = Op.getOperand(1);
12446 if (!Subtarget->hasSSE2())
12449 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12453 V = LowerScalarVariableShift(Op, DAG, Subtarget);
12457 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12458 if (Subtarget->hasInt256()) {
12459 if (Op.getOpcode() == ISD::SRL &&
12460 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12461 VT == MVT::v4i64 || VT == MVT::v8i32))
12463 if (Op.getOpcode() == ISD::SHL &&
12464 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12465 VT == MVT::v4i64 || VT == MVT::v8i32))
12467 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12471 // Lower SHL with variable shift amount.
12472 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12473 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12475 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12476 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12477 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12478 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12480 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12481 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12484 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12485 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12487 // Turn 'a' into a mask suitable for VSELECT
12488 SDValue VSelM = DAG.getConstant(0x80, VT);
12489 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12490 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12492 SDValue CM1 = DAG.getConstant(0x0f, VT);
12493 SDValue CM2 = DAG.getConstant(0x3f, VT);
12495 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12496 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12497 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12498 DAG.getConstant(4, MVT::i32), DAG);
12499 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12500 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12503 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12504 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12505 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12507 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12508 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12509 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12510 DAG.getConstant(2, MVT::i32), DAG);
12511 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12512 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12515 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12516 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12517 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12519 // return VSELECT(r, r+r, a);
12520 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12521 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12525 // Decompose 256-bit shifts into smaller 128-bit shifts.
12526 if (VT.is256BitVector()) {
12527 unsigned NumElems = VT.getVectorNumElements();
12528 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12529 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12531 // Extract the two vectors
12532 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12533 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12535 // Recreate the shift amount vectors
12536 SDValue Amt1, Amt2;
12537 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12538 // Constant shift amount
12539 SmallVector<SDValue, 4> Amt1Csts;
12540 SmallVector<SDValue, 4> Amt2Csts;
12541 for (unsigned i = 0; i != NumElems/2; ++i)
12542 Amt1Csts.push_back(Amt->getOperand(i));
12543 for (unsigned i = NumElems/2; i != NumElems; ++i)
12544 Amt2Csts.push_back(Amt->getOperand(i));
12546 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12547 &Amt1Csts[0], NumElems/2);
12548 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12549 &Amt2Csts[0], NumElems/2);
12551 // Variable shift amount
12552 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12553 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12556 // Issue new vector shifts for the smaller types
12557 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12558 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12560 // Concatenate the result back
12561 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12567 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12568 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12569 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12570 // looks for this combo and may remove the "setcc" instruction if the "setcc"
12571 // has only one use.
12572 SDNode *N = Op.getNode();
12573 SDValue LHS = N->getOperand(0);
12574 SDValue RHS = N->getOperand(1);
12575 unsigned BaseOp = 0;
12578 switch (Op.getOpcode()) {
12579 default: llvm_unreachable("Unknown ovf instruction!");
12581 // A subtract of one will be selected as a INC. Note that INC doesn't
12582 // set CF, so we can't do this for UADDO.
12583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12585 BaseOp = X86ISD::INC;
12586 Cond = X86::COND_O;
12589 BaseOp = X86ISD::ADD;
12590 Cond = X86::COND_O;
12593 BaseOp = X86ISD::ADD;
12594 Cond = X86::COND_B;
12597 // A subtract of one will be selected as a DEC. Note that DEC doesn't
12598 // set CF, so we can't do this for USUBO.
12599 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12601 BaseOp = X86ISD::DEC;
12602 Cond = X86::COND_O;
12605 BaseOp = X86ISD::SUB;
12606 Cond = X86::COND_O;
12609 BaseOp = X86ISD::SUB;
12610 Cond = X86::COND_B;
12613 BaseOp = X86ISD::SMUL;
12614 Cond = X86::COND_O;
12616 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12617 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12619 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12622 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12623 DAG.getConstant(X86::COND_O, MVT::i32),
12624 SDValue(Sum.getNode(), 2));
12626 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12630 // Also sets EFLAGS.
12631 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12632 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12635 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12636 DAG.getConstant(Cond, MVT::i32),
12637 SDValue(Sum.getNode(), 1));
12639 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12642 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12643 SelectionDAG &DAG) const {
12645 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12646 EVT VT = Op.getValueType();
12648 if (!Subtarget->hasSSE2() || !VT.isVector())
12651 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12652 ExtraVT.getScalarType().getSizeInBits();
12653 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12655 switch (VT.getSimpleVT().SimpleTy) {
12656 default: return SDValue();
12659 if (!Subtarget->hasFp256())
12661 if (!Subtarget->hasInt256()) {
12662 // needs to be split
12663 unsigned NumElems = VT.getVectorNumElements();
12665 // Extract the LHS vectors
12666 SDValue LHS = Op.getOperand(0);
12667 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12668 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12670 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12671 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12673 EVT ExtraEltVT = ExtraVT.getVectorElementType();
12674 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12675 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12677 SDValue Extra = DAG.getValueType(ExtraVT);
12679 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12680 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12682 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12687 // (sext (vzext x)) -> (vsext x)
12688 SDValue Op0 = Op.getOperand(0);
12689 SDValue Op00 = Op0.getOperand(0);
12691 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12692 if (Op0.getOpcode() == ISD::BITCAST &&
12693 Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12694 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
12695 if (Tmp1.getNode()) {
12696 SDValue Tmp1Op0 = Tmp1.getOperand(0);
12697 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12698 "This optimization is invalid without a VZEXT.");
12699 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12702 // If the above didn't work, then just use Shift-Left + Shift-Right.
12703 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12704 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12709 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12710 SelectionDAG &DAG) {
12712 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12713 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12714 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12715 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12717 // The only fence that needs an instruction is a sequentially-consistent
12718 // cross-thread fence.
12719 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12720 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12721 // no-sse2). There isn't any reason to disable it if the target processor
12723 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12724 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12726 SDValue Chain = Op.getOperand(0);
12727 SDValue Zero = DAG.getConstant(0, MVT::i32);
12729 DAG.getRegister(X86::ESP, MVT::i32), // Base
12730 DAG.getTargetConstant(1, MVT::i8), // Scale
12731 DAG.getRegister(0, MVT::i32), // Index
12732 DAG.getTargetConstant(0, MVT::i32), // Disp
12733 DAG.getRegister(0, MVT::i32), // Segment.
12737 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12738 return SDValue(Res, 0);
12741 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12742 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12745 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12746 SelectionDAG &DAG) {
12747 EVT T = Op.getValueType();
12751 switch(T.getSimpleVT().SimpleTy) {
12752 default: llvm_unreachable("Invalid value type!");
12753 case MVT::i8: Reg = X86::AL; size = 1; break;
12754 case MVT::i16: Reg = X86::AX; size = 2; break;
12755 case MVT::i32: Reg = X86::EAX; size = 4; break;
12757 assert(Subtarget->is64Bit() && "Node not type legal!");
12758 Reg = X86::RAX; size = 8;
12761 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12762 Op.getOperand(2), SDValue());
12763 SDValue Ops[] = { cpIn.getValue(0),
12766 DAG.getTargetConstant(size, MVT::i8),
12767 cpIn.getValue(1) };
12768 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12769 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12770 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12771 Ops, array_lengthof(Ops), T, MMO);
12773 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12777 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12778 SelectionDAG &DAG) {
12779 assert(Subtarget->is64Bit() && "Result not type legalized?");
12780 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12781 SDValue TheChain = Op.getOperand(0);
12783 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12784 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12785 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12787 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12788 DAG.getConstant(32, MVT::i8));
12790 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12793 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12796 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
12797 SelectionDAG &DAG) {
12798 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
12799 MVT DstVT = Op.getSimpleValueType();
12800 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12801 Subtarget->hasMMX() && "Unexpected custom BITCAST");
12802 assert((DstVT == MVT::i64 ||
12803 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12804 "Unexpected custom BITCAST");
12805 // i64 <=> MMX conversions are Legal.
12806 if (SrcVT==MVT::i64 && DstVT.isVector())
12808 if (DstVT==MVT::i64 && SrcVT.isVector())
12810 // MMX <=> MMX conversions are Legal.
12811 if (SrcVT.isVector() && DstVT.isVector())
12813 // All other conversions need to be expanded.
12817 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12818 SDNode *Node = Op.getNode();
12820 EVT T = Node->getValueType(0);
12821 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12822 DAG.getConstant(0, T), Node->getOperand(2));
12823 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12824 cast<AtomicSDNode>(Node)->getMemoryVT(),
12825 Node->getOperand(0),
12826 Node->getOperand(1), negOp,
12827 cast<AtomicSDNode>(Node)->getSrcValue(),
12828 cast<AtomicSDNode>(Node)->getAlignment(),
12829 cast<AtomicSDNode>(Node)->getOrdering(),
12830 cast<AtomicSDNode>(Node)->getSynchScope());
12833 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12834 SDNode *Node = Op.getNode();
12836 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12838 // Convert seq_cst store -> xchg
12839 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12840 // FIXME: On 32-bit, store -> fist or movq would be more efficient
12841 // (The only way to get a 16-byte store is cmpxchg16b)
12842 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12843 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12844 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12845 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12846 cast<AtomicSDNode>(Node)->getMemoryVT(),
12847 Node->getOperand(0),
12848 Node->getOperand(1), Node->getOperand(2),
12849 cast<AtomicSDNode>(Node)->getMemOperand(),
12850 cast<AtomicSDNode>(Node)->getOrdering(),
12851 cast<AtomicSDNode>(Node)->getSynchScope());
12852 return Swap.getValue(1);
12854 // Other atomic stores have a simple pattern.
12858 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12859 EVT VT = Op.getNode()->getValueType(0);
12861 // Let legalize expand this if it isn't a legal type yet.
12862 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12865 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12868 bool ExtraOp = false;
12869 switch (Op.getOpcode()) {
12870 default: llvm_unreachable("Invalid code");
12871 case ISD::ADDC: Opc = X86ISD::ADD; break;
12872 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12873 case ISD::SUBC: Opc = X86ISD::SUB; break;
12874 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12878 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12880 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12881 Op.getOperand(1), Op.getOperand(2));
12884 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
12885 SelectionDAG &DAG) {
12886 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12888 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12889 // which returns the values as { float, float } (in XMM0) or
12890 // { double, double } (which is returned in XMM0, XMM1).
12892 SDValue Arg = Op.getOperand(0);
12893 EVT ArgVT = Arg.getValueType();
12894 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12896 TargetLowering::ArgListTy Args;
12897 TargetLowering::ArgListEntry Entry;
12901 Entry.isSExt = false;
12902 Entry.isZExt = false;
12903 Args.push_back(Entry);
12905 bool isF64 = ArgVT == MVT::f64;
12906 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12907 // the small struct {f32, f32} is returned in (eax, edx). For f64,
12908 // the results are returned via SRet in memory.
12909 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
12910 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12911 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
12913 Type *RetTy = isF64
12914 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12915 : (Type*)VectorType::get(ArgTy, 4);
12917 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12918 false, false, false, false, 0,
12919 CallingConv::C, /*isTaillCall=*/false,
12920 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12921 Callee, Args, DAG, dl);
12922 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
12925 // Returned in xmm0 and xmm1.
12926 return CallResult.first;
12928 // Returned in bits 0:31 and 32:64 xmm0.
12929 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12930 CallResult.first, DAG.getIntPtrConstant(0));
12931 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12932 CallResult.first, DAG.getIntPtrConstant(1));
12933 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12934 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12937 /// LowerOperation - Provide custom lowering hooks for some operations.
12939 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12940 switch (Op.getOpcode()) {
12941 default: llvm_unreachable("Should not custom lower this!");
12942 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12943 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12944 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12945 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12946 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12947 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12948 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12949 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12950 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12951 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12952 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12953 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12954 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12955 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12956 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12957 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12958 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12959 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12960 case ISD::SHL_PARTS:
12961 case ISD::SRA_PARTS:
12962 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12963 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12964 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12965 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12966 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12967 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12968 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12969 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12970 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12971 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12972 case ISD::FABS: return LowerFABS(Op, DAG);
12973 case ISD::FNEG: return LowerFNEG(Op, DAG);
12974 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12975 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12976 case ISD::SETCC: return LowerSETCC(Op, DAG);
12977 case ISD::SELECT: return LowerSELECT(Op, DAG);
12978 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12979 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12980 case ISD::VASTART: return LowerVASTART(Op, DAG);
12981 case ISD::VAARG: return LowerVAARG(Op, DAG);
12982 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12983 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12984 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12985 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12986 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12987 case ISD::FRAME_TO_ARGS_OFFSET:
12988 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12989 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12990 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12991 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12992 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12993 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12994 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12995 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12996 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12997 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12998 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12999 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
13002 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
13008 case ISD::UMULO: return LowerXALUO(Op, DAG);
13009 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13010 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
13014 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13015 case ISD::ADD: return LowerADD(Op, DAG);
13016 case ISD::SUB: return LowerSUB(Op, DAG);
13017 case ISD::SDIV: return LowerSDIV(Op, DAG);
13018 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
13022 static void ReplaceATOMIC_LOAD(SDNode *Node,
13023 SmallVectorImpl<SDValue> &Results,
13024 SelectionDAG &DAG) {
13026 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13028 // Convert wide load -> cmpxchg8b/cmpxchg16b
13029 // FIXME: On 32-bit, load -> fild or movq would be more efficient
13030 // (The only way to get a 16-byte load is cmpxchg16b)
13031 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13032 SDValue Zero = DAG.getConstant(0, VT);
13033 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13034 Node->getOperand(0),
13035 Node->getOperand(1), Zero, Zero,
13036 cast<AtomicSDNode>(Node)->getMemOperand(),
13037 cast<AtomicSDNode>(Node)->getOrdering(),
13038 cast<AtomicSDNode>(Node)->getSynchScope());
13039 Results.push_back(Swap.getValue(0));
13040 Results.push_back(Swap.getValue(1));
13044 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13045 SelectionDAG &DAG, unsigned NewOp) {
13047 assert (Node->getValueType(0) == MVT::i64 &&
13048 "Only know how to expand i64 atomics");
13050 SDValue Chain = Node->getOperand(0);
13051 SDValue In1 = Node->getOperand(1);
13052 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13053 Node->getOperand(2), DAG.getIntPtrConstant(0));
13054 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13055 Node->getOperand(2), DAG.getIntPtrConstant(1));
13056 SDValue Ops[] = { Chain, In1, In2L, In2H };
13057 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13059 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13060 cast<MemSDNode>(Node)->getMemOperand());
13061 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13062 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13063 Results.push_back(Result.getValue(2));
13066 /// ReplaceNodeResults - Replace a node with an illegal result type
13067 /// with a new node built out of custom code.
13068 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13069 SmallVectorImpl<SDValue>&Results,
13070 SelectionDAG &DAG) const {
13072 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13073 switch (N->getOpcode()) {
13075 llvm_unreachable("Do not know how to custom type legalize this operation!");
13076 case ISD::SIGN_EXTEND_INREG:
13081 // We don't want to expand or promote these.
13083 case ISD::FP_TO_SINT:
13084 case ISD::FP_TO_UINT: {
13085 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13087 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13090 std::pair<SDValue,SDValue> Vals =
13091 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13092 SDValue FIST = Vals.first, StackSlot = Vals.second;
13093 if (FIST.getNode() != 0) {
13094 EVT VT = N->getValueType(0);
13095 // Return a load from the stack slot.
13096 if (StackSlot.getNode() != 0)
13097 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13098 MachinePointerInfo(),
13099 false, false, false, 0));
13101 Results.push_back(FIST);
13105 case ISD::UINT_TO_FP: {
13106 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13107 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13108 N->getValueType(0) != MVT::v2f32)
13110 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13112 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13114 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13115 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13116 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13117 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13118 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13119 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13122 case ISD::FP_ROUND: {
13123 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13125 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13126 Results.push_back(V);
13129 case ISD::READCYCLECOUNTER: {
13130 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13131 SDValue TheChain = N->getOperand(0);
13132 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13133 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13135 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13137 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13138 SDValue Ops[] = { eax, edx };
13139 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13140 array_lengthof(Ops)));
13141 Results.push_back(edx.getValue(1));
13144 case ISD::ATOMIC_CMP_SWAP: {
13145 EVT T = N->getValueType(0);
13146 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13147 bool Regs64bit = T == MVT::i128;
13148 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13149 SDValue cpInL, cpInH;
13150 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13151 DAG.getConstant(0, HalfT));
13152 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13153 DAG.getConstant(1, HalfT));
13154 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13155 Regs64bit ? X86::RAX : X86::EAX,
13157 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13158 Regs64bit ? X86::RDX : X86::EDX,
13159 cpInH, cpInL.getValue(1));
13160 SDValue swapInL, swapInH;
13161 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13162 DAG.getConstant(0, HalfT));
13163 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13164 DAG.getConstant(1, HalfT));
13165 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13166 Regs64bit ? X86::RBX : X86::EBX,
13167 swapInL, cpInH.getValue(1));
13168 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13169 Regs64bit ? X86::RCX : X86::ECX,
13170 swapInH, swapInL.getValue(1));
13171 SDValue Ops[] = { swapInH.getValue(0),
13173 swapInH.getValue(1) };
13174 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13175 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13176 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13177 X86ISD::LCMPXCHG8_DAG;
13178 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13179 Ops, array_lengthof(Ops), T, MMO);
13180 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13181 Regs64bit ? X86::RAX : X86::EAX,
13182 HalfT, Result.getValue(1));
13183 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13184 Regs64bit ? X86::RDX : X86::EDX,
13185 HalfT, cpOutL.getValue(2));
13186 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13187 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13188 Results.push_back(cpOutH.getValue(1));
13191 case ISD::ATOMIC_LOAD_ADD:
13192 case ISD::ATOMIC_LOAD_AND:
13193 case ISD::ATOMIC_LOAD_NAND:
13194 case ISD::ATOMIC_LOAD_OR:
13195 case ISD::ATOMIC_LOAD_SUB:
13196 case ISD::ATOMIC_LOAD_XOR:
13197 case ISD::ATOMIC_LOAD_MAX:
13198 case ISD::ATOMIC_LOAD_MIN:
13199 case ISD::ATOMIC_LOAD_UMAX:
13200 case ISD::ATOMIC_LOAD_UMIN:
13201 case ISD::ATOMIC_SWAP: {
13203 switch (N->getOpcode()) {
13204 default: llvm_unreachable("Unexpected opcode");
13205 case ISD::ATOMIC_LOAD_ADD:
13206 Opc = X86ISD::ATOMADD64_DAG;
13208 case ISD::ATOMIC_LOAD_AND:
13209 Opc = X86ISD::ATOMAND64_DAG;
13211 case ISD::ATOMIC_LOAD_NAND:
13212 Opc = X86ISD::ATOMNAND64_DAG;
13214 case ISD::ATOMIC_LOAD_OR:
13215 Opc = X86ISD::ATOMOR64_DAG;
13217 case ISD::ATOMIC_LOAD_SUB:
13218 Opc = X86ISD::ATOMSUB64_DAG;
13220 case ISD::ATOMIC_LOAD_XOR:
13221 Opc = X86ISD::ATOMXOR64_DAG;
13223 case ISD::ATOMIC_LOAD_MAX:
13224 Opc = X86ISD::ATOMMAX64_DAG;
13226 case ISD::ATOMIC_LOAD_MIN:
13227 Opc = X86ISD::ATOMMIN64_DAG;
13229 case ISD::ATOMIC_LOAD_UMAX:
13230 Opc = X86ISD::ATOMUMAX64_DAG;
13232 case ISD::ATOMIC_LOAD_UMIN:
13233 Opc = X86ISD::ATOMUMIN64_DAG;
13235 case ISD::ATOMIC_SWAP:
13236 Opc = X86ISD::ATOMSWAP64_DAG;
13239 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13242 case ISD::ATOMIC_LOAD:
13243 ReplaceATOMIC_LOAD(N, Results, DAG);
13247 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13249 default: return NULL;
13250 case X86ISD::BSF: return "X86ISD::BSF";
13251 case X86ISD::BSR: return "X86ISD::BSR";
13252 case X86ISD::SHLD: return "X86ISD::SHLD";
13253 case X86ISD::SHRD: return "X86ISD::SHRD";
13254 case X86ISD::FAND: return "X86ISD::FAND";
13255 case X86ISD::FANDN: return "X86ISD::FANDN";
13256 case X86ISD::FOR: return "X86ISD::FOR";
13257 case X86ISD::FXOR: return "X86ISD::FXOR";
13258 case X86ISD::FSRL: return "X86ISD::FSRL";
13259 case X86ISD::FILD: return "X86ISD::FILD";
13260 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
13261 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13262 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13263 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13264 case X86ISD::FLD: return "X86ISD::FLD";
13265 case X86ISD::FST: return "X86ISD::FST";
13266 case X86ISD::CALL: return "X86ISD::CALL";
13267 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
13268 case X86ISD::BT: return "X86ISD::BT";
13269 case X86ISD::CMP: return "X86ISD::CMP";
13270 case X86ISD::COMI: return "X86ISD::COMI";
13271 case X86ISD::UCOMI: return "X86ISD::UCOMI";
13272 case X86ISD::CMPM: return "X86ISD::CMPM";
13273 case X86ISD::CMPMU: return "X86ISD::CMPMU";
13274 case X86ISD::SETCC: return "X86ISD::SETCC";
13275 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
13276 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
13277 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
13278 case X86ISD::CMOV: return "X86ISD::CMOV";
13279 case X86ISD::BRCOND: return "X86ISD::BRCOND";
13280 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
13281 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
13282 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
13283 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
13284 case X86ISD::Wrapper: return "X86ISD::Wrapper";
13285 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
13286 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
13287 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
13288 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
13289 case X86ISD::PINSRB: return "X86ISD::PINSRB";
13290 case X86ISD::PINSRW: return "X86ISD::PINSRW";
13291 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
13292 case X86ISD::ANDNP: return "X86ISD::ANDNP";
13293 case X86ISD::PSIGN: return "X86ISD::PSIGN";
13294 case X86ISD::BLENDV: return "X86ISD::BLENDV";
13295 case X86ISD::BLENDI: return "X86ISD::BLENDI";
13296 case X86ISD::SUBUS: return "X86ISD::SUBUS";
13297 case X86ISD::HADD: return "X86ISD::HADD";
13298 case X86ISD::HSUB: return "X86ISD::HSUB";
13299 case X86ISD::FHADD: return "X86ISD::FHADD";
13300 case X86ISD::FHSUB: return "X86ISD::FHSUB";
13301 case X86ISD::UMAX: return "X86ISD::UMAX";
13302 case X86ISD::UMIN: return "X86ISD::UMIN";
13303 case X86ISD::SMAX: return "X86ISD::SMAX";
13304 case X86ISD::SMIN: return "X86ISD::SMIN";
13305 case X86ISD::FMAX: return "X86ISD::FMAX";
13306 case X86ISD::FMIN: return "X86ISD::FMIN";
13307 case X86ISD::FMAXC: return "X86ISD::FMAXC";
13308 case X86ISD::FMINC: return "X86ISD::FMINC";
13309 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
13310 case X86ISD::FRCP: return "X86ISD::FRCP";
13311 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
13312 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
13313 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
13314 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
13315 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
13316 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
13317 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
13318 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
13319 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
13320 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
13321 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
13322 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
13323 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
13324 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
13325 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
13326 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
13327 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
13328 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
13329 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
13330 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
13331 case X86ISD::VZEXT: return "X86ISD::VZEXT";
13332 case X86ISD::VSEXT: return "X86ISD::VSEXT";
13333 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
13334 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
13335 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
13336 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
13337 case X86ISD::VSHL: return "X86ISD::VSHL";
13338 case X86ISD::VSRL: return "X86ISD::VSRL";
13339 case X86ISD::VSRA: return "X86ISD::VSRA";
13340 case X86ISD::VSHLI: return "X86ISD::VSHLI";
13341 case X86ISD::VSRLI: return "X86ISD::VSRLI";
13342 case X86ISD::VSRAI: return "X86ISD::VSRAI";
13343 case X86ISD::CMPP: return "X86ISD::CMPP";
13344 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
13345 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
13346 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
13347 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
13348 case X86ISD::ADD: return "X86ISD::ADD";
13349 case X86ISD::SUB: return "X86ISD::SUB";
13350 case X86ISD::ADC: return "X86ISD::ADC";
13351 case X86ISD::SBB: return "X86ISD::SBB";
13352 case X86ISD::SMUL: return "X86ISD::SMUL";
13353 case X86ISD::UMUL: return "X86ISD::UMUL";
13354 case X86ISD::INC: return "X86ISD::INC";
13355 case X86ISD::DEC: return "X86ISD::DEC";
13356 case X86ISD::OR: return "X86ISD::OR";
13357 case X86ISD::XOR: return "X86ISD::XOR";
13358 case X86ISD::AND: return "X86ISD::AND";
13359 case X86ISD::BLSI: return "X86ISD::BLSI";
13360 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
13361 case X86ISD::BLSR: return "X86ISD::BLSR";
13362 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
13363 case X86ISD::PTEST: return "X86ISD::PTEST";
13364 case X86ISD::TESTP: return "X86ISD::TESTP";
13365 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
13366 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
13367 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
13368 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
13369 case X86ISD::SHUFP: return "X86ISD::SHUFP";
13370 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
13371 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
13372 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
13373 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
13374 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
13375 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
13376 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
13377 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
13378 case X86ISD::MOVSD: return "X86ISD::MOVSD";
13379 case X86ISD::MOVSS: return "X86ISD::MOVSS";
13380 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
13381 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
13382 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
13383 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
13384 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
13385 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
13386 case X86ISD::VPERMV: return "X86ISD::VPERMV";
13387 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
13388 case X86ISD::VPERMI: return "X86ISD::VPERMI";
13389 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
13390 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13391 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
13392 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
13393 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
13394 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
13395 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
13396 case X86ISD::SAHF: return "X86ISD::SAHF";
13397 case X86ISD::RDRAND: return "X86ISD::RDRAND";
13398 case X86ISD::RDSEED: return "X86ISD::RDSEED";
13399 case X86ISD::FMADD: return "X86ISD::FMADD";
13400 case X86ISD::FMSUB: return "X86ISD::FMSUB";
13401 case X86ISD::FNMADD: return "X86ISD::FNMADD";
13402 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
13403 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
13404 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
13405 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
13406 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
13407 case X86ISD::XTEST: return "X86ISD::XTEST";
13411 // isLegalAddressingMode - Return true if the addressing mode represented
13412 // by AM is legal for this target, for a load/store of the specified type.
13413 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13415 // X86 supports extremely general addressing modes.
13416 CodeModel::Model M = getTargetMachine().getCodeModel();
13417 Reloc::Model R = getTargetMachine().getRelocationModel();
13419 // X86 allows a sign-extended 32-bit immediate field as a displacement.
13420 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13425 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13427 // If a reference to this global requires an extra load, we can't fold it.
13428 if (isGlobalStubReference(GVFlags))
13431 // If BaseGV requires a register for the PIC base, we cannot also have a
13432 // BaseReg specified.
13433 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13436 // If lower 4G is not available, then we must use rip-relative addressing.
13437 if ((M != CodeModel::Small || R != Reloc::Static) &&
13438 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13442 switch (AM.Scale) {
13448 // These scales always work.
13453 // These scales are formed with basereg+scalereg. Only accept if there is
13458 default: // Other stuff never works.
13465 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13466 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13468 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13469 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13470 return NumBits1 > NumBits2;
13473 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13474 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13477 if (!isTypeLegal(EVT::getEVT(Ty1)))
13480 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13482 // Assuming the caller doesn't have a zeroext or signext return parameter,
13483 // truncation all the way down to i1 is valid.
13487 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13488 return isInt<32>(Imm);
13491 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13492 // Can also use sub to handle negated immediates.
13493 return isInt<32>(Imm);
13496 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13497 if (!VT1.isInteger() || !VT2.isInteger())
13499 unsigned NumBits1 = VT1.getSizeInBits();
13500 unsigned NumBits2 = VT2.getSizeInBits();
13501 return NumBits1 > NumBits2;
13504 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13505 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13506 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13509 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13510 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13511 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13514 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13515 EVT VT1 = Val.getValueType();
13516 if (isZExtFree(VT1, VT2))
13519 if (Val.getOpcode() != ISD::LOAD)
13522 if (!VT1.isSimple() || !VT1.isInteger() ||
13523 !VT2.isSimple() || !VT2.isInteger())
13526 switch (VT1.getSimpleVT().SimpleTy) {
13531 // X86 has 8, 16, and 32-bit zero-extending loads.
13539 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13540 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13543 VT = VT.getScalarType();
13545 if (!VT.isSimple())
13548 switch (VT.getSimpleVT().SimpleTy) {
13559 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13560 // i16 instructions are longer (0x66 prefix) and potentially slower.
13561 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13564 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13565 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13566 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13567 /// are assumed to be legal.
13569 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13571 if (!VT.isSimple())
13574 MVT SVT = VT.getSimpleVT();
13576 // Very little shuffling can be done for 64-bit vectors right now.
13577 if (VT.getSizeInBits() == 64)
13580 // FIXME: pshufb, blends, shifts.
13581 return (SVT.getVectorNumElements() == 2 ||
13582 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13583 isMOVLMask(M, SVT) ||
13584 isSHUFPMask(M, SVT, Subtarget->hasFp256()) ||
13585 isPSHUFDMask(M, SVT) ||
13586 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
13587 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
13588 isPALIGNRMask(M, SVT, Subtarget) ||
13589 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
13590 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
13591 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
13592 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
13596 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13598 if (!VT.isSimple())
13601 MVT SVT = VT.getSimpleVT();
13602 unsigned NumElts = SVT.getVectorNumElements();
13603 // FIXME: This collection of masks seems suspect.
13606 if (NumElts == 4 && SVT.is128BitVector()) {
13607 return (isMOVLMask(Mask, SVT) ||
13608 isCommutedMOVLMask(Mask, SVT, true) ||
13609 isSHUFPMask(Mask, SVT, Subtarget->hasFp256()) ||
13610 isSHUFPMask(Mask, SVT, Subtarget->hasFp256(), /* Commuted */ true));
13615 //===----------------------------------------------------------------------===//
13616 // X86 Scheduler Hooks
13617 //===----------------------------------------------------------------------===//
13619 /// Utility function to emit xbegin specifying the start of an RTM region.
13620 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13621 const TargetInstrInfo *TII) {
13622 DebugLoc DL = MI->getDebugLoc();
13624 const BasicBlock *BB = MBB->getBasicBlock();
13625 MachineFunction::iterator I = MBB;
13628 // For the v = xbegin(), we generate
13639 MachineBasicBlock *thisMBB = MBB;
13640 MachineFunction *MF = MBB->getParent();
13641 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13642 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13643 MF->insert(I, mainMBB);
13644 MF->insert(I, sinkMBB);
13646 // Transfer the remainder of BB and its successor edges to sinkMBB.
13647 sinkMBB->splice(sinkMBB->begin(), MBB,
13648 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13649 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13653 // # fallthrough to mainMBB
13654 // # abortion to sinkMBB
13655 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13656 thisMBB->addSuccessor(mainMBB);
13657 thisMBB->addSuccessor(sinkMBB);
13661 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13662 mainMBB->addSuccessor(sinkMBB);
13665 // EAX is live into the sinkMBB
13666 sinkMBB->addLiveIn(X86::EAX);
13667 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13668 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13671 MI->eraseFromParent();
13675 // Get CMPXCHG opcode for the specified data type.
13676 static unsigned getCmpXChgOpcode(EVT VT) {
13677 switch (VT.getSimpleVT().SimpleTy) {
13678 case MVT::i8: return X86::LCMPXCHG8;
13679 case MVT::i16: return X86::LCMPXCHG16;
13680 case MVT::i32: return X86::LCMPXCHG32;
13681 case MVT::i64: return X86::LCMPXCHG64;
13685 llvm_unreachable("Invalid operand size!");
13688 // Get LOAD opcode for the specified data type.
13689 static unsigned getLoadOpcode(EVT VT) {
13690 switch (VT.getSimpleVT().SimpleTy) {
13691 case MVT::i8: return X86::MOV8rm;
13692 case MVT::i16: return X86::MOV16rm;
13693 case MVT::i32: return X86::MOV32rm;
13694 case MVT::i64: return X86::MOV64rm;
13698 llvm_unreachable("Invalid operand size!");
13701 // Get opcode of the non-atomic one from the specified atomic instruction.
13702 static unsigned getNonAtomicOpcode(unsigned Opc) {
13704 case X86::ATOMAND8: return X86::AND8rr;
13705 case X86::ATOMAND16: return X86::AND16rr;
13706 case X86::ATOMAND32: return X86::AND32rr;
13707 case X86::ATOMAND64: return X86::AND64rr;
13708 case X86::ATOMOR8: return X86::OR8rr;
13709 case X86::ATOMOR16: return X86::OR16rr;
13710 case X86::ATOMOR32: return X86::OR32rr;
13711 case X86::ATOMOR64: return X86::OR64rr;
13712 case X86::ATOMXOR8: return X86::XOR8rr;
13713 case X86::ATOMXOR16: return X86::XOR16rr;
13714 case X86::ATOMXOR32: return X86::XOR32rr;
13715 case X86::ATOMXOR64: return X86::XOR64rr;
13717 llvm_unreachable("Unhandled atomic-load-op opcode!");
13720 // Get opcode of the non-atomic one from the specified atomic instruction with
13722 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13723 unsigned &ExtraOpc) {
13725 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
13726 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
13727 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
13728 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
13729 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
13730 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13731 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13732 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13733 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
13734 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13735 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13736 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13737 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
13738 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13739 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13740 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13741 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
13742 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13743 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13744 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13746 llvm_unreachable("Unhandled atomic-load-op opcode!");
13749 // Get opcode of the non-atomic one from the specified atomic instruction for
13750 // 64-bit data type on 32-bit target.
13751 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13753 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
13754 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
13755 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
13756 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
13757 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
13758 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13759 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
13760 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
13761 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
13762 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
13764 llvm_unreachable("Unhandled atomic-load-op opcode!");
13767 // Get opcode of the non-atomic one from the specified atomic instruction for
13768 // 64-bit data type on 32-bit target with extra opcode.
13769 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13771 unsigned &ExtraOpc) {
13773 case X86::ATOMNAND6432:
13774 ExtraOpc = X86::NOT32r;
13775 HiOpc = X86::AND32rr;
13776 return X86::AND32rr;
13778 llvm_unreachable("Unhandled atomic-load-op opcode!");
13781 // Get pseudo CMOV opcode from the specified data type.
13782 static unsigned getPseudoCMOVOpc(EVT VT) {
13783 switch (VT.getSimpleVT().SimpleTy) {
13784 case MVT::i8: return X86::CMOV_GR8;
13785 case MVT::i16: return X86::CMOV_GR16;
13786 case MVT::i32: return X86::CMOV_GR32;
13790 llvm_unreachable("Unknown CMOV opcode!");
13793 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13794 // They will be translated into a spin-loop or compare-exchange loop from
13797 // dst = atomic-fetch-op MI.addr, MI.val
13803 // t1 = LOAD MI.addr
13805 // t4 = phi(t1, t3 / loop)
13806 // t2 = OP MI.val, t4
13808 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13814 MachineBasicBlock *
13815 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13816 MachineBasicBlock *MBB) const {
13817 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13818 DebugLoc DL = MI->getDebugLoc();
13820 MachineFunction *MF = MBB->getParent();
13821 MachineRegisterInfo &MRI = MF->getRegInfo();
13823 const BasicBlock *BB = MBB->getBasicBlock();
13824 MachineFunction::iterator I = MBB;
13827 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13828 "Unexpected number of operands");
13830 assert(MI->hasOneMemOperand() &&
13831 "Expected atomic-load-op to have one memoperand");
13833 // Memory Reference
13834 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13835 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13837 unsigned DstReg, SrcReg;
13838 unsigned MemOpndSlot;
13840 unsigned CurOp = 0;
13842 DstReg = MI->getOperand(CurOp++).getReg();
13843 MemOpndSlot = CurOp;
13844 CurOp += X86::AddrNumOperands;
13845 SrcReg = MI->getOperand(CurOp++).getReg();
13847 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13848 MVT::SimpleValueType VT = *RC->vt_begin();
13849 unsigned t1 = MRI.createVirtualRegister(RC);
13850 unsigned t2 = MRI.createVirtualRegister(RC);
13851 unsigned t3 = MRI.createVirtualRegister(RC);
13852 unsigned t4 = MRI.createVirtualRegister(RC);
13853 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13855 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13856 unsigned LOADOpc = getLoadOpcode(VT);
13858 // For the atomic load-arith operator, we generate
13861 // t1 = LOAD [MI.addr]
13863 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
13864 // t1 = OP MI.val, EAX
13866 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13872 MachineBasicBlock *thisMBB = MBB;
13873 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13874 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13875 MF->insert(I, mainMBB);
13876 MF->insert(I, sinkMBB);
13878 MachineInstrBuilder MIB;
13880 // Transfer the remainder of BB and its successor edges to sinkMBB.
13881 sinkMBB->splice(sinkMBB->begin(), MBB,
13882 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13883 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13886 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13887 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13888 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13890 NewMO.setIsKill(false);
13891 MIB.addOperand(NewMO);
13893 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13894 unsigned flags = (*MMOI)->getFlags();
13895 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13896 MachineMemOperand *MMO =
13897 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13898 (*MMOI)->getSize(),
13899 (*MMOI)->getBaseAlignment(),
13900 (*MMOI)->getTBAAInfo(),
13901 (*MMOI)->getRanges());
13902 MIB.addMemOperand(MMO);
13905 thisMBB->addSuccessor(mainMBB);
13908 MachineBasicBlock *origMainMBB = mainMBB;
13911 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13912 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13914 unsigned Opc = MI->getOpcode();
13917 llvm_unreachable("Unhandled atomic-load-op opcode!");
13918 case X86::ATOMAND8:
13919 case X86::ATOMAND16:
13920 case X86::ATOMAND32:
13921 case X86::ATOMAND64:
13923 case X86::ATOMOR16:
13924 case X86::ATOMOR32:
13925 case X86::ATOMOR64:
13926 case X86::ATOMXOR8:
13927 case X86::ATOMXOR16:
13928 case X86::ATOMXOR32:
13929 case X86::ATOMXOR64: {
13930 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13931 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13935 case X86::ATOMNAND8:
13936 case X86::ATOMNAND16:
13937 case X86::ATOMNAND32:
13938 case X86::ATOMNAND64: {
13939 unsigned Tmp = MRI.createVirtualRegister(RC);
13941 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13942 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13944 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13947 case X86::ATOMMAX8:
13948 case X86::ATOMMAX16:
13949 case X86::ATOMMAX32:
13950 case X86::ATOMMAX64:
13951 case X86::ATOMMIN8:
13952 case X86::ATOMMIN16:
13953 case X86::ATOMMIN32:
13954 case X86::ATOMMIN64:
13955 case X86::ATOMUMAX8:
13956 case X86::ATOMUMAX16:
13957 case X86::ATOMUMAX32:
13958 case X86::ATOMUMAX64:
13959 case X86::ATOMUMIN8:
13960 case X86::ATOMUMIN16:
13961 case X86::ATOMUMIN32:
13962 case X86::ATOMUMIN64: {
13964 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13966 BuildMI(mainMBB, DL, TII->get(CMPOpc))
13970 if (Subtarget->hasCMov()) {
13971 if (VT != MVT::i8) {
13973 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13977 // Promote i8 to i32 to use CMOV32
13978 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13979 const TargetRegisterClass *RC32 =
13980 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13981 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13982 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13983 unsigned Tmp = MRI.createVirtualRegister(RC32);
13985 unsigned Undef = MRI.createVirtualRegister(RC32);
13986 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13988 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13991 .addImm(X86::sub_8bit);
13992 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13995 .addImm(X86::sub_8bit);
13997 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14001 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14002 .addReg(Tmp, 0, X86::sub_8bit);
14005 // Use pseudo select and lower them.
14006 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14007 "Invalid atomic-load-op transformation!");
14008 unsigned SelOpc = getPseudoCMOVOpc(VT);
14009 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14010 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14011 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14012 .addReg(SrcReg).addReg(t4)
14014 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14015 // Replace the original PHI node as mainMBB is changed after CMOV
14017 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14018 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14019 Phi->eraseFromParent();
14025 // Copy PhyReg back from virtual register.
14026 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14029 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14030 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14031 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14033 NewMO.setIsKill(false);
14034 MIB.addOperand(NewMO);
14037 MIB.setMemRefs(MMOBegin, MMOEnd);
14039 // Copy PhyReg back to virtual register.
14040 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14043 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14045 mainMBB->addSuccessor(origMainMBB);
14046 mainMBB->addSuccessor(sinkMBB);
14049 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14050 TII->get(TargetOpcode::COPY), DstReg)
14053 MI->eraseFromParent();
14057 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14058 // instructions. They will be translated into a spin-loop or compare-exchange
14062 // dst = atomic-fetch-op MI.addr, MI.val
14068 // t1L = LOAD [MI.addr + 0]
14069 // t1H = LOAD [MI.addr + 4]
14071 // t4L = phi(t1L, t3L / loop)
14072 // t4H = phi(t1H, t3H / loop)
14073 // t2L = OP MI.val.lo, t4L
14074 // t2H = OP MI.val.hi, t4H
14079 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14087 MachineBasicBlock *
14088 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14089 MachineBasicBlock *MBB) const {
14090 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14091 DebugLoc DL = MI->getDebugLoc();
14093 MachineFunction *MF = MBB->getParent();
14094 MachineRegisterInfo &MRI = MF->getRegInfo();
14096 const BasicBlock *BB = MBB->getBasicBlock();
14097 MachineFunction::iterator I = MBB;
14100 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14101 "Unexpected number of operands");
14103 assert(MI->hasOneMemOperand() &&
14104 "Expected atomic-load-op32 to have one memoperand");
14106 // Memory Reference
14107 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14108 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14110 unsigned DstLoReg, DstHiReg;
14111 unsigned SrcLoReg, SrcHiReg;
14112 unsigned MemOpndSlot;
14114 unsigned CurOp = 0;
14116 DstLoReg = MI->getOperand(CurOp++).getReg();
14117 DstHiReg = MI->getOperand(CurOp++).getReg();
14118 MemOpndSlot = CurOp;
14119 CurOp += X86::AddrNumOperands;
14120 SrcLoReg = MI->getOperand(CurOp++).getReg();
14121 SrcHiReg = MI->getOperand(CurOp++).getReg();
14123 const TargetRegisterClass *RC = &X86::GR32RegClass;
14124 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14126 unsigned t1L = MRI.createVirtualRegister(RC);
14127 unsigned t1H = MRI.createVirtualRegister(RC);
14128 unsigned t2L = MRI.createVirtualRegister(RC);
14129 unsigned t2H = MRI.createVirtualRegister(RC);
14130 unsigned t3L = MRI.createVirtualRegister(RC);
14131 unsigned t3H = MRI.createVirtualRegister(RC);
14132 unsigned t4L = MRI.createVirtualRegister(RC);
14133 unsigned t4H = MRI.createVirtualRegister(RC);
14135 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14136 unsigned LOADOpc = X86::MOV32rm;
14138 // For the atomic load-arith operator, we generate
14141 // t1L = LOAD [MI.addr + 0]
14142 // t1H = LOAD [MI.addr + 4]
14144 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
14145 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
14146 // t2L = OP MI.val.lo, t4L
14147 // t2H = OP MI.val.hi, t4H
14150 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14158 MachineBasicBlock *thisMBB = MBB;
14159 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14160 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14161 MF->insert(I, mainMBB);
14162 MF->insert(I, sinkMBB);
14164 MachineInstrBuilder MIB;
14166 // Transfer the remainder of BB and its successor edges to sinkMBB.
14167 sinkMBB->splice(sinkMBB->begin(), MBB,
14168 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14169 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14173 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14174 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14175 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14177 NewMO.setIsKill(false);
14178 MIB.addOperand(NewMO);
14180 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14181 unsigned flags = (*MMOI)->getFlags();
14182 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14183 MachineMemOperand *MMO =
14184 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14185 (*MMOI)->getSize(),
14186 (*MMOI)->getBaseAlignment(),
14187 (*MMOI)->getTBAAInfo(),
14188 (*MMOI)->getRanges());
14189 MIB.addMemOperand(MMO);
14191 MachineInstr *LowMI = MIB;
14194 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14195 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14196 if (i == X86::AddrDisp) {
14197 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14199 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14201 NewMO.setIsKill(false);
14202 MIB.addOperand(NewMO);
14205 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14207 thisMBB->addSuccessor(mainMBB);
14210 MachineBasicBlock *origMainMBB = mainMBB;
14213 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14214 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14215 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14216 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14218 unsigned Opc = MI->getOpcode();
14221 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14222 case X86::ATOMAND6432:
14223 case X86::ATOMOR6432:
14224 case X86::ATOMXOR6432:
14225 case X86::ATOMADD6432:
14226 case X86::ATOMSUB6432: {
14228 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14229 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14231 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14235 case X86::ATOMNAND6432: {
14236 unsigned HiOpc, NOTOpc;
14237 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14238 unsigned TmpL = MRI.createVirtualRegister(RC);
14239 unsigned TmpH = MRI.createVirtualRegister(RC);
14240 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14242 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14244 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14245 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14248 case X86::ATOMMAX6432:
14249 case X86::ATOMMIN6432:
14250 case X86::ATOMUMAX6432:
14251 case X86::ATOMUMIN6432: {
14253 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14254 unsigned cL = MRI.createVirtualRegister(RC8);
14255 unsigned cH = MRI.createVirtualRegister(RC8);
14256 unsigned cL32 = MRI.createVirtualRegister(RC);
14257 unsigned cH32 = MRI.createVirtualRegister(RC);
14258 unsigned cc = MRI.createVirtualRegister(RC);
14259 // cl := cmp src_lo, lo
14260 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14261 .addReg(SrcLoReg).addReg(t4L);
14262 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14263 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14264 // ch := cmp src_hi, hi
14265 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14266 .addReg(SrcHiReg).addReg(t4H);
14267 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14268 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14269 // cc := if (src_hi == hi) ? cl : ch;
14270 if (Subtarget->hasCMov()) {
14271 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14272 .addReg(cH32).addReg(cL32);
14274 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14275 .addReg(cH32).addReg(cL32)
14276 .addImm(X86::COND_E);
14277 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14279 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14280 if (Subtarget->hasCMov()) {
14281 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14282 .addReg(SrcLoReg).addReg(t4L);
14283 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14284 .addReg(SrcHiReg).addReg(t4H);
14286 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14287 .addReg(SrcLoReg).addReg(t4L)
14288 .addImm(X86::COND_NE);
14289 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14290 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14291 // 2nd CMOV lowering.
14292 mainMBB->addLiveIn(X86::EFLAGS);
14293 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14294 .addReg(SrcHiReg).addReg(t4H)
14295 .addImm(X86::COND_NE);
14296 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14297 // Replace the original PHI node as mainMBB is changed after CMOV
14299 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14300 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14301 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14302 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14303 PhiL->eraseFromParent();
14304 PhiH->eraseFromParent();
14308 case X86::ATOMSWAP6432: {
14310 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14311 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14312 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14317 // Copy EDX:EAX back from HiReg:LoReg
14318 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14319 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14320 // Copy ECX:EBX from t1H:t1L
14321 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14322 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14324 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14325 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14326 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14328 NewMO.setIsKill(false);
14329 MIB.addOperand(NewMO);
14331 MIB.setMemRefs(MMOBegin, MMOEnd);
14333 // Copy EDX:EAX back to t3H:t3L
14334 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14335 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14337 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14339 mainMBB->addSuccessor(origMainMBB);
14340 mainMBB->addSuccessor(sinkMBB);
14343 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14344 TII->get(TargetOpcode::COPY), DstLoReg)
14346 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14347 TII->get(TargetOpcode::COPY), DstHiReg)
14350 MI->eraseFromParent();
14354 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14355 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14356 // in the .td file.
14357 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14358 const TargetInstrInfo *TII) {
14360 switch (MI->getOpcode()) {
14361 default: llvm_unreachable("illegal opcode!");
14362 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
14363 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14364 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
14365 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14366 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
14367 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14368 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
14369 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14372 DebugLoc dl = MI->getDebugLoc();
14373 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14375 unsigned NumArgs = MI->getNumOperands();
14376 for (unsigned i = 1; i < NumArgs; ++i) {
14377 MachineOperand &Op = MI->getOperand(i);
14378 if (!(Op.isReg() && Op.isImplicit()))
14379 MIB.addOperand(Op);
14381 if (MI->hasOneMemOperand())
14382 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14384 BuildMI(*BB, MI, dl,
14385 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14386 .addReg(X86::XMM0);
14388 MI->eraseFromParent();
14392 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14393 // defs in an instruction pattern
14394 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14395 const TargetInstrInfo *TII) {
14397 switch (MI->getOpcode()) {
14398 default: llvm_unreachable("illegal opcode!");
14399 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
14400 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14401 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
14402 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14403 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
14404 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14405 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
14406 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14409 DebugLoc dl = MI->getDebugLoc();
14410 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14412 unsigned NumArgs = MI->getNumOperands(); // remove the results
14413 for (unsigned i = 1; i < NumArgs; ++i) {
14414 MachineOperand &Op = MI->getOperand(i);
14415 if (!(Op.isReg() && Op.isImplicit()))
14416 MIB.addOperand(Op);
14418 if (MI->hasOneMemOperand())
14419 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14421 BuildMI(*BB, MI, dl,
14422 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14425 MI->eraseFromParent();
14429 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14430 const TargetInstrInfo *TII,
14431 const X86Subtarget* Subtarget) {
14432 DebugLoc dl = MI->getDebugLoc();
14434 // Address into RAX/EAX, other two args into ECX, EDX.
14435 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14436 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14437 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14438 for (int i = 0; i < X86::AddrNumOperands; ++i)
14439 MIB.addOperand(MI->getOperand(i));
14441 unsigned ValOps = X86::AddrNumOperands;
14442 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14443 .addReg(MI->getOperand(ValOps).getReg());
14444 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14445 .addReg(MI->getOperand(ValOps+1).getReg());
14447 // The instruction doesn't actually take any operands though.
14448 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14450 MI->eraseFromParent(); // The pseudo is gone now.
14454 MachineBasicBlock *
14455 X86TargetLowering::EmitVAARG64WithCustomInserter(
14457 MachineBasicBlock *MBB) const {
14458 // Emit va_arg instruction on X86-64.
14460 // Operands to this pseudo-instruction:
14461 // 0 ) Output : destination address (reg)
14462 // 1-5) Input : va_list address (addr, i64mem)
14463 // 6 ) ArgSize : Size (in bytes) of vararg type
14464 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14465 // 8 ) Align : Alignment of type
14466 // 9 ) EFLAGS (implicit-def)
14468 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14469 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14471 unsigned DestReg = MI->getOperand(0).getReg();
14472 MachineOperand &Base = MI->getOperand(1);
14473 MachineOperand &Scale = MI->getOperand(2);
14474 MachineOperand &Index = MI->getOperand(3);
14475 MachineOperand &Disp = MI->getOperand(4);
14476 MachineOperand &Segment = MI->getOperand(5);
14477 unsigned ArgSize = MI->getOperand(6).getImm();
14478 unsigned ArgMode = MI->getOperand(7).getImm();
14479 unsigned Align = MI->getOperand(8).getImm();
14481 // Memory Reference
14482 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14483 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14484 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14486 // Machine Information
14487 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14488 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14489 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14490 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14491 DebugLoc DL = MI->getDebugLoc();
14493 // struct va_list {
14496 // i64 overflow_area (address)
14497 // i64 reg_save_area (address)
14499 // sizeof(va_list) = 24
14500 // alignment(va_list) = 8
14502 unsigned TotalNumIntRegs = 6;
14503 unsigned TotalNumXMMRegs = 8;
14504 bool UseGPOffset = (ArgMode == 1);
14505 bool UseFPOffset = (ArgMode == 2);
14506 unsigned MaxOffset = TotalNumIntRegs * 8 +
14507 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14509 /* Align ArgSize to a multiple of 8 */
14510 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14511 bool NeedsAlign = (Align > 8);
14513 MachineBasicBlock *thisMBB = MBB;
14514 MachineBasicBlock *overflowMBB;
14515 MachineBasicBlock *offsetMBB;
14516 MachineBasicBlock *endMBB;
14518 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
14519 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
14520 unsigned OffsetReg = 0;
14522 if (!UseGPOffset && !UseFPOffset) {
14523 // If we only pull from the overflow region, we don't create a branch.
14524 // We don't need to alter control flow.
14525 OffsetDestReg = 0; // unused
14526 OverflowDestReg = DestReg;
14529 overflowMBB = thisMBB;
14532 // First emit code to check if gp_offset (or fp_offset) is below the bound.
14533 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14534 // If not, pull from overflow_area. (branch to overflowMBB)
14539 // offsetMBB overflowMBB
14544 // Registers for the PHI in endMBB
14545 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14546 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14548 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14549 MachineFunction *MF = MBB->getParent();
14550 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14551 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14552 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14554 MachineFunction::iterator MBBIter = MBB;
14557 // Insert the new basic blocks
14558 MF->insert(MBBIter, offsetMBB);
14559 MF->insert(MBBIter, overflowMBB);
14560 MF->insert(MBBIter, endMBB);
14562 // Transfer the remainder of MBB and its successor edges to endMBB.
14563 endMBB->splice(endMBB->begin(), thisMBB,
14564 llvm::next(MachineBasicBlock::iterator(MI)),
14566 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14568 // Make offsetMBB and overflowMBB successors of thisMBB
14569 thisMBB->addSuccessor(offsetMBB);
14570 thisMBB->addSuccessor(overflowMBB);
14572 // endMBB is a successor of both offsetMBB and overflowMBB
14573 offsetMBB->addSuccessor(endMBB);
14574 overflowMBB->addSuccessor(endMBB);
14576 // Load the offset value into a register
14577 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14578 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14582 .addDisp(Disp, UseFPOffset ? 4 : 0)
14583 .addOperand(Segment)
14584 .setMemRefs(MMOBegin, MMOEnd);
14586 // Check if there is enough room left to pull this argument.
14587 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14589 .addImm(MaxOffset + 8 - ArgSizeA8);
14591 // Branch to "overflowMBB" if offset >= max
14592 // Fall through to "offsetMBB" otherwise
14593 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14594 .addMBB(overflowMBB);
14597 // In offsetMBB, emit code to use the reg_save_area.
14599 assert(OffsetReg != 0);
14601 // Read the reg_save_area address.
14602 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14603 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14608 .addOperand(Segment)
14609 .setMemRefs(MMOBegin, MMOEnd);
14611 // Zero-extend the offset
14612 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14613 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14616 .addImm(X86::sub_32bit);
14618 // Add the offset to the reg_save_area to get the final address.
14619 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14620 .addReg(OffsetReg64)
14621 .addReg(RegSaveReg);
14623 // Compute the offset for the next argument
14624 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14625 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14627 .addImm(UseFPOffset ? 16 : 8);
14629 // Store it back into the va_list.
14630 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14634 .addDisp(Disp, UseFPOffset ? 4 : 0)
14635 .addOperand(Segment)
14636 .addReg(NextOffsetReg)
14637 .setMemRefs(MMOBegin, MMOEnd);
14640 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14645 // Emit code to use overflow area
14648 // Load the overflow_area address into a register.
14649 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14650 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14655 .addOperand(Segment)
14656 .setMemRefs(MMOBegin, MMOEnd);
14658 // If we need to align it, do so. Otherwise, just copy the address
14659 // to OverflowDestReg.
14661 // Align the overflow address
14662 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14663 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14665 // aligned_addr = (addr + (align-1)) & ~(align-1)
14666 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14667 .addReg(OverflowAddrReg)
14670 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14672 .addImm(~(uint64_t)(Align-1));
14674 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14675 .addReg(OverflowAddrReg);
14678 // Compute the next overflow address after this argument.
14679 // (the overflow address should be kept 8-byte aligned)
14680 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14681 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14682 .addReg(OverflowDestReg)
14683 .addImm(ArgSizeA8);
14685 // Store the new overflow address.
14686 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14691 .addOperand(Segment)
14692 .addReg(NextAddrReg)
14693 .setMemRefs(MMOBegin, MMOEnd);
14695 // If we branched, emit the PHI to the front of endMBB.
14697 BuildMI(*endMBB, endMBB->begin(), DL,
14698 TII->get(X86::PHI), DestReg)
14699 .addReg(OffsetDestReg).addMBB(offsetMBB)
14700 .addReg(OverflowDestReg).addMBB(overflowMBB);
14703 // Erase the pseudo instruction
14704 MI->eraseFromParent();
14709 MachineBasicBlock *
14710 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14712 MachineBasicBlock *MBB) const {
14713 // Emit code to save XMM registers to the stack. The ABI says that the
14714 // number of registers to save is given in %al, so it's theoretically
14715 // possible to do an indirect jump trick to avoid saving all of them,
14716 // however this code takes a simpler approach and just executes all
14717 // of the stores if %al is non-zero. It's less code, and it's probably
14718 // easier on the hardware branch predictor, and stores aren't all that
14719 // expensive anyway.
14721 // Create the new basic blocks. One block contains all the XMM stores,
14722 // and one block is the final destination regardless of whether any
14723 // stores were performed.
14724 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14725 MachineFunction *F = MBB->getParent();
14726 MachineFunction::iterator MBBIter = MBB;
14728 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14729 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14730 F->insert(MBBIter, XMMSaveMBB);
14731 F->insert(MBBIter, EndMBB);
14733 // Transfer the remainder of MBB and its successor edges to EndMBB.
14734 EndMBB->splice(EndMBB->begin(), MBB,
14735 llvm::next(MachineBasicBlock::iterator(MI)),
14737 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14739 // The original block will now fall through to the XMM save block.
14740 MBB->addSuccessor(XMMSaveMBB);
14741 // The XMMSaveMBB will fall through to the end block.
14742 XMMSaveMBB->addSuccessor(EndMBB);
14744 // Now add the instructions.
14745 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14746 DebugLoc DL = MI->getDebugLoc();
14748 unsigned CountReg = MI->getOperand(0).getReg();
14749 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14750 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14752 if (!Subtarget->isTargetWin64()) {
14753 // If %al is 0, branch around the XMM save block.
14754 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14755 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14756 MBB->addSuccessor(EndMBB);
14759 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14760 // In the XMM save block, save all the XMM argument registers.
14761 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14762 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14763 MachineMemOperand *MMO =
14764 F->getMachineMemOperand(
14765 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14766 MachineMemOperand::MOStore,
14767 /*Size=*/16, /*Align=*/16);
14768 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14769 .addFrameIndex(RegSaveFrameIndex)
14770 .addImm(/*Scale=*/1)
14771 .addReg(/*IndexReg=*/0)
14772 .addImm(/*Disp=*/Offset)
14773 .addReg(/*Segment=*/0)
14774 .addReg(MI->getOperand(i).getReg())
14775 .addMemOperand(MMO);
14778 MI->eraseFromParent(); // The pseudo instruction is gone now.
14783 // The EFLAGS operand of SelectItr might be missing a kill marker
14784 // because there were multiple uses of EFLAGS, and ISel didn't know
14785 // which to mark. Figure out whether SelectItr should have had a
14786 // kill marker, and set it if it should. Returns the correct kill
14788 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14789 MachineBasicBlock* BB,
14790 const TargetRegisterInfo* TRI) {
14791 // Scan forward through BB for a use/def of EFLAGS.
14792 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14793 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14794 const MachineInstr& mi = *miI;
14795 if (mi.readsRegister(X86::EFLAGS))
14797 if (mi.definesRegister(X86::EFLAGS))
14798 break; // Should have kill-flag - update below.
14801 // If we hit the end of the block, check whether EFLAGS is live into a
14803 if (miI == BB->end()) {
14804 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14805 sEnd = BB->succ_end();
14806 sItr != sEnd; ++sItr) {
14807 MachineBasicBlock* succ = *sItr;
14808 if (succ->isLiveIn(X86::EFLAGS))
14813 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14814 // out. SelectMI should have a kill flag on EFLAGS.
14815 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14819 MachineBasicBlock *
14820 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14821 MachineBasicBlock *BB) const {
14822 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14823 DebugLoc DL = MI->getDebugLoc();
14825 // To "insert" a SELECT_CC instruction, we actually have to insert the
14826 // diamond control-flow pattern. The incoming instruction knows the
14827 // destination vreg to set, the condition code register to branch on, the
14828 // true/false values to select between, and a branch opcode to use.
14829 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14830 MachineFunction::iterator It = BB;
14836 // cmpTY ccX, r1, r2
14838 // fallthrough --> copy0MBB
14839 MachineBasicBlock *thisMBB = BB;
14840 MachineFunction *F = BB->getParent();
14841 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14842 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14843 F->insert(It, copy0MBB);
14844 F->insert(It, sinkMBB);
14846 // If the EFLAGS register isn't dead in the terminator, then claim that it's
14847 // live into the sink and copy blocks.
14848 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14849 if (!MI->killsRegister(X86::EFLAGS) &&
14850 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14851 copy0MBB->addLiveIn(X86::EFLAGS);
14852 sinkMBB->addLiveIn(X86::EFLAGS);
14855 // Transfer the remainder of BB and its successor edges to sinkMBB.
14856 sinkMBB->splice(sinkMBB->begin(), BB,
14857 llvm::next(MachineBasicBlock::iterator(MI)),
14859 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14861 // Add the true and fallthrough blocks as its successors.
14862 BB->addSuccessor(copy0MBB);
14863 BB->addSuccessor(sinkMBB);
14865 // Create the conditional branch instruction.
14867 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14868 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14871 // %FalseValue = ...
14872 // # fallthrough to sinkMBB
14873 copy0MBB->addSuccessor(sinkMBB);
14876 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14878 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14879 TII->get(X86::PHI), MI->getOperand(0).getReg())
14880 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14881 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14883 MI->eraseFromParent(); // The pseudo instruction is gone now.
14887 MachineBasicBlock *
14888 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14889 bool Is64Bit) const {
14890 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14891 DebugLoc DL = MI->getDebugLoc();
14892 MachineFunction *MF = BB->getParent();
14893 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14895 assert(getTargetMachine().Options.EnableSegmentedStacks);
14897 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14898 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14901 // ... [Till the alloca]
14902 // If stacklet is not large enough, jump to mallocMBB
14905 // Allocate by subtracting from RSP
14906 // Jump to continueMBB
14909 // Allocate by call to runtime
14913 // [rest of original BB]
14916 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14917 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14918 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14920 MachineRegisterInfo &MRI = MF->getRegInfo();
14921 const TargetRegisterClass *AddrRegClass =
14922 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14924 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14925 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14926 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14927 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14928 sizeVReg = MI->getOperand(1).getReg(),
14929 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14931 MachineFunction::iterator MBBIter = BB;
14934 MF->insert(MBBIter, bumpMBB);
14935 MF->insert(MBBIter, mallocMBB);
14936 MF->insert(MBBIter, continueMBB);
14938 continueMBB->splice(continueMBB->begin(), BB, llvm::next
14939 (MachineBasicBlock::iterator(MI)), BB->end());
14940 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14942 // Add code to the main basic block to check if the stack limit has been hit,
14943 // and if so, jump to mallocMBB otherwise to bumpMBB.
14944 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14945 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14946 .addReg(tmpSPVReg).addReg(sizeVReg);
14947 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14948 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14949 .addReg(SPLimitVReg);
14950 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14952 // bumpMBB simply decreases the stack pointer, since we know the current
14953 // stacklet has enough space.
14954 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14955 .addReg(SPLimitVReg);
14956 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14957 .addReg(SPLimitVReg);
14958 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14960 // Calls into a routine in libgcc to allocate more space from the heap.
14961 const uint32_t *RegMask =
14962 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14964 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14966 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14967 .addExternalSymbol("__morestack_allocate_stack_space")
14968 .addRegMask(RegMask)
14969 .addReg(X86::RDI, RegState::Implicit)
14970 .addReg(X86::RAX, RegState::ImplicitDefine);
14972 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14974 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14975 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14976 .addExternalSymbol("__morestack_allocate_stack_space")
14977 .addRegMask(RegMask)
14978 .addReg(X86::EAX, RegState::ImplicitDefine);
14982 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14985 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14986 .addReg(Is64Bit ? X86::RAX : X86::EAX);
14987 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14989 // Set up the CFG correctly.
14990 BB->addSuccessor(bumpMBB);
14991 BB->addSuccessor(mallocMBB);
14992 mallocMBB->addSuccessor(continueMBB);
14993 bumpMBB->addSuccessor(continueMBB);
14995 // Take care of the PHI nodes.
14996 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14997 MI->getOperand(0).getReg())
14998 .addReg(mallocPtrVReg).addMBB(mallocMBB)
14999 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15001 // Delete the original pseudo instruction.
15002 MI->eraseFromParent();
15005 return continueMBB;
15008 MachineBasicBlock *
15009 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15010 MachineBasicBlock *BB) const {
15011 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15012 DebugLoc DL = MI->getDebugLoc();
15014 assert(!Subtarget->isTargetEnvMacho());
15016 // The lowering is pretty easy: we're just emitting the call to _alloca. The
15017 // non-trivial part is impdef of ESP.
15019 if (Subtarget->isTargetWin64()) {
15020 if (Subtarget->isTargetCygMing()) {
15021 // ___chkstk(Mingw64):
15022 // Clobbers R10, R11, RAX and EFLAGS.
15024 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15025 .addExternalSymbol("___chkstk")
15026 .addReg(X86::RAX, RegState::Implicit)
15027 .addReg(X86::RSP, RegState::Implicit)
15028 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15029 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15030 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15032 // __chkstk(MSVCRT): does not update stack pointer.
15033 // Clobbers R10, R11 and EFLAGS.
15034 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15035 .addExternalSymbol("__chkstk")
15036 .addReg(X86::RAX, RegState::Implicit)
15037 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15038 // RAX has the offset to be subtracted from RSP.
15039 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15044 const char *StackProbeSymbol =
15045 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15047 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15048 .addExternalSymbol(StackProbeSymbol)
15049 .addReg(X86::EAX, RegState::Implicit)
15050 .addReg(X86::ESP, RegState::Implicit)
15051 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15052 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15053 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15056 MI->eraseFromParent(); // The pseudo instruction is gone now.
15060 MachineBasicBlock *
15061 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15062 MachineBasicBlock *BB) const {
15063 // This is pretty easy. We're taking the value that we received from
15064 // our load from the relocation, sticking it in either RDI (x86-64)
15065 // or EAX and doing an indirect call. The return value will then
15066 // be in the normal return register.
15067 const X86InstrInfo *TII
15068 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15069 DebugLoc DL = MI->getDebugLoc();
15070 MachineFunction *F = BB->getParent();
15072 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15073 assert(MI->getOperand(3).isGlobal() && "This should be a global");
15075 // Get a register mask for the lowered call.
15076 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15077 // proper register mask.
15078 const uint32_t *RegMask =
15079 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15080 if (Subtarget->is64Bit()) {
15081 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15082 TII->get(X86::MOV64rm), X86::RDI)
15084 .addImm(0).addReg(0)
15085 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15086 MI->getOperand(3).getTargetFlags())
15088 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15089 addDirectMem(MIB, X86::RDI);
15090 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15091 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15092 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15093 TII->get(X86::MOV32rm), X86::EAX)
15095 .addImm(0).addReg(0)
15096 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15097 MI->getOperand(3).getTargetFlags())
15099 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15100 addDirectMem(MIB, X86::EAX);
15101 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15103 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15104 TII->get(X86::MOV32rm), X86::EAX)
15105 .addReg(TII->getGlobalBaseReg(F))
15106 .addImm(0).addReg(0)
15107 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15108 MI->getOperand(3).getTargetFlags())
15110 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15111 addDirectMem(MIB, X86::EAX);
15112 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15115 MI->eraseFromParent(); // The pseudo instruction is gone now.
15119 MachineBasicBlock *
15120 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15121 MachineBasicBlock *MBB) const {
15122 DebugLoc DL = MI->getDebugLoc();
15123 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15125 MachineFunction *MF = MBB->getParent();
15126 MachineRegisterInfo &MRI = MF->getRegInfo();
15128 const BasicBlock *BB = MBB->getBasicBlock();
15129 MachineFunction::iterator I = MBB;
15132 // Memory Reference
15133 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15134 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15137 unsigned MemOpndSlot = 0;
15139 unsigned CurOp = 0;
15141 DstReg = MI->getOperand(CurOp++).getReg();
15142 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15143 assert(RC->hasType(MVT::i32) && "Invalid destination!");
15144 unsigned mainDstReg = MRI.createVirtualRegister(RC);
15145 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15147 MemOpndSlot = CurOp;
15149 MVT PVT = getPointerTy();
15150 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15151 "Invalid Pointer Size!");
15153 // For v = setjmp(buf), we generate
15156 // buf[LabelOffset] = restoreMBB
15157 // SjLjSetup restoreMBB
15163 // v = phi(main, restore)
15168 MachineBasicBlock *thisMBB = MBB;
15169 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15170 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15171 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15172 MF->insert(I, mainMBB);
15173 MF->insert(I, sinkMBB);
15174 MF->push_back(restoreMBB);
15176 MachineInstrBuilder MIB;
15178 // Transfer the remainder of BB and its successor edges to sinkMBB.
15179 sinkMBB->splice(sinkMBB->begin(), MBB,
15180 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15181 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15184 unsigned PtrStoreOpc = 0;
15185 unsigned LabelReg = 0;
15186 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15187 Reloc::Model RM = getTargetMachine().getRelocationModel();
15188 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15189 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15191 // Prepare IP either in reg or imm.
15192 if (!UseImmLabel) {
15193 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15194 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15195 LabelReg = MRI.createVirtualRegister(PtrRC);
15196 if (Subtarget->is64Bit()) {
15197 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15201 .addMBB(restoreMBB)
15204 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15205 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15206 .addReg(XII->getGlobalBaseReg(MF))
15209 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15213 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15215 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15216 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15217 if (i == X86::AddrDisp)
15218 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15220 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15223 MIB.addReg(LabelReg);
15225 MIB.addMBB(restoreMBB);
15226 MIB.setMemRefs(MMOBegin, MMOEnd);
15228 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15229 .addMBB(restoreMBB);
15231 const X86RegisterInfo *RegInfo =
15232 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15233 MIB.addRegMask(RegInfo->getNoPreservedMask());
15234 thisMBB->addSuccessor(mainMBB);
15235 thisMBB->addSuccessor(restoreMBB);
15239 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15240 mainMBB->addSuccessor(sinkMBB);
15243 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15244 TII->get(X86::PHI), DstReg)
15245 .addReg(mainDstReg).addMBB(mainMBB)
15246 .addReg(restoreDstReg).addMBB(restoreMBB);
15249 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15250 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15251 restoreMBB->addSuccessor(sinkMBB);
15253 MI->eraseFromParent();
15257 MachineBasicBlock *
15258 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15259 MachineBasicBlock *MBB) const {
15260 DebugLoc DL = MI->getDebugLoc();
15261 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15263 MachineFunction *MF = MBB->getParent();
15264 MachineRegisterInfo &MRI = MF->getRegInfo();
15266 // Memory Reference
15267 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15268 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15270 MVT PVT = getPointerTy();
15271 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15272 "Invalid Pointer Size!");
15274 const TargetRegisterClass *RC =
15275 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15276 unsigned Tmp = MRI.createVirtualRegister(RC);
15277 // Since FP is only updated here but NOT referenced, it's treated as GPR.
15278 const X86RegisterInfo *RegInfo =
15279 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15280 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15281 unsigned SP = RegInfo->getStackRegister();
15283 MachineInstrBuilder MIB;
15285 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15286 const int64_t SPOffset = 2 * PVT.getStoreSize();
15288 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15289 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15292 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15293 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15294 MIB.addOperand(MI->getOperand(i));
15295 MIB.setMemRefs(MMOBegin, MMOEnd);
15297 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15298 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15299 if (i == X86::AddrDisp)
15300 MIB.addDisp(MI->getOperand(i), LabelOffset);
15302 MIB.addOperand(MI->getOperand(i));
15304 MIB.setMemRefs(MMOBegin, MMOEnd);
15306 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15307 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15308 if (i == X86::AddrDisp)
15309 MIB.addDisp(MI->getOperand(i), SPOffset);
15311 MIB.addOperand(MI->getOperand(i));
15313 MIB.setMemRefs(MMOBegin, MMOEnd);
15315 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15317 MI->eraseFromParent();
15321 MachineBasicBlock *
15322 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15323 MachineBasicBlock *BB) const {
15324 switch (MI->getOpcode()) {
15325 default: llvm_unreachable("Unexpected instr type to insert");
15326 case X86::TAILJMPd64:
15327 case X86::TAILJMPr64:
15328 case X86::TAILJMPm64:
15329 llvm_unreachable("TAILJMP64 would not be touched here.");
15330 case X86::TCRETURNdi64:
15331 case X86::TCRETURNri64:
15332 case X86::TCRETURNmi64:
15334 case X86::WIN_ALLOCA:
15335 return EmitLoweredWinAlloca(MI, BB);
15336 case X86::SEG_ALLOCA_32:
15337 return EmitLoweredSegAlloca(MI, BB, false);
15338 case X86::SEG_ALLOCA_64:
15339 return EmitLoweredSegAlloca(MI, BB, true);
15340 case X86::TLSCall_32:
15341 case X86::TLSCall_64:
15342 return EmitLoweredTLSCall(MI, BB);
15343 case X86::CMOV_GR8:
15344 case X86::CMOV_FR32:
15345 case X86::CMOV_FR64:
15346 case X86::CMOV_V4F32:
15347 case X86::CMOV_V2F64:
15348 case X86::CMOV_V2I64:
15349 case X86::CMOV_V8F32:
15350 case X86::CMOV_V4F64:
15351 case X86::CMOV_V4I64:
15352 case X86::CMOV_GR16:
15353 case X86::CMOV_GR32:
15354 case X86::CMOV_RFP32:
15355 case X86::CMOV_RFP64:
15356 case X86::CMOV_RFP80:
15357 return EmitLoweredSelect(MI, BB);
15359 case X86::FP32_TO_INT16_IN_MEM:
15360 case X86::FP32_TO_INT32_IN_MEM:
15361 case X86::FP32_TO_INT64_IN_MEM:
15362 case X86::FP64_TO_INT16_IN_MEM:
15363 case X86::FP64_TO_INT32_IN_MEM:
15364 case X86::FP64_TO_INT64_IN_MEM:
15365 case X86::FP80_TO_INT16_IN_MEM:
15366 case X86::FP80_TO_INT32_IN_MEM:
15367 case X86::FP80_TO_INT64_IN_MEM: {
15368 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15369 DebugLoc DL = MI->getDebugLoc();
15371 // Change the floating point control register to use "round towards zero"
15372 // mode when truncating to an integer value.
15373 MachineFunction *F = BB->getParent();
15374 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15375 addFrameReference(BuildMI(*BB, MI, DL,
15376 TII->get(X86::FNSTCW16m)), CWFrameIdx);
15378 // Load the old value of the high byte of the control word...
15380 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15381 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15384 // Set the high part to be round to zero...
15385 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15388 // Reload the modified control word now...
15389 addFrameReference(BuildMI(*BB, MI, DL,
15390 TII->get(X86::FLDCW16m)), CWFrameIdx);
15392 // Restore the memory image of control word to original value
15393 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15396 // Get the X86 opcode to use.
15398 switch (MI->getOpcode()) {
15399 default: llvm_unreachable("illegal opcode!");
15400 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15401 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15402 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15403 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15404 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15405 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15406 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15407 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15408 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15412 MachineOperand &Op = MI->getOperand(0);
15414 AM.BaseType = X86AddressMode::RegBase;
15415 AM.Base.Reg = Op.getReg();
15417 AM.BaseType = X86AddressMode::FrameIndexBase;
15418 AM.Base.FrameIndex = Op.getIndex();
15420 Op = MI->getOperand(1);
15422 AM.Scale = Op.getImm();
15423 Op = MI->getOperand(2);
15425 AM.IndexReg = Op.getImm();
15426 Op = MI->getOperand(3);
15427 if (Op.isGlobal()) {
15428 AM.GV = Op.getGlobal();
15430 AM.Disp = Op.getImm();
15432 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15433 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15435 // Reload the original control word now.
15436 addFrameReference(BuildMI(*BB, MI, DL,
15437 TII->get(X86::FLDCW16m)), CWFrameIdx);
15439 MI->eraseFromParent(); // The pseudo instruction is gone now.
15442 // String/text processing lowering.
15443 case X86::PCMPISTRM128REG:
15444 case X86::VPCMPISTRM128REG:
15445 case X86::PCMPISTRM128MEM:
15446 case X86::VPCMPISTRM128MEM:
15447 case X86::PCMPESTRM128REG:
15448 case X86::VPCMPESTRM128REG:
15449 case X86::PCMPESTRM128MEM:
15450 case X86::VPCMPESTRM128MEM:
15451 assert(Subtarget->hasSSE42() &&
15452 "Target must have SSE4.2 or AVX features enabled");
15453 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15455 // String/text processing lowering.
15456 case X86::PCMPISTRIREG:
15457 case X86::VPCMPISTRIREG:
15458 case X86::PCMPISTRIMEM:
15459 case X86::VPCMPISTRIMEM:
15460 case X86::PCMPESTRIREG:
15461 case X86::VPCMPESTRIREG:
15462 case X86::PCMPESTRIMEM:
15463 case X86::VPCMPESTRIMEM:
15464 assert(Subtarget->hasSSE42() &&
15465 "Target must have SSE4.2 or AVX features enabled");
15466 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15468 // Thread synchronization.
15470 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15474 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15476 // Atomic Lowering.
15477 case X86::ATOMAND8:
15478 case X86::ATOMAND16:
15479 case X86::ATOMAND32:
15480 case X86::ATOMAND64:
15483 case X86::ATOMOR16:
15484 case X86::ATOMOR32:
15485 case X86::ATOMOR64:
15487 case X86::ATOMXOR16:
15488 case X86::ATOMXOR8:
15489 case X86::ATOMXOR32:
15490 case X86::ATOMXOR64:
15492 case X86::ATOMNAND8:
15493 case X86::ATOMNAND16:
15494 case X86::ATOMNAND32:
15495 case X86::ATOMNAND64:
15497 case X86::ATOMMAX8:
15498 case X86::ATOMMAX16:
15499 case X86::ATOMMAX32:
15500 case X86::ATOMMAX64:
15502 case X86::ATOMMIN8:
15503 case X86::ATOMMIN16:
15504 case X86::ATOMMIN32:
15505 case X86::ATOMMIN64:
15507 case X86::ATOMUMAX8:
15508 case X86::ATOMUMAX16:
15509 case X86::ATOMUMAX32:
15510 case X86::ATOMUMAX64:
15512 case X86::ATOMUMIN8:
15513 case X86::ATOMUMIN16:
15514 case X86::ATOMUMIN32:
15515 case X86::ATOMUMIN64:
15516 return EmitAtomicLoadArith(MI, BB);
15518 // This group does 64-bit operations on a 32-bit host.
15519 case X86::ATOMAND6432:
15520 case X86::ATOMOR6432:
15521 case X86::ATOMXOR6432:
15522 case X86::ATOMNAND6432:
15523 case X86::ATOMADD6432:
15524 case X86::ATOMSUB6432:
15525 case X86::ATOMMAX6432:
15526 case X86::ATOMMIN6432:
15527 case X86::ATOMUMAX6432:
15528 case X86::ATOMUMIN6432:
15529 case X86::ATOMSWAP6432:
15530 return EmitAtomicLoadArith6432(MI, BB);
15532 case X86::VASTART_SAVE_XMM_REGS:
15533 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15535 case X86::VAARG_64:
15536 return EmitVAARG64WithCustomInserter(MI, BB);
15538 case X86::EH_SjLj_SetJmp32:
15539 case X86::EH_SjLj_SetJmp64:
15540 return emitEHSjLjSetJmp(MI, BB);
15542 case X86::EH_SjLj_LongJmp32:
15543 case X86::EH_SjLj_LongJmp64:
15544 return emitEHSjLjLongJmp(MI, BB);
15548 //===----------------------------------------------------------------------===//
15549 // X86 Optimization Hooks
15550 //===----------------------------------------------------------------------===//
15552 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15555 const SelectionDAG &DAG,
15556 unsigned Depth) const {
15557 unsigned BitWidth = KnownZero.getBitWidth();
15558 unsigned Opc = Op.getOpcode();
15559 assert((Opc >= ISD::BUILTIN_OP_END ||
15560 Opc == ISD::INTRINSIC_WO_CHAIN ||
15561 Opc == ISD::INTRINSIC_W_CHAIN ||
15562 Opc == ISD::INTRINSIC_VOID) &&
15563 "Should use MaskedValueIsZero if you don't know whether Op"
15564 " is a target node!");
15566 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
15580 // These nodes' second result is a boolean.
15581 if (Op.getResNo() == 0)
15584 case X86ISD::SETCC:
15585 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15587 case ISD::INTRINSIC_WO_CHAIN: {
15588 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15589 unsigned NumLoBits = 0;
15592 case Intrinsic::x86_sse_movmsk_ps:
15593 case Intrinsic::x86_avx_movmsk_ps_256:
15594 case Intrinsic::x86_sse2_movmsk_pd:
15595 case Intrinsic::x86_avx_movmsk_pd_256:
15596 case Intrinsic::x86_mmx_pmovmskb:
15597 case Intrinsic::x86_sse2_pmovmskb_128:
15598 case Intrinsic::x86_avx2_pmovmskb: {
15599 // High bits of movmskp{s|d}, pmovmskb are known zero.
15601 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15602 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
15603 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
15604 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
15605 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
15606 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
15607 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
15608 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
15610 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15619 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15620 unsigned Depth) const {
15621 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15622 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15623 return Op.getValueType().getScalarType().getSizeInBits();
15629 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15630 /// node is a GlobalAddress + offset.
15631 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15632 const GlobalValue* &GA,
15633 int64_t &Offset) const {
15634 if (N->getOpcode() == X86ISD::Wrapper) {
15635 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15636 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15637 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15641 return TargetLowering::isGAPlusOffset(N, GA, Offset);
15644 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15645 /// same as extracting the high 128-bit part of 256-bit vector and then
15646 /// inserting the result into the low part of a new 256-bit vector
15647 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15648 EVT VT = SVOp->getValueType(0);
15649 unsigned NumElems = VT.getVectorNumElements();
15651 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15652 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15653 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15654 SVOp->getMaskElt(j) >= 0)
15660 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15661 /// same as extracting the low 128-bit part of 256-bit vector and then
15662 /// inserting the result into the high part of a new 256-bit vector
15663 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15664 EVT VT = SVOp->getValueType(0);
15665 unsigned NumElems = VT.getVectorNumElements();
15667 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15668 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15669 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15670 SVOp->getMaskElt(j) >= 0)
15676 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15677 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15678 TargetLowering::DAGCombinerInfo &DCI,
15679 const X86Subtarget* Subtarget) {
15681 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15682 SDValue V1 = SVOp->getOperand(0);
15683 SDValue V2 = SVOp->getOperand(1);
15684 EVT VT = SVOp->getValueType(0);
15685 unsigned NumElems = VT.getVectorNumElements();
15687 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15688 V2.getOpcode() == ISD::CONCAT_VECTORS) {
15692 // V UNDEF BUILD_VECTOR UNDEF
15694 // CONCAT_VECTOR CONCAT_VECTOR
15697 // RESULT: V + zero extended
15699 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15700 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15701 V1.getOperand(1).getOpcode() != ISD::UNDEF)
15704 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15707 // To match the shuffle mask, the first half of the mask should
15708 // be exactly the first vector, and all the rest a splat with the
15709 // first element of the second one.
15710 for (unsigned i = 0; i != NumElems/2; ++i)
15711 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15712 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15715 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15716 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15717 if (Ld->hasNUsesOfValue(1, 0)) {
15718 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15719 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15721 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15722 array_lengthof(Ops),
15724 Ld->getPointerInfo(),
15725 Ld->getAlignment(),
15726 false/*isVolatile*/, true/*ReadMem*/,
15727 false/*WriteMem*/);
15729 // Make sure the newly-created LOAD is in the same position as Ld in
15730 // terms of dependency. We create a TokenFactor for Ld and ResNode,
15731 // and update uses of Ld's output chain to use the TokenFactor.
15732 if (Ld->hasAnyUseOfValue(1)) {
15733 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15734 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15735 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15736 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15737 SDValue(ResNode.getNode(), 1));
15740 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15744 // Emit a zeroed vector and insert the desired subvector on its
15746 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15747 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15748 return DCI.CombineTo(N, InsV);
15751 //===--------------------------------------------------------------------===//
15752 // Combine some shuffles into subvector extracts and inserts:
15755 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15756 if (isShuffleHigh128VectorInsertLow(SVOp)) {
15757 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15758 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15759 return DCI.CombineTo(N, InsV);
15762 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15763 if (isShuffleLow128VectorInsertHigh(SVOp)) {
15764 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15765 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15766 return DCI.CombineTo(N, InsV);
15772 /// PerformShuffleCombine - Performs several different shuffle combines.
15773 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15774 TargetLowering::DAGCombinerInfo &DCI,
15775 const X86Subtarget *Subtarget) {
15777 EVT VT = N->getValueType(0);
15779 // Don't create instructions with illegal types after legalize types has run.
15780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15781 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15784 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15785 if (Subtarget->hasFp256() && VT.is256BitVector() &&
15786 N->getOpcode() == ISD::VECTOR_SHUFFLE)
15787 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15789 // Only handle 128 wide vector from here on.
15790 if (!VT.is128BitVector())
15793 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15794 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15795 // consecutive, non-overlapping, and in the right order.
15796 SmallVector<SDValue, 16> Elts;
15797 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15798 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15800 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15803 /// PerformTruncateCombine - Converts truncate operation to
15804 /// a sequence of vector shuffle operations.
15805 /// It is possible when we truncate 256-bit vector to 128-bit vector
15806 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15807 TargetLowering::DAGCombinerInfo &DCI,
15808 const X86Subtarget *Subtarget) {
15812 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15813 /// specific shuffle of a load can be folded into a single element load.
15814 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15815 /// shuffles have been customed lowered so we need to handle those here.
15816 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15817 TargetLowering::DAGCombinerInfo &DCI) {
15818 if (DCI.isBeforeLegalizeOps())
15821 SDValue InVec = N->getOperand(0);
15822 SDValue EltNo = N->getOperand(1);
15824 if (!isa<ConstantSDNode>(EltNo))
15827 EVT VT = InVec.getValueType();
15829 bool HasShuffleIntoBitcast = false;
15830 if (InVec.getOpcode() == ISD::BITCAST) {
15831 // Don't duplicate a load with other uses.
15832 if (!InVec.hasOneUse())
15834 EVT BCVT = InVec.getOperand(0).getValueType();
15835 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15837 InVec = InVec.getOperand(0);
15838 HasShuffleIntoBitcast = true;
15841 if (!isTargetShuffle(InVec.getOpcode()))
15844 // Don't duplicate a load with other uses.
15845 if (!InVec.hasOneUse())
15848 SmallVector<int, 16> ShuffleMask;
15850 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15854 // Select the input vector, guarding against out of range extract vector.
15855 unsigned NumElems = VT.getVectorNumElements();
15856 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15857 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15858 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15859 : InVec.getOperand(1);
15861 // If inputs to shuffle are the same for both ops, then allow 2 uses
15862 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15864 if (LdNode.getOpcode() == ISD::BITCAST) {
15865 // Don't duplicate a load with other uses.
15866 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15869 AllowedUses = 1; // only allow 1 load use if we have a bitcast
15870 LdNode = LdNode.getOperand(0);
15873 if (!ISD::isNormalLoad(LdNode.getNode()))
15876 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15878 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15881 if (HasShuffleIntoBitcast) {
15882 // If there's a bitcast before the shuffle, check if the load type and
15883 // alignment is valid.
15884 unsigned Align = LN0->getAlignment();
15885 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15886 unsigned NewAlign = TLI.getDataLayout()->
15887 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15889 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15893 // All checks match so transform back to vector_shuffle so that DAG combiner
15894 // can finish the job
15897 // Create shuffle node taking into account the case that its a unary shuffle
15898 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15899 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15900 InVec.getOperand(0), Shuffle,
15902 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15903 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15907 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15908 /// generation and convert it from being a bunch of shuffles and extracts
15909 /// to a simple store and scalar loads to extract the elements.
15910 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15911 TargetLowering::DAGCombinerInfo &DCI) {
15912 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15913 if (NewOp.getNode())
15916 SDValue InputVector = N->getOperand(0);
15917 // Detect whether we are trying to convert from mmx to i32 and the bitcast
15918 // from mmx to v2i32 has a single usage.
15919 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15920 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15921 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15922 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15923 N->getValueType(0),
15924 InputVector.getNode()->getOperand(0));
15926 // Only operate on vectors of 4 elements, where the alternative shuffling
15927 // gets to be more expensive.
15928 if (InputVector.getValueType() != MVT::v4i32)
15931 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15932 // single use which is a sign-extend or zero-extend, and all elements are
15934 SmallVector<SDNode *, 4> Uses;
15935 unsigned ExtractedElements = 0;
15936 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15937 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15938 if (UI.getUse().getResNo() != InputVector.getResNo())
15941 SDNode *Extract = *UI;
15942 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15945 if (Extract->getValueType(0) != MVT::i32)
15947 if (!Extract->hasOneUse())
15949 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15950 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15952 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15955 // Record which element was extracted.
15956 ExtractedElements |=
15957 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15959 Uses.push_back(Extract);
15962 // If not all the elements were used, this may not be worthwhile.
15963 if (ExtractedElements != 15)
15966 // Ok, we've now decided to do the transformation.
15967 SDLoc dl(InputVector);
15969 // Store the value to a temporary stack slot.
15970 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15971 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15972 MachinePointerInfo(), false, false, 0);
15974 // Replace each use (extract) with a load of the appropriate element.
15975 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15976 UE = Uses.end(); UI != UE; ++UI) {
15977 SDNode *Extract = *UI;
15979 // cOMpute the element's address.
15980 SDValue Idx = Extract->getOperand(1);
15982 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15983 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15985 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15987 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15988 StackPtr, OffsetVal);
15990 // Load the scalar.
15991 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15992 ScalarAddr, MachinePointerInfo(),
15993 false, false, false, 0);
15995 // Replace the exact with the load.
15996 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15999 // The replacement was made in place; don't return anything.
16003 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16004 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
16005 SDValue RHS, SelectionDAG &DAG,
16006 const X86Subtarget *Subtarget) {
16007 if (!VT.isVector())
16010 switch (VT.getSimpleVT().SimpleTy) {
16015 if (!Subtarget->hasAVX2())
16020 if (!Subtarget->hasSSE2())
16024 // SSE2 has only a small subset of the operations.
16025 bool hasUnsigned = Subtarget->hasSSE41() ||
16026 (Subtarget->hasSSE2() && VT == MVT::v16i8);
16027 bool hasSigned = Subtarget->hasSSE41() ||
16028 (Subtarget->hasSSE2() && VT == MVT::v8i16);
16030 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16032 // Check for x CC y ? x : y.
16033 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16034 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16039 return hasUnsigned ? X86ISD::UMIN : 0;
16042 return hasUnsigned ? X86ISD::UMAX : 0;
16045 return hasSigned ? X86ISD::SMIN : 0;
16048 return hasSigned ? X86ISD::SMAX : 0;
16050 // Check for x CC y ? y : x -- a min/max with reversed arms.
16051 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16052 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16057 return hasUnsigned ? X86ISD::UMAX : 0;
16060 return hasUnsigned ? X86ISD::UMIN : 0;
16063 return hasSigned ? X86ISD::SMAX : 0;
16066 return hasSigned ? X86ISD::SMIN : 0;
16073 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16075 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16076 TargetLowering::DAGCombinerInfo &DCI,
16077 const X86Subtarget *Subtarget) {
16079 SDValue Cond = N->getOperand(0);
16080 // Get the LHS/RHS of the select.
16081 SDValue LHS = N->getOperand(1);
16082 SDValue RHS = N->getOperand(2);
16083 EVT VT = LHS.getValueType();
16085 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16086 // instructions match the semantics of the common C idiom x<y?x:y but not
16087 // x<=y?x:y, because of how they handle negative zero (which can be
16088 // ignored in unsafe-math mode).
16089 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16090 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16091 (Subtarget->hasSSE2() ||
16092 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16093 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16095 unsigned Opcode = 0;
16096 // Check for x CC y ? x : y.
16097 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16098 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16102 // Converting this to a min would handle NaNs incorrectly, and swapping
16103 // the operands would cause it to handle comparisons between positive
16104 // and negative zero incorrectly.
16105 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16106 if (!DAG.getTarget().Options.UnsafeFPMath &&
16107 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16109 std::swap(LHS, RHS);
16111 Opcode = X86ISD::FMIN;
16114 // Converting this to a min would handle comparisons between positive
16115 // and negative zero incorrectly.
16116 if (!DAG.getTarget().Options.UnsafeFPMath &&
16117 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16119 Opcode = X86ISD::FMIN;
16122 // Converting this to a min would handle both negative zeros and NaNs
16123 // incorrectly, but we can swap the operands to fix both.
16124 std::swap(LHS, RHS);
16128 Opcode = X86ISD::FMIN;
16132 // Converting this to a max would handle comparisons between positive
16133 // and negative zero incorrectly.
16134 if (!DAG.getTarget().Options.UnsafeFPMath &&
16135 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16137 Opcode = X86ISD::FMAX;
16140 // Converting this to a max would handle NaNs incorrectly, and swapping
16141 // the operands would cause it to handle comparisons between positive
16142 // and negative zero incorrectly.
16143 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16144 if (!DAG.getTarget().Options.UnsafeFPMath &&
16145 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16147 std::swap(LHS, RHS);
16149 Opcode = X86ISD::FMAX;
16152 // Converting this to a max would handle both negative zeros and NaNs
16153 // incorrectly, but we can swap the operands to fix both.
16154 std::swap(LHS, RHS);
16158 Opcode = X86ISD::FMAX;
16161 // Check for x CC y ? y : x -- a min/max with reversed arms.
16162 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16163 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16167 // Converting this to a min would handle comparisons between positive
16168 // and negative zero incorrectly, and swapping the operands would
16169 // cause it to handle NaNs incorrectly.
16170 if (!DAG.getTarget().Options.UnsafeFPMath &&
16171 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16172 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16174 std::swap(LHS, RHS);
16176 Opcode = X86ISD::FMIN;
16179 // Converting this to a min would handle NaNs incorrectly.
16180 if (!DAG.getTarget().Options.UnsafeFPMath &&
16181 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16183 Opcode = X86ISD::FMIN;
16186 // Converting this to a min would handle both negative zeros and NaNs
16187 // incorrectly, but we can swap the operands to fix both.
16188 std::swap(LHS, RHS);
16192 Opcode = X86ISD::FMIN;
16196 // Converting this to a max would handle NaNs incorrectly.
16197 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16199 Opcode = X86ISD::FMAX;
16202 // Converting this to a max would handle comparisons between positive
16203 // and negative zero incorrectly, and swapping the operands would
16204 // cause it to handle NaNs incorrectly.
16205 if (!DAG.getTarget().Options.UnsafeFPMath &&
16206 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16207 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16209 std::swap(LHS, RHS);
16211 Opcode = X86ISD::FMAX;
16214 // Converting this to a max would handle both negative zeros and NaNs
16215 // incorrectly, but we can swap the operands to fix both.
16216 std::swap(LHS, RHS);
16220 Opcode = X86ISD::FMAX;
16226 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16229 // If this is a select between two integer constants, try to do some
16231 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16232 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16233 // Don't do this for crazy integer types.
16234 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16235 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16236 // so that TrueC (the true value) is larger than FalseC.
16237 bool NeedsCondInvert = false;
16239 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16240 // Efficiently invertible.
16241 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
16242 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
16243 isa<ConstantSDNode>(Cond.getOperand(1))))) {
16244 NeedsCondInvert = true;
16245 std::swap(TrueC, FalseC);
16248 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
16249 if (FalseC->getAPIntValue() == 0 &&
16250 TrueC->getAPIntValue().isPowerOf2()) {
16251 if (NeedsCondInvert) // Invert the condition if needed.
16252 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16253 DAG.getConstant(1, Cond.getValueType()));
16255 // Zero extend the condition if needed.
16256 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16258 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16259 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16260 DAG.getConstant(ShAmt, MVT::i8));
16263 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16264 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16265 if (NeedsCondInvert) // Invert the condition if needed.
16266 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16267 DAG.getConstant(1, Cond.getValueType()));
16269 // Zero extend the condition if needed.
16270 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16271 FalseC->getValueType(0), Cond);
16272 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16273 SDValue(FalseC, 0));
16276 // Optimize cases that will turn into an LEA instruction. This requires
16277 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16278 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16279 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16280 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16282 bool isFastMultiplier = false;
16284 switch ((unsigned char)Diff) {
16286 case 1: // result = add base, cond
16287 case 2: // result = lea base( , cond*2)
16288 case 3: // result = lea base(cond, cond*2)
16289 case 4: // result = lea base( , cond*4)
16290 case 5: // result = lea base(cond, cond*4)
16291 case 8: // result = lea base( , cond*8)
16292 case 9: // result = lea base(cond, cond*8)
16293 isFastMultiplier = true;
16298 if (isFastMultiplier) {
16299 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16300 if (NeedsCondInvert) // Invert the condition if needed.
16301 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16302 DAG.getConstant(1, Cond.getValueType()));
16304 // Zero extend the condition if needed.
16305 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16307 // Scale the condition by the difference.
16309 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16310 DAG.getConstant(Diff, Cond.getValueType()));
16312 // Add the base if non-zero.
16313 if (FalseC->getAPIntValue() != 0)
16314 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16315 SDValue(FalseC, 0));
16322 // Canonicalize max and min:
16323 // (x > y) ? x : y -> (x >= y) ? x : y
16324 // (x < y) ? x : y -> (x <= y) ? x : y
16325 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16326 // the need for an extra compare
16327 // against zero. e.g.
16328 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16330 // testl %edi, %edi
16332 // cmovgl %edi, %eax
16336 // cmovsl %eax, %edi
16337 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16338 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16339 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16340 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16345 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16346 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16347 Cond.getOperand(0), Cond.getOperand(1), NewCC);
16348 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16353 // Match VSELECTs into subs with unsigned saturation.
16354 if (!DCI.isBeforeLegalize() &&
16355 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16356 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16357 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16358 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16359 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16361 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16362 // left side invert the predicate to simplify logic below.
16364 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16366 CC = ISD::getSetCCInverse(CC, true);
16367 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16371 if (Other.getNode() && Other->getNumOperands() == 2 &&
16372 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16373 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16374 SDValue CondRHS = Cond->getOperand(1);
16376 // Look for a general sub with unsigned saturation first.
16377 // x >= y ? x-y : 0 --> subus x, y
16378 // x > y ? x-y : 0 --> subus x, y
16379 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16380 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16381 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16383 // If the RHS is a constant we have to reverse the const canonicalization.
16384 // x > C-1 ? x+-C : 0 --> subus x, C
16385 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16386 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16387 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16388 if (CondRHS.getConstantOperandVal(0) == -A-1)
16389 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16390 DAG.getConstant(-A, VT));
16393 // Another special case: If C was a sign bit, the sub has been
16394 // canonicalized into a xor.
16395 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16396 // it's safe to decanonicalize the xor?
16397 // x s< 0 ? x^C : 0 --> subus x, C
16398 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16399 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16400 isSplatVector(OpRHS.getNode())) {
16401 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16403 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16408 // Try to match a min/max vector operation.
16409 if (!DCI.isBeforeLegalize() &&
16410 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16411 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16412 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16414 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16415 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16416 Cond.getOpcode() == ISD::SETCC) {
16418 assert(Cond.getValueType().isVector() &&
16419 "vector select expects a vector selector!");
16421 EVT IntVT = Cond.getValueType();
16422 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16423 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16425 if (!TValIsAllOnes && !FValIsAllZeros) {
16426 // Try invert the condition if true value is not all 1s and false value
16428 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16429 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16431 if (TValIsAllZeros || FValIsAllOnes) {
16432 SDValue CC = Cond.getOperand(2);
16433 ISD::CondCode NewCC =
16434 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16435 Cond.getOperand(0).getValueType().isInteger());
16436 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16437 std::swap(LHS, RHS);
16438 TValIsAllOnes = FValIsAllOnes;
16439 FValIsAllZeros = TValIsAllZeros;
16443 if (TValIsAllOnes || FValIsAllZeros) {
16446 if (TValIsAllOnes && FValIsAllZeros)
16448 else if (TValIsAllOnes)
16449 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16450 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16451 else if (FValIsAllZeros)
16452 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16453 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16455 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16459 // If we know that this node is legal then we know that it is going to be
16460 // matched by one of the SSE/AVX BLEND instructions. These instructions only
16461 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16462 // to simplify previous instructions.
16463 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16464 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16465 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16466 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16468 // Don't optimize vector selects that map to mask-registers.
16472 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16473 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16475 APInt KnownZero, KnownOne;
16476 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16477 DCI.isBeforeLegalizeOps());
16478 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16479 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16480 DCI.CommitTargetLoweringOpt(TLO);
16486 // Check whether a boolean test is testing a boolean value generated by
16487 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16490 // Simplify the following patterns:
16491 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16492 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16493 // to (Op EFLAGS Cond)
16495 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16496 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16497 // to (Op EFLAGS !Cond)
16499 // where Op could be BRCOND or CMOV.
16501 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16502 // Quit if not CMP and SUB with its value result used.
16503 if (Cmp.getOpcode() != X86ISD::CMP &&
16504 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16507 // Quit if not used as a boolean value.
16508 if (CC != X86::COND_E && CC != X86::COND_NE)
16511 // Check CMP operands. One of them should be 0 or 1 and the other should be
16512 // an SetCC or extended from it.
16513 SDValue Op1 = Cmp.getOperand(0);
16514 SDValue Op2 = Cmp.getOperand(1);
16517 const ConstantSDNode* C = 0;
16518 bool needOppositeCond = (CC == X86::COND_E);
16519 bool checkAgainstTrue = false; // Is it a comparison against 1?
16521 if ((C = dyn_cast<ConstantSDNode>(Op1)))
16523 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16525 else // Quit if all operands are not constants.
16528 if (C->getZExtValue() == 1) {
16529 needOppositeCond = !needOppositeCond;
16530 checkAgainstTrue = true;
16531 } else if (C->getZExtValue() != 0)
16532 // Quit if the constant is neither 0 or 1.
16535 bool truncatedToBoolWithAnd = false;
16536 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16537 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16538 SetCC.getOpcode() == ISD::TRUNCATE ||
16539 SetCC.getOpcode() == ISD::AND) {
16540 if (SetCC.getOpcode() == ISD::AND) {
16542 ConstantSDNode *CS;
16543 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16544 CS->getZExtValue() == 1)
16546 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16547 CS->getZExtValue() == 1)
16551 SetCC = SetCC.getOperand(OpIdx);
16552 truncatedToBoolWithAnd = true;
16554 SetCC = SetCC.getOperand(0);
16557 switch (SetCC.getOpcode()) {
16558 case X86ISD::SETCC_CARRY:
16559 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16560 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16561 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16562 // truncated to i1 using 'and'.
16563 if (checkAgainstTrue && !truncatedToBoolWithAnd)
16565 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16566 "Invalid use of SETCC_CARRY!");
16568 case X86ISD::SETCC:
16569 // Set the condition code or opposite one if necessary.
16570 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16571 if (needOppositeCond)
16572 CC = X86::GetOppositeBranchCondition(CC);
16573 return SetCC.getOperand(1);
16574 case X86ISD::CMOV: {
16575 // Check whether false/true value has canonical one, i.e. 0 or 1.
16576 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16577 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16578 // Quit if true value is not a constant.
16581 // Quit if false value is not a constant.
16583 SDValue Op = SetCC.getOperand(0);
16584 // Skip 'zext' or 'trunc' node.
16585 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16586 Op.getOpcode() == ISD::TRUNCATE)
16587 Op = Op.getOperand(0);
16588 // A special case for rdrand/rdseed, where 0 is set if false cond is
16590 if ((Op.getOpcode() != X86ISD::RDRAND &&
16591 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16594 // Quit if false value is not the constant 0 or 1.
16595 bool FValIsFalse = true;
16596 if (FVal && FVal->getZExtValue() != 0) {
16597 if (FVal->getZExtValue() != 1)
16599 // If FVal is 1, opposite cond is needed.
16600 needOppositeCond = !needOppositeCond;
16601 FValIsFalse = false;
16603 // Quit if TVal is not the constant opposite of FVal.
16604 if (FValIsFalse && TVal->getZExtValue() != 1)
16606 if (!FValIsFalse && TVal->getZExtValue() != 0)
16608 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16609 if (needOppositeCond)
16610 CC = X86::GetOppositeBranchCondition(CC);
16611 return SetCC.getOperand(3);
16618 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16619 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16620 TargetLowering::DAGCombinerInfo &DCI,
16621 const X86Subtarget *Subtarget) {
16624 // If the flag operand isn't dead, don't touch this CMOV.
16625 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16628 SDValue FalseOp = N->getOperand(0);
16629 SDValue TrueOp = N->getOperand(1);
16630 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16631 SDValue Cond = N->getOperand(3);
16633 if (CC == X86::COND_E || CC == X86::COND_NE) {
16634 switch (Cond.getOpcode()) {
16638 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16639 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16640 return (CC == X86::COND_E) ? FalseOp : TrueOp;
16646 Flags = checkBoolTestSetCCCombine(Cond, CC);
16647 if (Flags.getNode() &&
16648 // Extra check as FCMOV only supports a subset of X86 cond.
16649 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16650 SDValue Ops[] = { FalseOp, TrueOp,
16651 DAG.getConstant(CC, MVT::i8), Flags };
16652 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16653 Ops, array_lengthof(Ops));
16656 // If this is a select between two integer constants, try to do some
16657 // optimizations. Note that the operands are ordered the opposite of SELECT
16659 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16660 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16661 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16662 // larger than FalseC (the false value).
16663 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16664 CC = X86::GetOppositeBranchCondition(CC);
16665 std::swap(TrueC, FalseC);
16666 std::swap(TrueOp, FalseOp);
16669 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
16670 // This is efficient for any integer data type (including i8/i16) and
16672 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16673 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16674 DAG.getConstant(CC, MVT::i8), Cond);
16676 // Zero extend the condition if needed.
16677 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16679 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16680 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16681 DAG.getConstant(ShAmt, MVT::i8));
16682 if (N->getNumValues() == 2) // Dead flag value?
16683 return DCI.CombineTo(N, Cond, SDValue());
16687 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
16688 // for any integer data type, including i8/i16.
16689 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16690 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16691 DAG.getConstant(CC, MVT::i8), Cond);
16693 // Zero extend the condition if needed.
16694 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16695 FalseC->getValueType(0), Cond);
16696 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16697 SDValue(FalseC, 0));
16699 if (N->getNumValues() == 2) // Dead flag value?
16700 return DCI.CombineTo(N, Cond, SDValue());
16704 // Optimize cases that will turn into an LEA instruction. This requires
16705 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16706 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16707 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16708 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16710 bool isFastMultiplier = false;
16712 switch ((unsigned char)Diff) {
16714 case 1: // result = add base, cond
16715 case 2: // result = lea base( , cond*2)
16716 case 3: // result = lea base(cond, cond*2)
16717 case 4: // result = lea base( , cond*4)
16718 case 5: // result = lea base(cond, cond*4)
16719 case 8: // result = lea base( , cond*8)
16720 case 9: // result = lea base(cond, cond*8)
16721 isFastMultiplier = true;
16726 if (isFastMultiplier) {
16727 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16728 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16729 DAG.getConstant(CC, MVT::i8), Cond);
16730 // Zero extend the condition if needed.
16731 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16733 // Scale the condition by the difference.
16735 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16736 DAG.getConstant(Diff, Cond.getValueType()));
16738 // Add the base if non-zero.
16739 if (FalseC->getAPIntValue() != 0)
16740 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16741 SDValue(FalseC, 0));
16742 if (N->getNumValues() == 2) // Dead flag value?
16743 return DCI.CombineTo(N, Cond, SDValue());
16750 // Handle these cases:
16751 // (select (x != c), e, c) -> select (x != c), e, x),
16752 // (select (x == c), c, e) -> select (x == c), x, e)
16753 // where the c is an integer constant, and the "select" is the combination
16754 // of CMOV and CMP.
16756 // The rationale for this change is that the conditional-move from a constant
16757 // needs two instructions, however, conditional-move from a register needs
16758 // only one instruction.
16760 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16761 // some instruction-combining opportunities. This opt needs to be
16762 // postponed as late as possible.
16764 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16765 // the DCI.xxxx conditions are provided to postpone the optimization as
16766 // late as possible.
16768 ConstantSDNode *CmpAgainst = 0;
16769 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16770 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16771 !isa<ConstantSDNode>(Cond.getOperand(0))) {
16773 if (CC == X86::COND_NE &&
16774 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16775 CC = X86::GetOppositeBranchCondition(CC);
16776 std::swap(TrueOp, FalseOp);
16779 if (CC == X86::COND_E &&
16780 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16781 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16782 DAG.getConstant(CC, MVT::i8), Cond };
16783 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16784 array_lengthof(Ops));
16792 /// PerformMulCombine - Optimize a single multiply with constant into two
16793 /// in order to implement it with two cheaper instructions, e.g.
16794 /// LEA + SHL, LEA + LEA.
16795 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16796 TargetLowering::DAGCombinerInfo &DCI) {
16797 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16800 EVT VT = N->getValueType(0);
16801 if (VT != MVT::i64)
16804 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16807 uint64_t MulAmt = C->getZExtValue();
16808 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16811 uint64_t MulAmt1 = 0;
16812 uint64_t MulAmt2 = 0;
16813 if ((MulAmt % 9) == 0) {
16815 MulAmt2 = MulAmt / 9;
16816 } else if ((MulAmt % 5) == 0) {
16818 MulAmt2 = MulAmt / 5;
16819 } else if ((MulAmt % 3) == 0) {
16821 MulAmt2 = MulAmt / 3;
16824 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16827 if (isPowerOf2_64(MulAmt2) &&
16828 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16829 // If second multiplifer is pow2, issue it first. We want the multiply by
16830 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16832 std::swap(MulAmt1, MulAmt2);
16835 if (isPowerOf2_64(MulAmt1))
16836 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16837 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16839 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16840 DAG.getConstant(MulAmt1, VT));
16842 if (isPowerOf2_64(MulAmt2))
16843 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16844 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16846 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16847 DAG.getConstant(MulAmt2, VT));
16849 // Do not add new nodes to DAG combiner worklist.
16850 DCI.CombineTo(N, NewMul, false);
16855 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16856 SDValue N0 = N->getOperand(0);
16857 SDValue N1 = N->getOperand(1);
16858 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16859 EVT VT = N0.getValueType();
16861 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16862 // since the result of setcc_c is all zero's or all ones.
16863 if (VT.isInteger() && !VT.isVector() &&
16864 N1C && N0.getOpcode() == ISD::AND &&
16865 N0.getOperand(1).getOpcode() == ISD::Constant) {
16866 SDValue N00 = N0.getOperand(0);
16867 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16868 ((N00.getOpcode() == ISD::ANY_EXTEND ||
16869 N00.getOpcode() == ISD::ZERO_EXTEND) &&
16870 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16871 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16872 APInt ShAmt = N1C->getAPIntValue();
16873 Mask = Mask.shl(ShAmt);
16875 return DAG.getNode(ISD::AND, SDLoc(N), VT,
16876 N00, DAG.getConstant(Mask, VT));
16880 // Hardware support for vector shifts is sparse which makes us scalarize the
16881 // vector operations in many cases. Also, on sandybridge ADD is faster than
16883 // (shl V, 1) -> add V,V
16884 if (isSplatVector(N1.getNode())) {
16885 assert(N0.getValueType().isVector() && "Invalid vector shift type");
16886 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16887 // We shift all of the values by one. In many cases we do not have
16888 // hardware support for this operation. This is better expressed as an ADD
16890 if (N1C && (1 == N1C->getZExtValue())) {
16891 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16898 /// \brief Returns a vector of 0s if the node in input is a vector logical
16899 /// shift by a constant amount which is known to be bigger than or equal
16900 /// to the vector element size in bits.
16901 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16902 const X86Subtarget *Subtarget) {
16903 EVT VT = N->getValueType(0);
16905 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16906 (!Subtarget->hasInt256() ||
16907 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16910 SDValue Amt = N->getOperand(1);
16912 if (isSplatVector(Amt.getNode())) {
16913 SDValue SclrAmt = Amt->getOperand(0);
16914 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16915 APInt ShiftAmt = C->getAPIntValue();
16916 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16918 // SSE2/AVX2 logical shifts always return a vector of 0s
16919 // if the shift amount is bigger than or equal to
16920 // the element size. The constant shift amount will be
16921 // encoded as a 8-bit immediate.
16922 if (ShiftAmt.trunc(8).uge(MaxAmount))
16923 return getZeroVector(VT, Subtarget, DAG, DL);
16930 /// PerformShiftCombine - Combine shifts.
16931 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16932 TargetLowering::DAGCombinerInfo &DCI,
16933 const X86Subtarget *Subtarget) {
16934 if (N->getOpcode() == ISD::SHL) {
16935 SDValue V = PerformSHLCombine(N, DAG);
16936 if (V.getNode()) return V;
16939 if (N->getOpcode() != ISD::SRA) {
16940 // Try to fold this logical shift into a zero vector.
16941 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16942 if (V.getNode()) return V;
16948 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
16949 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16950 // and friends. Likewise for OR -> CMPNEQSS.
16951 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16952 TargetLowering::DAGCombinerInfo &DCI,
16953 const X86Subtarget *Subtarget) {
16956 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16957 // we're requiring SSE2 for both.
16958 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16959 SDValue N0 = N->getOperand(0);
16960 SDValue N1 = N->getOperand(1);
16961 SDValue CMP0 = N0->getOperand(1);
16962 SDValue CMP1 = N1->getOperand(1);
16965 // The SETCCs should both refer to the same CMP.
16966 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16969 SDValue CMP00 = CMP0->getOperand(0);
16970 SDValue CMP01 = CMP0->getOperand(1);
16971 EVT VT = CMP00.getValueType();
16973 if (VT == MVT::f32 || VT == MVT::f64) {
16974 bool ExpectingFlags = false;
16975 // Check for any users that want flags:
16976 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16977 !ExpectingFlags && UI != UE; ++UI)
16978 switch (UI->getOpcode()) {
16983 ExpectingFlags = true;
16985 case ISD::CopyToReg:
16986 case ISD::SIGN_EXTEND:
16987 case ISD::ZERO_EXTEND:
16988 case ISD::ANY_EXTEND:
16992 if (!ExpectingFlags) {
16993 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16994 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16996 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16997 X86::CondCode tmp = cc0;
17002 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
17003 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17004 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17005 X86ISD::NodeType NTOperator = is64BitFP ?
17006 X86ISD::FSETCCsd : X86ISD::FSETCCss;
17007 // FIXME: need symbolic constants for these magic numbers.
17008 // See X86ATTInstPrinter.cpp:printSSECC().
17009 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17010 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
17011 DAG.getConstant(x86cc, MVT::i8));
17012 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
17014 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
17015 DAG.getConstant(1, MVT::i32));
17016 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17017 return OneBitOfTruth;
17025 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17026 /// so it can be folded inside ANDNP.
17027 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17028 EVT VT = N->getValueType(0);
17030 // Match direct AllOnes for 128 and 256-bit vectors
17031 if (ISD::isBuildVectorAllOnes(N))
17034 // Look through a bit convert.
17035 if (N->getOpcode() == ISD::BITCAST)
17036 N = N->getOperand(0).getNode();
17038 // Sometimes the operand may come from a insert_subvector building a 256-bit
17040 if (VT.is256BitVector() &&
17041 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17042 SDValue V1 = N->getOperand(0);
17043 SDValue V2 = N->getOperand(1);
17045 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17046 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17047 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17048 ISD::isBuildVectorAllOnes(V2.getNode()))
17055 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17056 // register. In most cases we actually compare or select YMM-sized registers
17057 // and mixing the two types creates horrible code. This method optimizes
17058 // some of the transition sequences.
17059 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17060 TargetLowering::DAGCombinerInfo &DCI,
17061 const X86Subtarget *Subtarget) {
17062 EVT VT = N->getValueType(0);
17063 if (!VT.is256BitVector())
17066 assert((N->getOpcode() == ISD::ANY_EXTEND ||
17067 N->getOpcode() == ISD::ZERO_EXTEND ||
17068 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17070 SDValue Narrow = N->getOperand(0);
17071 EVT NarrowVT = Narrow->getValueType(0);
17072 if (!NarrowVT.is128BitVector())
17075 if (Narrow->getOpcode() != ISD::XOR &&
17076 Narrow->getOpcode() != ISD::AND &&
17077 Narrow->getOpcode() != ISD::OR)
17080 SDValue N0 = Narrow->getOperand(0);
17081 SDValue N1 = Narrow->getOperand(1);
17084 // The Left side has to be a trunc.
17085 if (N0.getOpcode() != ISD::TRUNCATE)
17088 // The type of the truncated inputs.
17089 EVT WideVT = N0->getOperand(0)->getValueType(0);
17093 // The right side has to be a 'trunc' or a constant vector.
17094 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17095 bool RHSConst = (isSplatVector(N1.getNode()) &&
17096 isa<ConstantSDNode>(N1->getOperand(0)));
17097 if (!RHSTrunc && !RHSConst)
17100 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17102 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17105 // Set N0 and N1 to hold the inputs to the new wide operation.
17106 N0 = N0->getOperand(0);
17108 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17109 N1->getOperand(0));
17110 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17111 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17112 } else if (RHSTrunc) {
17113 N1 = N1->getOperand(0);
17116 // Generate the wide operation.
17117 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17118 unsigned Opcode = N->getOpcode();
17120 case ISD::ANY_EXTEND:
17122 case ISD::ZERO_EXTEND: {
17123 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17124 APInt Mask = APInt::getAllOnesValue(InBits);
17125 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17126 return DAG.getNode(ISD::AND, DL, VT,
17127 Op, DAG.getConstant(Mask, VT));
17129 case ISD::SIGN_EXTEND:
17130 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17131 Op, DAG.getValueType(NarrowVT));
17133 llvm_unreachable("Unexpected opcode");
17137 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17138 TargetLowering::DAGCombinerInfo &DCI,
17139 const X86Subtarget *Subtarget) {
17140 EVT VT = N->getValueType(0);
17141 if (DCI.isBeforeLegalizeOps())
17144 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17148 // Create BLSI, and BLSR instructions
17149 // BLSI is X & (-X)
17150 // BLSR is X & (X-1)
17151 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
17152 SDValue N0 = N->getOperand(0);
17153 SDValue N1 = N->getOperand(1);
17156 // Check LHS for neg
17157 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17158 isZero(N0.getOperand(0)))
17159 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17161 // Check RHS for neg
17162 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17163 isZero(N1.getOperand(0)))
17164 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17166 // Check LHS for X-1
17167 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17168 isAllOnes(N0.getOperand(1)))
17169 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17171 // Check RHS for X-1
17172 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17173 isAllOnes(N1.getOperand(1)))
17174 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17179 // Want to form ANDNP nodes:
17180 // 1) In the hopes of then easily combining them with OR and AND nodes
17181 // to form PBLEND/PSIGN.
17182 // 2) To match ANDN packed intrinsics
17183 if (VT != MVT::v2i64 && VT != MVT::v4i64)
17186 SDValue N0 = N->getOperand(0);
17187 SDValue N1 = N->getOperand(1);
17190 // Check LHS for vnot
17191 if (N0.getOpcode() == ISD::XOR &&
17192 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17193 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17194 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17196 // Check RHS for vnot
17197 if (N1.getOpcode() == ISD::XOR &&
17198 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17199 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17200 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17205 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17206 TargetLowering::DAGCombinerInfo &DCI,
17207 const X86Subtarget *Subtarget) {
17208 EVT VT = N->getValueType(0);
17209 if (DCI.isBeforeLegalizeOps())
17212 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17216 SDValue N0 = N->getOperand(0);
17217 SDValue N1 = N->getOperand(1);
17219 // look for psign/blend
17220 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17221 if (!Subtarget->hasSSSE3() ||
17222 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17225 // Canonicalize pandn to RHS
17226 if (N0.getOpcode() == X86ISD::ANDNP)
17228 // or (and (m, y), (pandn m, x))
17229 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17230 SDValue Mask = N1.getOperand(0);
17231 SDValue X = N1.getOperand(1);
17233 if (N0.getOperand(0) == Mask)
17234 Y = N0.getOperand(1);
17235 if (N0.getOperand(1) == Mask)
17236 Y = N0.getOperand(0);
17238 // Check to see if the mask appeared in both the AND and ANDNP and
17242 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17243 // Look through mask bitcast.
17244 if (Mask.getOpcode() == ISD::BITCAST)
17245 Mask = Mask.getOperand(0);
17246 if (X.getOpcode() == ISD::BITCAST)
17247 X = X.getOperand(0);
17248 if (Y.getOpcode() == ISD::BITCAST)
17249 Y = Y.getOperand(0);
17251 EVT MaskVT = Mask.getValueType();
17253 // Validate that the Mask operand is a vector sra node.
17254 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17255 // there is no psrai.b
17256 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17257 unsigned SraAmt = ~0;
17258 if (Mask.getOpcode() == ISD::SRA) {
17259 SDValue Amt = Mask.getOperand(1);
17260 if (isSplatVector(Amt.getNode())) {
17261 SDValue SclrAmt = Amt->getOperand(0);
17262 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17263 SraAmt = C->getZExtValue();
17265 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17266 SDValue SraC = Mask.getOperand(1);
17267 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
17269 if ((SraAmt + 1) != EltBits)
17274 // Now we know we at least have a plendvb with the mask val. See if
17275 // we can form a psignb/w/d.
17276 // psign = x.type == y.type == mask.type && y = sub(0, x);
17277 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17278 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17279 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17280 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17281 "Unsupported VT for PSIGN");
17282 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17283 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17285 // PBLENDVB only available on SSE 4.1
17286 if (!Subtarget->hasSSE41())
17289 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17291 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17292 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17293 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17294 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17295 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17299 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17302 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17303 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17305 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17307 if (!N0.hasOneUse() || !N1.hasOneUse())
17310 SDValue ShAmt0 = N0.getOperand(1);
17311 if (ShAmt0.getValueType() != MVT::i8)
17313 SDValue ShAmt1 = N1.getOperand(1);
17314 if (ShAmt1.getValueType() != MVT::i8)
17316 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17317 ShAmt0 = ShAmt0.getOperand(0);
17318 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17319 ShAmt1 = ShAmt1.getOperand(0);
17322 unsigned Opc = X86ISD::SHLD;
17323 SDValue Op0 = N0.getOperand(0);
17324 SDValue Op1 = N1.getOperand(0);
17325 if (ShAmt0.getOpcode() == ISD::SUB) {
17326 Opc = X86ISD::SHRD;
17327 std::swap(Op0, Op1);
17328 std::swap(ShAmt0, ShAmt1);
17331 unsigned Bits = VT.getSizeInBits();
17332 if (ShAmt1.getOpcode() == ISD::SUB) {
17333 SDValue Sum = ShAmt1.getOperand(0);
17334 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17335 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17336 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17337 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17338 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17339 return DAG.getNode(Opc, DL, VT,
17341 DAG.getNode(ISD::TRUNCATE, DL,
17344 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17345 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17347 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17348 return DAG.getNode(Opc, DL, VT,
17349 N0.getOperand(0), N1.getOperand(0),
17350 DAG.getNode(ISD::TRUNCATE, DL,
17357 // Generate NEG and CMOV for integer abs.
17358 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17359 EVT VT = N->getValueType(0);
17361 // Since X86 does not have CMOV for 8-bit integer, we don't convert
17362 // 8-bit integer abs to NEG and CMOV.
17363 if (VT.isInteger() && VT.getSizeInBits() == 8)
17366 SDValue N0 = N->getOperand(0);
17367 SDValue N1 = N->getOperand(1);
17370 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17371 // and change it to SUB and CMOV.
17372 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17373 N0.getOpcode() == ISD::ADD &&
17374 N0.getOperand(1) == N1 &&
17375 N1.getOpcode() == ISD::SRA &&
17376 N1.getOperand(0) == N0.getOperand(0))
17377 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17378 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17379 // Generate SUB & CMOV.
17380 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17381 DAG.getConstant(0, VT), N0.getOperand(0));
17383 SDValue Ops[] = { N0.getOperand(0), Neg,
17384 DAG.getConstant(X86::COND_GE, MVT::i8),
17385 SDValue(Neg.getNode(), 1) };
17386 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17387 Ops, array_lengthof(Ops));
17392 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17393 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17394 TargetLowering::DAGCombinerInfo &DCI,
17395 const X86Subtarget *Subtarget) {
17396 EVT VT = N->getValueType(0);
17397 if (DCI.isBeforeLegalizeOps())
17400 if (Subtarget->hasCMov()) {
17401 SDValue RV = performIntegerAbsCombine(N, DAG);
17406 // Try forming BMI if it is available.
17407 if (!Subtarget->hasBMI())
17410 if (VT != MVT::i32 && VT != MVT::i64)
17413 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17415 // Create BLSMSK instructions by finding X ^ (X-1)
17416 SDValue N0 = N->getOperand(0);
17417 SDValue N1 = N->getOperand(1);
17420 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17421 isAllOnes(N0.getOperand(1)))
17422 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17424 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17425 isAllOnes(N1.getOperand(1)))
17426 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17431 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17432 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17433 TargetLowering::DAGCombinerInfo &DCI,
17434 const X86Subtarget *Subtarget) {
17435 LoadSDNode *Ld = cast<LoadSDNode>(N);
17436 EVT RegVT = Ld->getValueType(0);
17437 EVT MemVT = Ld->getMemoryVT();
17439 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17440 unsigned RegSz = RegVT.getSizeInBits();
17442 // On Sandybridge unaligned 256bit loads are inefficient.
17443 ISD::LoadExtType Ext = Ld->getExtensionType();
17444 unsigned Alignment = Ld->getAlignment();
17445 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17446 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17447 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17448 unsigned NumElems = RegVT.getVectorNumElements();
17452 SDValue Ptr = Ld->getBasePtr();
17453 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17455 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17457 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17458 Ld->getPointerInfo(), Ld->isVolatile(),
17459 Ld->isNonTemporal(), Ld->isInvariant(),
17461 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17462 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17463 Ld->getPointerInfo(), Ld->isVolatile(),
17464 Ld->isNonTemporal(), Ld->isInvariant(),
17465 std::min(16U, Alignment));
17466 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17468 Load2.getValue(1));
17470 SDValue NewVec = DAG.getUNDEF(RegVT);
17471 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17472 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17473 return DCI.CombineTo(N, NewVec, TF, true);
17476 // If this is a vector EXT Load then attempt to optimize it using a
17477 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17478 // expansion is still better than scalar code.
17479 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17480 // emit a shuffle and a arithmetic shift.
17481 // TODO: It is possible to support ZExt by zeroing the undef values
17482 // during the shuffle phase or after the shuffle.
17483 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17484 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17485 assert(MemVT != RegVT && "Cannot extend to the same type");
17486 assert(MemVT.isVector() && "Must load a vector from memory");
17488 unsigned NumElems = RegVT.getVectorNumElements();
17489 unsigned MemSz = MemVT.getSizeInBits();
17490 assert(RegSz > MemSz && "Register size must be greater than the mem size");
17492 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17495 // All sizes must be a power of two.
17496 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17499 // Attempt to load the original value using scalar loads.
17500 // Find the largest scalar type that divides the total loaded size.
17501 MVT SclrLoadTy = MVT::i8;
17502 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17503 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17504 MVT Tp = (MVT::SimpleValueType)tp;
17505 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17510 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17511 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17513 SclrLoadTy = MVT::f64;
17515 // Calculate the number of scalar loads that we need to perform
17516 // in order to load our vector from memory.
17517 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17518 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17521 unsigned loadRegZize = RegSz;
17522 if (Ext == ISD::SEXTLOAD && RegSz == 256)
17525 // Represent our vector as a sequence of elements which are the
17526 // largest scalar that we can load.
17527 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17528 loadRegZize/SclrLoadTy.getSizeInBits());
17530 // Represent the data using the same element type that is stored in
17531 // memory. In practice, we ''widen'' MemVT.
17533 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17534 loadRegZize/MemVT.getScalarType().getSizeInBits());
17536 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17537 "Invalid vector type");
17539 // We can't shuffle using an illegal type.
17540 if (!TLI.isTypeLegal(WideVecVT))
17543 SmallVector<SDValue, 8> Chains;
17544 SDValue Ptr = Ld->getBasePtr();
17545 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17546 TLI.getPointerTy());
17547 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17549 for (unsigned i = 0; i < NumLoads; ++i) {
17550 // Perform a single load.
17551 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17552 Ptr, Ld->getPointerInfo(),
17553 Ld->isVolatile(), Ld->isNonTemporal(),
17554 Ld->isInvariant(), Ld->getAlignment());
17555 Chains.push_back(ScalarLoad.getValue(1));
17556 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17557 // another round of DAGCombining.
17559 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17561 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17562 ScalarLoad, DAG.getIntPtrConstant(i));
17564 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17567 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17570 // Bitcast the loaded value to a vector of the original element type, in
17571 // the size of the target vector type.
17572 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17573 unsigned SizeRatio = RegSz/MemSz;
17575 if (Ext == ISD::SEXTLOAD) {
17576 // If we have SSE4.1 we can directly emit a VSEXT node.
17577 if (Subtarget->hasSSE41()) {
17578 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17579 return DCI.CombineTo(N, Sext, TF, true);
17582 // Otherwise we'll shuffle the small elements in the high bits of the
17583 // larger type and perform an arithmetic shift. If the shift is not legal
17584 // it's better to scalarize.
17585 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17588 // Redistribute the loaded elements into the different locations.
17589 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17590 for (unsigned i = 0; i != NumElems; ++i)
17591 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17593 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17594 DAG.getUNDEF(WideVecVT),
17597 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17599 // Build the arithmetic shift.
17600 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17601 MemVT.getVectorElementType().getSizeInBits();
17602 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17603 DAG.getConstant(Amt, RegVT));
17605 return DCI.CombineTo(N, Shuff, TF, true);
17608 // Redistribute the loaded elements into the different locations.
17609 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17610 for (unsigned i = 0; i != NumElems; ++i)
17611 ShuffleVec[i*SizeRatio] = i;
17613 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17614 DAG.getUNDEF(WideVecVT),
17617 // Bitcast to the requested type.
17618 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17619 // Replace the original load with the new sequence
17620 // and return the new chain.
17621 return DCI.CombineTo(N, Shuff, TF, true);
17627 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17628 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17629 const X86Subtarget *Subtarget) {
17630 StoreSDNode *St = cast<StoreSDNode>(N);
17631 EVT VT = St->getValue().getValueType();
17632 EVT StVT = St->getMemoryVT();
17634 SDValue StoredVal = St->getOperand(1);
17635 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17637 // If we are saving a concatenation of two XMM registers, perform two stores.
17638 // On Sandy Bridge, 256-bit memory operations are executed by two
17639 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17640 // memory operation.
17641 unsigned Alignment = St->getAlignment();
17642 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17643 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17644 StVT == VT && !IsAligned) {
17645 unsigned NumElems = VT.getVectorNumElements();
17649 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17650 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17652 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17653 SDValue Ptr0 = St->getBasePtr();
17654 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17656 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17657 St->getPointerInfo(), St->isVolatile(),
17658 St->isNonTemporal(), Alignment);
17659 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17660 St->getPointerInfo(), St->isVolatile(),
17661 St->isNonTemporal(),
17662 std::min(16U, Alignment));
17663 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17666 // Optimize trunc store (of multiple scalars) to shuffle and store.
17667 // First, pack all of the elements in one place. Next, store to memory
17668 // in fewer chunks.
17669 if (St->isTruncatingStore() && VT.isVector()) {
17670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17671 unsigned NumElems = VT.getVectorNumElements();
17672 assert(StVT != VT && "Cannot truncate to the same type");
17673 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17674 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17676 // From, To sizes and ElemCount must be pow of two
17677 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17678 // We are going to use the original vector elt for storing.
17679 // Accumulated smaller vector elements must be a multiple of the store size.
17680 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17682 unsigned SizeRatio = FromSz / ToSz;
17684 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17686 // Create a type on which we perform the shuffle
17687 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17688 StVT.getScalarType(), NumElems*SizeRatio);
17690 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17692 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17693 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17694 for (unsigned i = 0; i != NumElems; ++i)
17695 ShuffleVec[i] = i * SizeRatio;
17697 // Can't shuffle using an illegal type.
17698 if (!TLI.isTypeLegal(WideVecVT))
17701 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17702 DAG.getUNDEF(WideVecVT),
17704 // At this point all of the data is stored at the bottom of the
17705 // register. We now need to save it to mem.
17707 // Find the largest store unit
17708 MVT StoreType = MVT::i8;
17709 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17710 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17711 MVT Tp = (MVT::SimpleValueType)tp;
17712 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17716 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17717 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17718 (64 <= NumElems * ToSz))
17719 StoreType = MVT::f64;
17721 // Bitcast the original vector into a vector of store-size units
17722 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17723 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17724 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17725 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17726 SmallVector<SDValue, 8> Chains;
17727 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17728 TLI.getPointerTy());
17729 SDValue Ptr = St->getBasePtr();
17731 // Perform one or more big stores into memory.
17732 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17733 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17734 StoreType, ShuffWide,
17735 DAG.getIntPtrConstant(i));
17736 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17737 St->getPointerInfo(), St->isVolatile(),
17738 St->isNonTemporal(), St->getAlignment());
17739 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17740 Chains.push_back(Ch);
17743 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17747 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
17748 // the FP state in cases where an emms may be missing.
17749 // A preferable solution to the general problem is to figure out the right
17750 // places to insert EMMS. This qualifies as a quick hack.
17752 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17753 if (VT.getSizeInBits() != 64)
17756 const Function *F = DAG.getMachineFunction().getFunction();
17757 bool NoImplicitFloatOps = F->getAttributes().
17758 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17759 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17760 && Subtarget->hasSSE2();
17761 if ((VT.isVector() ||
17762 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17763 isa<LoadSDNode>(St->getValue()) &&
17764 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17765 St->getChain().hasOneUse() && !St->isVolatile()) {
17766 SDNode* LdVal = St->getValue().getNode();
17767 LoadSDNode *Ld = 0;
17768 int TokenFactorIndex = -1;
17769 SmallVector<SDValue, 8> Ops;
17770 SDNode* ChainVal = St->getChain().getNode();
17771 // Must be a store of a load. We currently handle two cases: the load
17772 // is a direct child, and it's under an intervening TokenFactor. It is
17773 // possible to dig deeper under nested TokenFactors.
17774 if (ChainVal == LdVal)
17775 Ld = cast<LoadSDNode>(St->getChain());
17776 else if (St->getValue().hasOneUse() &&
17777 ChainVal->getOpcode() == ISD::TokenFactor) {
17778 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17779 if (ChainVal->getOperand(i).getNode() == LdVal) {
17780 TokenFactorIndex = i;
17781 Ld = cast<LoadSDNode>(St->getValue());
17783 Ops.push_back(ChainVal->getOperand(i));
17787 if (!Ld || !ISD::isNormalLoad(Ld))
17790 // If this is not the MMX case, i.e. we are just turning i64 load/store
17791 // into f64 load/store, avoid the transformation if there are multiple
17792 // uses of the loaded value.
17793 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17798 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17799 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17801 if (Subtarget->is64Bit() || F64IsLegal) {
17802 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17803 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17804 Ld->getPointerInfo(), Ld->isVolatile(),
17805 Ld->isNonTemporal(), Ld->isInvariant(),
17806 Ld->getAlignment());
17807 SDValue NewChain = NewLd.getValue(1);
17808 if (TokenFactorIndex != -1) {
17809 Ops.push_back(NewChain);
17810 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17813 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17814 St->getPointerInfo(),
17815 St->isVolatile(), St->isNonTemporal(),
17816 St->getAlignment());
17819 // Otherwise, lower to two pairs of 32-bit loads / stores.
17820 SDValue LoAddr = Ld->getBasePtr();
17821 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17822 DAG.getConstant(4, MVT::i32));
17824 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17825 Ld->getPointerInfo(),
17826 Ld->isVolatile(), Ld->isNonTemporal(),
17827 Ld->isInvariant(), Ld->getAlignment());
17828 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17829 Ld->getPointerInfo().getWithOffset(4),
17830 Ld->isVolatile(), Ld->isNonTemporal(),
17832 MinAlign(Ld->getAlignment(), 4));
17834 SDValue NewChain = LoLd.getValue(1);
17835 if (TokenFactorIndex != -1) {
17836 Ops.push_back(LoLd);
17837 Ops.push_back(HiLd);
17838 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17842 LoAddr = St->getBasePtr();
17843 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17844 DAG.getConstant(4, MVT::i32));
17846 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17847 St->getPointerInfo(),
17848 St->isVolatile(), St->isNonTemporal(),
17849 St->getAlignment());
17850 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17851 St->getPointerInfo().getWithOffset(4),
17853 St->isNonTemporal(),
17854 MinAlign(St->getAlignment(), 4));
17855 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17860 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17861 /// and return the operands for the horizontal operation in LHS and RHS. A
17862 /// horizontal operation performs the binary operation on successive elements
17863 /// of its first operand, then on successive elements of its second operand,
17864 /// returning the resulting values in a vector. For example, if
17865 /// A = < float a0, float a1, float a2, float a3 >
17867 /// B = < float b0, float b1, float b2, float b3 >
17868 /// then the result of doing a horizontal operation on A and B is
17869 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17870 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17871 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17872 /// set to A, RHS to B, and the routine returns 'true'.
17873 /// Note that the binary operation should have the property that if one of the
17874 /// operands is UNDEF then the result is UNDEF.
17875 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17876 // Look for the following pattern: if
17877 // A = < float a0, float a1, float a2, float a3 >
17878 // B = < float b0, float b1, float b2, float b3 >
17880 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17881 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17882 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17883 // which is A horizontal-op B.
17885 // At least one of the operands should be a vector shuffle.
17886 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17887 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17890 MVT VT = LHS.getSimpleValueType();
17892 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17893 "Unsupported vector type for horizontal add/sub");
17895 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17896 // operate independently on 128-bit lanes.
17897 unsigned NumElts = VT.getVectorNumElements();
17898 unsigned NumLanes = VT.getSizeInBits()/128;
17899 unsigned NumLaneElts = NumElts / NumLanes;
17900 assert((NumLaneElts % 2 == 0) &&
17901 "Vector type should have an even number of elements in each lane");
17902 unsigned HalfLaneElts = NumLaneElts/2;
17904 // View LHS in the form
17905 // LHS = VECTOR_SHUFFLE A, B, LMask
17906 // If LHS is not a shuffle then pretend it is the shuffle
17907 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17908 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17911 SmallVector<int, 16> LMask(NumElts);
17912 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17913 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17914 A = LHS.getOperand(0);
17915 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17916 B = LHS.getOperand(1);
17917 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17918 std::copy(Mask.begin(), Mask.end(), LMask.begin());
17920 if (LHS.getOpcode() != ISD::UNDEF)
17922 for (unsigned i = 0; i != NumElts; ++i)
17926 // Likewise, view RHS in the form
17927 // RHS = VECTOR_SHUFFLE C, D, RMask
17929 SmallVector<int, 16> RMask(NumElts);
17930 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17931 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17932 C = RHS.getOperand(0);
17933 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17934 D = RHS.getOperand(1);
17935 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17936 std::copy(Mask.begin(), Mask.end(), RMask.begin());
17938 if (RHS.getOpcode() != ISD::UNDEF)
17940 for (unsigned i = 0; i != NumElts; ++i)
17944 // Check that the shuffles are both shuffling the same vectors.
17945 if (!(A == C && B == D) && !(A == D && B == C))
17948 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17949 if (!A.getNode() && !B.getNode())
17952 // If A and B occur in reverse order in RHS, then "swap" them (which means
17953 // rewriting the mask).
17955 CommuteVectorShuffleMask(RMask, NumElts);
17957 // At this point LHS and RHS are equivalent to
17958 // LHS = VECTOR_SHUFFLE A, B, LMask
17959 // RHS = VECTOR_SHUFFLE A, B, RMask
17960 // Check that the masks correspond to performing a horizontal operation.
17961 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
17962 for (unsigned i = 0; i != NumLaneElts; ++i) {
17963 int LIdx = LMask[i+l], RIdx = RMask[i+l];
17965 // Ignore any UNDEF components.
17966 if (LIdx < 0 || RIdx < 0 ||
17967 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17968 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17971 // Check that successive elements are being operated on. If not, this is
17972 // not a horizontal operation.
17973 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
17974 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
17975 if (!(LIdx == Index && RIdx == Index + 1) &&
17976 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17981 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17982 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17986 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17987 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17988 const X86Subtarget *Subtarget) {
17989 EVT VT = N->getValueType(0);
17990 SDValue LHS = N->getOperand(0);
17991 SDValue RHS = N->getOperand(1);
17993 // Try to synthesize horizontal adds from adds of shuffles.
17994 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17995 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17996 isHorizontalBinOp(LHS, RHS, true))
17997 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18001 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18002 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18003 const X86Subtarget *Subtarget) {
18004 EVT VT = N->getValueType(0);
18005 SDValue LHS = N->getOperand(0);
18006 SDValue RHS = N->getOperand(1);
18008 // Try to synthesize horizontal subs from subs of shuffles.
18009 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18010 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18011 isHorizontalBinOp(LHS, RHS, false))
18012 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18016 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18017 /// X86ISD::FXOR nodes.
18018 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18019 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18020 // F[X]OR(0.0, x) -> x
18021 // F[X]OR(x, 0.0) -> x
18022 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18023 if (C->getValueAPF().isPosZero())
18024 return N->getOperand(1);
18025 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18026 if (C->getValueAPF().isPosZero())
18027 return N->getOperand(0);
18031 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18032 /// X86ISD::FMAX nodes.
18033 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18034 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18036 // Only perform optimizations if UnsafeMath is used.
18037 if (!DAG.getTarget().Options.UnsafeFPMath)
18040 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18041 // into FMINC and FMAXC, which are Commutative operations.
18042 unsigned NewOp = 0;
18043 switch (N->getOpcode()) {
18044 default: llvm_unreachable("unknown opcode");
18045 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
18046 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
18049 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18050 N->getOperand(0), N->getOperand(1));
18053 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18054 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18055 // FAND(0.0, x) -> 0.0
18056 // FAND(x, 0.0) -> 0.0
18057 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18058 if (C->getValueAPF().isPosZero())
18059 return N->getOperand(0);
18060 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18061 if (C->getValueAPF().isPosZero())
18062 return N->getOperand(1);
18066 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18067 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18068 // FANDN(x, 0.0) -> 0.0
18069 // FANDN(0.0, x) -> x
18070 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18071 if (C->getValueAPF().isPosZero())
18072 return N->getOperand(1);
18073 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18074 if (C->getValueAPF().isPosZero())
18075 return N->getOperand(1);
18079 static SDValue PerformBTCombine(SDNode *N,
18081 TargetLowering::DAGCombinerInfo &DCI) {
18082 // BT ignores high bits in the bit index operand.
18083 SDValue Op1 = N->getOperand(1);
18084 if (Op1.hasOneUse()) {
18085 unsigned BitWidth = Op1.getValueSizeInBits();
18086 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18087 APInt KnownZero, KnownOne;
18088 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18089 !DCI.isBeforeLegalizeOps());
18090 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18091 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18092 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18093 DCI.CommitTargetLoweringOpt(TLO);
18098 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18099 SDValue Op = N->getOperand(0);
18100 if (Op.getOpcode() == ISD::BITCAST)
18101 Op = Op.getOperand(0);
18102 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18103 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18104 VT.getVectorElementType().getSizeInBits() ==
18105 OpVT.getVectorElementType().getSizeInBits()) {
18106 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18111 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18112 const X86Subtarget *Subtarget) {
18113 EVT VT = N->getValueType(0);
18114 if (!VT.isVector())
18117 SDValue N0 = N->getOperand(0);
18118 SDValue N1 = N->getOperand(1);
18119 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18122 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18123 // both SSE and AVX2 since there is no sign-extended shift right
18124 // operation on a vector with 64-bit elements.
18125 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18126 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18127 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18128 N0.getOpcode() == ISD::SIGN_EXTEND)) {
18129 SDValue N00 = N0.getOperand(0);
18131 // EXTLOAD has a better solution on AVX2,
18132 // it may be replaced with X86ISD::VSEXT node.
18133 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18134 if (!ISD::isNormalLoad(N00.getNode()))
18137 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18138 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18140 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18146 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18147 TargetLowering::DAGCombinerInfo &DCI,
18148 const X86Subtarget *Subtarget) {
18149 if (!DCI.isBeforeLegalizeOps())
18152 if (!Subtarget->hasFp256())
18155 EVT VT = N->getValueType(0);
18156 if (VT.isVector() && VT.getSizeInBits() == 256) {
18157 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18165 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18166 const X86Subtarget* Subtarget) {
18168 EVT VT = N->getValueType(0);
18170 // Let legalize expand this if it isn't a legal type yet.
18171 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18174 EVT ScalarVT = VT.getScalarType();
18175 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18176 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18179 SDValue A = N->getOperand(0);
18180 SDValue B = N->getOperand(1);
18181 SDValue C = N->getOperand(2);
18183 bool NegA = (A.getOpcode() == ISD::FNEG);
18184 bool NegB = (B.getOpcode() == ISD::FNEG);
18185 bool NegC = (C.getOpcode() == ISD::FNEG);
18187 // Negative multiplication when NegA xor NegB
18188 bool NegMul = (NegA != NegB);
18190 A = A.getOperand(0);
18192 B = B.getOperand(0);
18194 C = C.getOperand(0);
18198 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18200 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18202 return DAG.getNode(Opcode, dl, VT, A, B, C);
18205 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18206 TargetLowering::DAGCombinerInfo &DCI,
18207 const X86Subtarget *Subtarget) {
18208 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
18209 // (and (i32 x86isd::setcc_carry), 1)
18210 // This eliminates the zext. This transformation is necessary because
18211 // ISD::SETCC is always legalized to i8.
18213 SDValue N0 = N->getOperand(0);
18214 EVT VT = N->getValueType(0);
18216 if (N0.getOpcode() == ISD::AND &&
18218 N0.getOperand(0).hasOneUse()) {
18219 SDValue N00 = N0.getOperand(0);
18220 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18221 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18222 if (!C || C->getZExtValue() != 1)
18224 return DAG.getNode(ISD::AND, dl, VT,
18225 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18226 N00.getOperand(0), N00.getOperand(1)),
18227 DAG.getConstant(1, VT));
18231 if (VT.is256BitVector()) {
18232 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18240 // Optimize x == -y --> x+y == 0
18241 // x != -y --> x+y != 0
18242 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18243 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18244 SDValue LHS = N->getOperand(0);
18245 SDValue RHS = N->getOperand(1);
18247 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18248 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18249 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18250 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18251 LHS.getValueType(), RHS, LHS.getOperand(1));
18252 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18253 addV, DAG.getConstant(0, addV.getValueType()), CC);
18255 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18256 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18257 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18258 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18259 RHS.getValueType(), LHS, RHS.getOperand(1));
18260 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18261 addV, DAG.getConstant(0, addV.getValueType()), CC);
18266 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18267 // as "sbb reg,reg", since it can be extended without zext and produces
18268 // an all-ones bit which is more useful than 0/1 in some cases.
18269 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18270 return DAG.getNode(ISD::AND, DL, MVT::i8,
18271 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18272 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18273 DAG.getConstant(1, MVT::i8));
18276 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18277 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18278 TargetLowering::DAGCombinerInfo &DCI,
18279 const X86Subtarget *Subtarget) {
18281 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18282 SDValue EFLAGS = N->getOperand(1);
18284 if (CC == X86::COND_A) {
18285 // Try to convert COND_A into COND_B in an attempt to facilitate
18286 // materializing "setb reg".
18288 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18289 // cannot take an immediate as its first operand.
18291 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18292 EFLAGS.getValueType().isInteger() &&
18293 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18294 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18295 EFLAGS.getNode()->getVTList(),
18296 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18297 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18298 return MaterializeSETB(DL, NewEFLAGS, DAG);
18302 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18303 // a zext and produces an all-ones bit which is more useful than 0/1 in some
18305 if (CC == X86::COND_B)
18306 return MaterializeSETB(DL, EFLAGS, DAG);
18310 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18311 if (Flags.getNode()) {
18312 SDValue Cond = DAG.getConstant(CC, MVT::i8);
18313 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18319 // Optimize branch condition evaluation.
18321 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18322 TargetLowering::DAGCombinerInfo &DCI,
18323 const X86Subtarget *Subtarget) {
18325 SDValue Chain = N->getOperand(0);
18326 SDValue Dest = N->getOperand(1);
18327 SDValue EFLAGS = N->getOperand(3);
18328 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18332 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18333 if (Flags.getNode()) {
18334 SDValue Cond = DAG.getConstant(CC, MVT::i8);
18335 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18342 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18343 const X86TargetLowering *XTLI) {
18344 SDValue Op0 = N->getOperand(0);
18345 EVT InVT = Op0->getValueType(0);
18347 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18348 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18350 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18351 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18352 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18355 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18356 // a 32-bit target where SSE doesn't support i64->FP operations.
18357 if (Op0.getOpcode() == ISD::LOAD) {
18358 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18359 EVT VT = Ld->getValueType(0);
18360 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18361 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18362 !XTLI->getSubtarget()->is64Bit() &&
18363 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18364 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18365 Ld->getChain(), Op0, DAG);
18366 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18373 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18374 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18375 X86TargetLowering::DAGCombinerInfo &DCI) {
18376 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18377 // the result is either zero or one (depending on the input carry bit).
18378 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18379 if (X86::isZeroNode(N->getOperand(0)) &&
18380 X86::isZeroNode(N->getOperand(1)) &&
18381 // We don't have a good way to replace an EFLAGS use, so only do this when
18383 SDValue(N, 1).use_empty()) {
18385 EVT VT = N->getValueType(0);
18386 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18387 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18388 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18389 DAG.getConstant(X86::COND_B,MVT::i8),
18391 DAG.getConstant(1, VT));
18392 return DCI.CombineTo(N, Res1, CarryOut);
18398 // fold (add Y, (sete X, 0)) -> adc 0, Y
18399 // (add Y, (setne X, 0)) -> sbb -1, Y
18400 // (sub (sete X, 0), Y) -> sbb 0, Y
18401 // (sub (setne X, 0), Y) -> adc -1, Y
18402 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18405 // Look through ZExts.
18406 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18407 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18410 SDValue SetCC = Ext.getOperand(0);
18411 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18414 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18415 if (CC != X86::COND_E && CC != X86::COND_NE)
18418 SDValue Cmp = SetCC.getOperand(1);
18419 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18420 !X86::isZeroNode(Cmp.getOperand(1)) ||
18421 !Cmp.getOperand(0).getValueType().isInteger())
18424 SDValue CmpOp0 = Cmp.getOperand(0);
18425 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18426 DAG.getConstant(1, CmpOp0.getValueType()));
18428 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18429 if (CC == X86::COND_NE)
18430 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18431 DL, OtherVal.getValueType(), OtherVal,
18432 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18433 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18434 DL, OtherVal.getValueType(), OtherVal,
18435 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18438 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18439 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18440 const X86Subtarget *Subtarget) {
18441 EVT VT = N->getValueType(0);
18442 SDValue Op0 = N->getOperand(0);
18443 SDValue Op1 = N->getOperand(1);
18445 // Try to synthesize horizontal adds from adds of shuffles.
18446 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18447 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18448 isHorizontalBinOp(Op0, Op1, true))
18449 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18451 return OptimizeConditionalInDecrement(N, DAG);
18454 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18455 const X86Subtarget *Subtarget) {
18456 SDValue Op0 = N->getOperand(0);
18457 SDValue Op1 = N->getOperand(1);
18459 // X86 can't encode an immediate LHS of a sub. See if we can push the
18460 // negation into a preceding instruction.
18461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18462 // If the RHS of the sub is a XOR with one use and a constant, invert the
18463 // immediate. Then add one to the LHS of the sub so we can turn
18464 // X-Y -> X+~Y+1, saving one register.
18465 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18466 isa<ConstantSDNode>(Op1.getOperand(1))) {
18467 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18468 EVT VT = Op0.getValueType();
18469 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18471 DAG.getConstant(~XorC, VT));
18472 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18473 DAG.getConstant(C->getAPIntValue()+1, VT));
18477 // Try to synthesize horizontal adds from adds of shuffles.
18478 EVT VT = N->getValueType(0);
18479 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18480 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18481 isHorizontalBinOp(Op0, Op1, true))
18482 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18484 return OptimizeConditionalInDecrement(N, DAG);
18487 /// performVZEXTCombine - Performs build vector combines
18488 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18489 TargetLowering::DAGCombinerInfo &DCI,
18490 const X86Subtarget *Subtarget) {
18491 // (vzext (bitcast (vzext (x)) -> (vzext x)
18492 SDValue In = N->getOperand(0);
18493 while (In.getOpcode() == ISD::BITCAST)
18494 In = In.getOperand(0);
18496 if (In.getOpcode() != X86ISD::VZEXT)
18499 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18503 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18504 DAGCombinerInfo &DCI) const {
18505 SelectionDAG &DAG = DCI.DAG;
18506 switch (N->getOpcode()) {
18508 case ISD::EXTRACT_VECTOR_ELT:
18509 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18511 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18512 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18513 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
18514 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
18515 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
18516 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
18519 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
18520 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
18521 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
18522 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
18523 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
18524 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
18525 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
18526 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
18527 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
18529 case X86ISD::FOR: return PerformFORCombine(N, DAG);
18531 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
18532 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
18533 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
18534 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
18535 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
18536 case ISD::ANY_EXTEND:
18537 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
18538 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
18539 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18540 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18541 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
18542 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18543 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18544 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
18545 case X86ISD::SHUFP: // Handle all target specific shuffles
18546 case X86ISD::PALIGNR:
18547 case X86ISD::UNPCKH:
18548 case X86ISD::UNPCKL:
18549 case X86ISD::MOVHLPS:
18550 case X86ISD::MOVLHPS:
18551 case X86ISD::PSHUFD:
18552 case X86ISD::PSHUFHW:
18553 case X86ISD::PSHUFLW:
18554 case X86ISD::MOVSS:
18555 case X86ISD::MOVSD:
18556 case X86ISD::VPERMILP:
18557 case X86ISD::VPERM2X128:
18558 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18559 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
18565 /// isTypeDesirableForOp - Return true if the target has native support for
18566 /// the specified value type and it is 'desirable' to use the type for the
18567 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18568 /// instruction encodings are longer and some i16 instructions are slow.
18569 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18570 if (!isTypeLegal(VT))
18572 if (VT != MVT::i16)
18579 case ISD::SIGN_EXTEND:
18580 case ISD::ZERO_EXTEND:
18581 case ISD::ANY_EXTEND:
18594 /// IsDesirableToPromoteOp - This method query the target whether it is
18595 /// beneficial for dag combiner to promote the specified node. If true, it
18596 /// should return the desired promotion type by reference.
18597 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18598 EVT VT = Op.getValueType();
18599 if (VT != MVT::i16)
18602 bool Promote = false;
18603 bool Commute = false;
18604 switch (Op.getOpcode()) {
18607 LoadSDNode *LD = cast<LoadSDNode>(Op);
18608 // If the non-extending load has a single use and it's not live out, then it
18609 // might be folded.
18610 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18611 Op.hasOneUse()*/) {
18612 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18613 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18614 // The only case where we'd want to promote LOAD (rather then it being
18615 // promoted as an operand is when it's only use is liveout.
18616 if (UI->getOpcode() != ISD::CopyToReg)
18623 case ISD::SIGN_EXTEND:
18624 case ISD::ZERO_EXTEND:
18625 case ISD::ANY_EXTEND:
18630 SDValue N0 = Op.getOperand(0);
18631 // Look out for (store (shl (load), x)).
18632 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18645 SDValue N0 = Op.getOperand(0);
18646 SDValue N1 = Op.getOperand(1);
18647 if (!Commute && MayFoldLoad(N1))
18649 // Avoid disabling potential load folding opportunities.
18650 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18652 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18662 //===----------------------------------------------------------------------===//
18663 // X86 Inline Assembly Support
18664 //===----------------------------------------------------------------------===//
18667 // Helper to match a string separated by whitespace.
18668 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18669 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18671 for (unsigned i = 0, e = args.size(); i != e; ++i) {
18672 StringRef piece(*args[i]);
18673 if (!s.startswith(piece)) // Check if the piece matches.
18676 s = s.substr(piece.size());
18677 StringRef::size_type pos = s.find_first_not_of(" \t");
18678 if (pos == 0) // We matched a prefix.
18686 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18689 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18690 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18692 std::string AsmStr = IA->getAsmString();
18694 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18695 if (!Ty || Ty->getBitWidth() % 16 != 0)
18698 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18699 SmallVector<StringRef, 4> AsmPieces;
18700 SplitString(AsmStr, AsmPieces, ";\n");
18702 switch (AsmPieces.size()) {
18703 default: return false;
18705 // FIXME: this should verify that we are targeting a 486 or better. If not,
18706 // we will turn this bswap into something that will be lowered to logical
18707 // ops instead of emitting the bswap asm. For now, we don't support 486 or
18708 // lower so don't worry about this.
18710 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18711 matchAsm(AsmPieces[0], "bswapl", "$0") ||
18712 matchAsm(AsmPieces[0], "bswapq", "$0") ||
18713 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18714 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18715 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18716 // No need to check constraints, nothing other than the equivalent of
18717 // "=r,0" would be valid here.
18718 return IntrinsicLowering::LowerToByteSwap(CI);
18721 // rorw $$8, ${0:w} --> llvm.bswap.i16
18722 if (CI->getType()->isIntegerTy(16) &&
18723 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18724 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18725 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18727 const std::string &ConstraintsStr = IA->getConstraintString();
18728 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18729 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18730 if (AsmPieces.size() == 4 &&
18731 AsmPieces[0] == "~{cc}" &&
18732 AsmPieces[1] == "~{dirflag}" &&
18733 AsmPieces[2] == "~{flags}" &&
18734 AsmPieces[3] == "~{fpsr}")
18735 return IntrinsicLowering::LowerToByteSwap(CI);
18739 if (CI->getType()->isIntegerTy(32) &&
18740 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18741 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18742 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18743 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18745 const std::string &ConstraintsStr = IA->getConstraintString();
18746 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18747 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18748 if (AsmPieces.size() == 4 &&
18749 AsmPieces[0] == "~{cc}" &&
18750 AsmPieces[1] == "~{dirflag}" &&
18751 AsmPieces[2] == "~{flags}" &&
18752 AsmPieces[3] == "~{fpsr}")
18753 return IntrinsicLowering::LowerToByteSwap(CI);
18756 if (CI->getType()->isIntegerTy(64)) {
18757 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18758 if (Constraints.size() >= 2 &&
18759 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18760 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18761 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
18762 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18763 matchAsm(AsmPieces[1], "bswap", "%edx") &&
18764 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18765 return IntrinsicLowering::LowerToByteSwap(CI);
18773 /// getConstraintType - Given a constraint letter, return the type of
18774 /// constraint it is for this target.
18775 X86TargetLowering::ConstraintType
18776 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18777 if (Constraint.size() == 1) {
18778 switch (Constraint[0]) {
18789 return C_RegisterClass;
18813 return TargetLowering::getConstraintType(Constraint);
18816 /// Examine constraint type and operand type and determine a weight value.
18817 /// This object must already have been set up with the operand type
18818 /// and the current alternative constraint selected.
18819 TargetLowering::ConstraintWeight
18820 X86TargetLowering::getSingleConstraintMatchWeight(
18821 AsmOperandInfo &info, const char *constraint) const {
18822 ConstraintWeight weight = CW_Invalid;
18823 Value *CallOperandVal = info.CallOperandVal;
18824 // If we don't have a value, we can't do a match,
18825 // but allow it at the lowest weight.
18826 if (CallOperandVal == NULL)
18828 Type *type = CallOperandVal->getType();
18829 // Look at the constraint type.
18830 switch (*constraint) {
18832 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18843 if (CallOperandVal->getType()->isIntegerTy())
18844 weight = CW_SpecificReg;
18849 if (type->isFloatingPointTy())
18850 weight = CW_SpecificReg;
18853 if (type->isX86_MMXTy() && Subtarget->hasMMX())
18854 weight = CW_SpecificReg;
18858 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18859 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18860 weight = CW_Register;
18863 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18864 if (C->getZExtValue() <= 31)
18865 weight = CW_Constant;
18869 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18870 if (C->getZExtValue() <= 63)
18871 weight = CW_Constant;
18875 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18876 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18877 weight = CW_Constant;
18881 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18882 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18883 weight = CW_Constant;
18887 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18888 if (C->getZExtValue() <= 3)
18889 weight = CW_Constant;
18893 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18894 if (C->getZExtValue() <= 0xff)
18895 weight = CW_Constant;
18900 if (dyn_cast<ConstantFP>(CallOperandVal)) {
18901 weight = CW_Constant;
18905 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18906 if ((C->getSExtValue() >= -0x80000000LL) &&
18907 (C->getSExtValue() <= 0x7fffffffLL))
18908 weight = CW_Constant;
18912 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18913 if (C->getZExtValue() <= 0xffffffff)
18914 weight = CW_Constant;
18921 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18922 /// with another that has more specific requirements based on the type of the
18923 /// corresponding operand.
18924 const char *X86TargetLowering::
18925 LowerXConstraint(EVT ConstraintVT) const {
18926 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18927 // 'f' like normal targets.
18928 if (ConstraintVT.isFloatingPoint()) {
18929 if (Subtarget->hasSSE2())
18931 if (Subtarget->hasSSE1())
18935 return TargetLowering::LowerXConstraint(ConstraintVT);
18938 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18939 /// vector. If it is invalid, don't add anything to Ops.
18940 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18941 std::string &Constraint,
18942 std::vector<SDValue>&Ops,
18943 SelectionDAG &DAG) const {
18944 SDValue Result(0, 0);
18946 // Only support length 1 constraints for now.
18947 if (Constraint.length() > 1) return;
18949 char ConstraintLetter = Constraint[0];
18950 switch (ConstraintLetter) {
18953 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18954 if (C->getZExtValue() <= 31) {
18955 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18961 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18962 if (C->getZExtValue() <= 63) {
18963 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18969 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18970 if (isInt<8>(C->getSExtValue())) {
18971 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18977 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18978 if (C->getZExtValue() <= 255) {
18979 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18985 // 32-bit signed value
18986 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18987 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18988 C->getSExtValue())) {
18989 // Widen to 64 bits here to get it sign extended.
18990 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18993 // FIXME gcc accepts some relocatable values here too, but only in certain
18994 // memory models; it's complicated.
18999 // 32-bit unsigned value
19000 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19001 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19002 C->getZExtValue())) {
19003 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19007 // FIXME gcc accepts some relocatable values here too, but only in certain
19008 // memory models; it's complicated.
19012 // Literal immediates are always ok.
19013 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19014 // Widen to 64 bits here to get it sign extended.
19015 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19019 // In any sort of PIC mode addresses need to be computed at runtime by
19020 // adding in a register or some sort of table lookup. These can't
19021 // be used as immediates.
19022 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19025 // If we are in non-pic codegen mode, we allow the address of a global (with
19026 // an optional displacement) to be used with 'i'.
19027 GlobalAddressSDNode *GA = 0;
19028 int64_t Offset = 0;
19030 // Match either (GA), (GA+C), (GA+C1+C2), etc.
19032 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19033 Offset += GA->getOffset();
19035 } else if (Op.getOpcode() == ISD::ADD) {
19036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19037 Offset += C->getZExtValue();
19038 Op = Op.getOperand(0);
19041 } else if (Op.getOpcode() == ISD::SUB) {
19042 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19043 Offset += -C->getZExtValue();
19044 Op = Op.getOperand(0);
19049 // Otherwise, this isn't something we can handle, reject it.
19053 const GlobalValue *GV = GA->getGlobal();
19054 // If we require an extra load to get this address, as in PIC mode, we
19055 // can't accept it.
19056 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19057 getTargetMachine())))
19060 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19061 GA->getValueType(0), Offset);
19066 if (Result.getNode()) {
19067 Ops.push_back(Result);
19070 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19073 std::pair<unsigned, const TargetRegisterClass*>
19074 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19076 // First, see if this is a constraint that directly corresponds to an LLVM
19078 if (Constraint.size() == 1) {
19079 // GCC Constraint Letters
19080 switch (Constraint[0]) {
19082 // TODO: Slight differences here in allocation order and leaving
19083 // RIP in the class. Do they matter any more here than they do
19084 // in the normal allocation?
19085 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19086 if (Subtarget->is64Bit()) {
19087 if (VT == MVT::i32 || VT == MVT::f32)
19088 return std::make_pair(0U, &X86::GR32RegClass);
19089 if (VT == MVT::i16)
19090 return std::make_pair(0U, &X86::GR16RegClass);
19091 if (VT == MVT::i8 || VT == MVT::i1)
19092 return std::make_pair(0U, &X86::GR8RegClass);
19093 if (VT == MVT::i64 || VT == MVT::f64)
19094 return std::make_pair(0U, &X86::GR64RegClass);
19097 // 32-bit fallthrough
19098 case 'Q': // Q_REGS
19099 if (VT == MVT::i32 || VT == MVT::f32)
19100 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19101 if (VT == MVT::i16)
19102 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19103 if (VT == MVT::i8 || VT == MVT::i1)
19104 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19105 if (VT == MVT::i64)
19106 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19108 case 'r': // GENERAL_REGS
19109 case 'l': // INDEX_REGS
19110 if (VT == MVT::i8 || VT == MVT::i1)
19111 return std::make_pair(0U, &X86::GR8RegClass);
19112 if (VT == MVT::i16)
19113 return std::make_pair(0U, &X86::GR16RegClass);
19114 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19115 return std::make_pair(0U, &X86::GR32RegClass);
19116 return std::make_pair(0U, &X86::GR64RegClass);
19117 case 'R': // LEGACY_REGS
19118 if (VT == MVT::i8 || VT == MVT::i1)
19119 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19120 if (VT == MVT::i16)
19121 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19122 if (VT == MVT::i32 || !Subtarget->is64Bit())
19123 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19124 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19125 case 'f': // FP Stack registers.
19126 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19127 // value to the correct fpstack register class.
19128 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19129 return std::make_pair(0U, &X86::RFP32RegClass);
19130 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19131 return std::make_pair(0U, &X86::RFP64RegClass);
19132 return std::make_pair(0U, &X86::RFP80RegClass);
19133 case 'y': // MMX_REGS if MMX allowed.
19134 if (!Subtarget->hasMMX()) break;
19135 return std::make_pair(0U, &X86::VR64RegClass);
19136 case 'Y': // SSE_REGS if SSE2 allowed
19137 if (!Subtarget->hasSSE2()) break;
19139 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19140 if (!Subtarget->hasSSE1()) break;
19142 switch (VT.SimpleTy) {
19144 // Scalar SSE types.
19147 return std::make_pair(0U, &X86::FR32RegClass);
19150 return std::make_pair(0U, &X86::FR64RegClass);
19158 return std::make_pair(0U, &X86::VR128RegClass);
19166 return std::make_pair(0U, &X86::VR256RegClass);
19171 return std::make_pair(0U, &X86::VR512RegClass);
19177 // Use the default implementation in TargetLowering to convert the register
19178 // constraint into a member of a register class.
19179 std::pair<unsigned, const TargetRegisterClass*> Res;
19180 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19182 // Not found as a standard register?
19183 if (Res.second == 0) {
19184 // Map st(0) -> st(7) -> ST0
19185 if (Constraint.size() == 7 && Constraint[0] == '{' &&
19186 tolower(Constraint[1]) == 's' &&
19187 tolower(Constraint[2]) == 't' &&
19188 Constraint[3] == '(' &&
19189 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19190 Constraint[5] == ')' &&
19191 Constraint[6] == '}') {
19193 Res.first = X86::ST0+Constraint[4]-'0';
19194 Res.second = &X86::RFP80RegClass;
19198 // GCC allows "st(0)" to be called just plain "st".
19199 if (StringRef("{st}").equals_lower(Constraint)) {
19200 Res.first = X86::ST0;
19201 Res.second = &X86::RFP80RegClass;
19206 if (StringRef("{flags}").equals_lower(Constraint)) {
19207 Res.first = X86::EFLAGS;
19208 Res.second = &X86::CCRRegClass;
19212 // 'A' means EAX + EDX.
19213 if (Constraint == "A") {
19214 Res.first = X86::EAX;
19215 Res.second = &X86::GR32_ADRegClass;
19221 // Otherwise, check to see if this is a register class of the wrong value
19222 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19223 // turn into {ax},{dx}.
19224 if (Res.second->hasType(VT))
19225 return Res; // Correct type already, nothing to do.
19227 // All of the single-register GCC register classes map their values onto
19228 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
19229 // really want an 8-bit or 32-bit register, map to the appropriate register
19230 // class and return the appropriate register.
19231 if (Res.second == &X86::GR16RegClass) {
19232 if (VT == MVT::i8 || VT == MVT::i1) {
19233 unsigned DestReg = 0;
19234 switch (Res.first) {
19236 case X86::AX: DestReg = X86::AL; break;
19237 case X86::DX: DestReg = X86::DL; break;
19238 case X86::CX: DestReg = X86::CL; break;
19239 case X86::BX: DestReg = X86::BL; break;
19242 Res.first = DestReg;
19243 Res.second = &X86::GR8RegClass;
19245 } else if (VT == MVT::i32 || VT == MVT::f32) {
19246 unsigned DestReg = 0;
19247 switch (Res.first) {
19249 case X86::AX: DestReg = X86::EAX; break;
19250 case X86::DX: DestReg = X86::EDX; break;
19251 case X86::CX: DestReg = X86::ECX; break;
19252 case X86::BX: DestReg = X86::EBX; break;
19253 case X86::SI: DestReg = X86::ESI; break;
19254 case X86::DI: DestReg = X86::EDI; break;
19255 case X86::BP: DestReg = X86::EBP; break;
19256 case X86::SP: DestReg = X86::ESP; break;
19259 Res.first = DestReg;
19260 Res.second = &X86::GR32RegClass;
19262 } else if (VT == MVT::i64 || VT == MVT::f64) {
19263 unsigned DestReg = 0;
19264 switch (Res.first) {
19266 case X86::AX: DestReg = X86::RAX; break;
19267 case X86::DX: DestReg = X86::RDX; break;
19268 case X86::CX: DestReg = X86::RCX; break;
19269 case X86::BX: DestReg = X86::RBX; break;
19270 case X86::SI: DestReg = X86::RSI; break;
19271 case X86::DI: DestReg = X86::RDI; break;
19272 case X86::BP: DestReg = X86::RBP; break;
19273 case X86::SP: DestReg = X86::RSP; break;
19276 Res.first = DestReg;
19277 Res.second = &X86::GR64RegClass;
19280 } else if (Res.second == &X86::FR32RegClass ||
19281 Res.second == &X86::FR64RegClass ||
19282 Res.second == &X86::VR128RegClass ||
19283 Res.second == &X86::VR256RegClass ||
19284 Res.second == &X86::FR32XRegClass ||
19285 Res.second == &X86::FR64XRegClass ||
19286 Res.second == &X86::VR128XRegClass ||
19287 Res.second == &X86::VR256XRegClass ||
19288 Res.second == &X86::VR512RegClass) {
19289 // Handle references to XMM physical registers that got mapped into the
19290 // wrong class. This can happen with constraints like {xmm0} where the
19291 // target independent register mapper will just pick the first match it can
19292 // find, ignoring the required type.
19294 if (VT == MVT::f32 || VT == MVT::i32)
19295 Res.second = &X86::FR32RegClass;
19296 else if (VT == MVT::f64 || VT == MVT::i64)
19297 Res.second = &X86::FR64RegClass;
19298 else if (X86::VR128RegClass.hasType(VT))
19299 Res.second = &X86::VR128RegClass;
19300 else if (X86::VR256RegClass.hasType(VT))
19301 Res.second = &X86::VR256RegClass;
19302 else if (X86::VR512RegClass.hasType(VT))
19303 Res.second = &X86::VR512RegClass;