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 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, SDLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 // If the input is a buildvector just emit a smaller one.
89 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
90 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
91 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
93 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
94 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
100 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
101 /// sets things up to match to an AVX VINSERTF128 instruction or a
102 /// simple superregister reference. Idx is an index in the 128 bits
103 /// we want. It need not be aligned to a 128-bit bounday. That makes
104 /// lowering INSERT_VECTOR_ELT operations easier.
105 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
106 unsigned IdxVal, SelectionDAG &DAG,
108 // Inserting UNDEF is Result
109 if (Vec.getOpcode() == ISD::UNDEF)
112 EVT VT = Vec.getValueType();
113 assert(VT.is128BitVector() && "Unexpected vector size!");
115 EVT ElVT = VT.getVectorElementType();
116 EVT ResultVT = Result.getValueType();
118 // Insert the relevant 128 bits.
119 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
121 // This is the index of the first element of the 128-bit chunk
123 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
126 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
127 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
131 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
132 /// instructions. This is used because creating CONCAT_VECTOR nodes of
133 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
134 /// large BUILD_VECTORS.
135 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
136 unsigned NumElems, SelectionDAG &DAG,
138 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
139 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
142 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
143 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
144 bool is64Bit = Subtarget->is64Bit();
146 if (Subtarget->isTargetEnvMacho()) {
148 return new X86_64MachoTargetObjectFile();
149 return new TargetLoweringObjectFileMachO();
152 if (Subtarget->isTargetLinux())
153 return new X86LinuxTargetObjectFile();
154 if (Subtarget->isTargetELF())
155 return new TargetLoweringObjectFileELF();
156 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
157 return new TargetLoweringObjectFileCOFF();
158 llvm_unreachable("unknown subtarget type");
161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
162 : TargetLowering(TM, createTLOF(TM)) {
163 Subtarget = &TM.getSubtarget<X86Subtarget>();
164 X86ScalarSSEf64 = Subtarget->hasSSE2();
165 X86ScalarSSEf32 = Subtarget->hasSSE1();
166 RegInfo = TM.getRegisterInfo();
167 TD = getDataLayout();
169 resetOperationActions();
172 void X86TargetLowering::resetOperationActions() {
173 const TargetMachine &TM = getTargetMachine();
174 static bool FirstTimeThrough = true;
176 // If none of the target options have changed, then we don't need to reset the
177 // operation actions.
178 if (!FirstTimeThrough && TO == TM.Options) return;
180 if (!FirstTimeThrough) {
181 // Reinitialize the actions.
183 FirstTimeThrough = false;
188 // Set up the TargetLowering object.
189 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
191 // X86 is weird, it always uses i8 for shift amounts and setcc results.
192 setBooleanContents(ZeroOrOneBooleanContent);
193 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
194 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
196 // For 64-bit since we have so many registers use the ILP scheduler, for
197 // 32-bit code use the register pressure specific scheduling.
198 // For Atom, always use ILP scheduling.
199 if (Subtarget->isAtom())
200 setSchedulingPreference(Sched::ILP);
201 else if (Subtarget->is64Bit())
202 setSchedulingPreference(Sched::ILP);
204 setSchedulingPreference(Sched::RegPressure);
205 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
207 // Bypass expensive divides on Atom when compiling with O2
208 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
209 addBypassSlowDiv(32, 8);
210 if (Subtarget->is64Bit())
211 addBypassSlowDiv(64, 16);
214 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
215 // Setup Windows compiler runtime calls.
216 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
217 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
218 setLibcallName(RTLIB::SREM_I64, "_allrem");
219 setLibcallName(RTLIB::UREM_I64, "_aullrem");
220 setLibcallName(RTLIB::MUL_I64, "_allmul");
221 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
222 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
223 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
224 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
225 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
227 // The _ftol2 runtime function has an unusual calling conv, which
228 // is modeled by a special pseudo-instruction.
229 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
230 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
231 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
232 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
235 if (Subtarget->isTargetDarwin()) {
236 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
237 setUseUnderscoreSetJmp(false);
238 setUseUnderscoreLongJmp(false);
239 } else if (Subtarget->isTargetMingw()) {
240 // MS runtime is weird: it exports _setjmp, but longjmp!
241 setUseUnderscoreSetJmp(true);
242 setUseUnderscoreLongJmp(false);
244 setUseUnderscoreSetJmp(true);
245 setUseUnderscoreLongJmp(true);
248 // Set up the register classes.
249 addRegisterClass(MVT::i8, &X86::GR8RegClass);
250 addRegisterClass(MVT::i16, &X86::GR16RegClass);
251 addRegisterClass(MVT::i32, &X86::GR32RegClass);
252 if (Subtarget->is64Bit())
253 addRegisterClass(MVT::i64, &X86::GR64RegClass);
255 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
257 // We don't accept any truncstore of integer registers.
258 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
259 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
260 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
261 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
262 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
263 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
265 // SETOEQ and SETUNE require checking two conditions.
266 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
267 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
268 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
269 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
270 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
271 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
273 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
275 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
276 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
277 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
279 if (Subtarget->is64Bit()) {
280 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
281 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
282 } else if (!TM.Options.UseSoftFloat) {
283 // We have an algorithm for SSE2->double, and we turn this into a
284 // 64-bit FILD followed by conditional FADD for other targets.
285 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
286 // We have an algorithm for SSE2, and we turn this into a 64-bit
287 // FILD for other targets.
288 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
291 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
293 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
294 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
296 if (!TM.Options.UseSoftFloat) {
297 // SSE has no i16 to fp conversion, only i32
298 if (X86ScalarSSEf32) {
299 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
300 // f32 and f64 cases are Legal, f80 case is not
301 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
303 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
304 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
307 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
308 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
311 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
312 // are Legal, f80 is custom lowered.
313 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
314 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
316 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
318 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
319 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
321 if (X86ScalarSSEf32) {
322 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
323 // f32 and f64 cases are Legal, f80 case is not
324 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
326 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
327 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
330 // Handle FP_TO_UINT by promoting the destination to a larger signed
332 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
333 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
334 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
338 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
339 } else if (!TM.Options.UseSoftFloat) {
340 // Since AVX is a superset of SSE3, only check for SSE here.
341 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
342 // Expand FP_TO_UINT into a select.
343 // FIXME: We would like to use a Custom expander here eventually to do
344 // the optimal thing for SSE vs. the default expansion in the legalizer.
345 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
347 // With SSE3 we can use fisttpll to convert to a signed i64; without
348 // SSE, we're stuck with a fistpll.
349 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
352 if (isTargetFTOL()) {
353 // Use the _ftol2 runtime function, which has a pseudo-instruction
354 // to handle its weird calling convention.
355 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
358 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
359 if (!X86ScalarSSEf64) {
360 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
361 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
362 if (Subtarget->is64Bit()) {
363 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
364 // Without SSE, i64->f64 goes through memory.
365 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
369 // Scalar integer divide and remainder are lowered to use operations that
370 // produce two results, to match the available instructions. This exposes
371 // the two-result form to trivial CSE, which is able to combine x/y and x%y
372 // into a single instruction.
374 // Scalar integer multiply-high is also lowered to use two-result
375 // operations, to match the available instructions. However, plain multiply
376 // (low) operations are left as Legal, as there are single-result
377 // instructions for this in x86. Using the two-result multiply instructions
378 // when both high and low results are needed must be arranged by dagcombine.
379 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
381 setOperationAction(ISD::MULHS, VT, Expand);
382 setOperationAction(ISD::MULHU, VT, Expand);
383 setOperationAction(ISD::SDIV, VT, Expand);
384 setOperationAction(ISD::UDIV, VT, Expand);
385 setOperationAction(ISD::SREM, VT, Expand);
386 setOperationAction(ISD::UREM, VT, Expand);
388 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
389 setOperationAction(ISD::ADDC, VT, Custom);
390 setOperationAction(ISD::ADDE, VT, Custom);
391 setOperationAction(ISD::SUBC, VT, Custom);
392 setOperationAction(ISD::SUBE, VT, Custom);
395 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
396 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
397 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
398 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
399 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
400 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
401 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
402 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
403 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
404 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
405 if (Subtarget->is64Bit())
406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
408 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
409 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
410 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
411 setOperationAction(ISD::FREM , MVT::f32 , Expand);
412 setOperationAction(ISD::FREM , MVT::f64 , Expand);
413 setOperationAction(ISD::FREM , MVT::f80 , Expand);
414 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
416 // Promote the i8 variants and force them on up to i32 which has a shorter
418 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
419 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
420 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
421 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
422 if (Subtarget->hasBMI()) {
423 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
424 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
425 if (Subtarget->is64Bit())
426 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
428 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
429 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
430 if (Subtarget->is64Bit())
431 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
434 if (Subtarget->hasLZCNT()) {
435 // When promoting the i8 variants, force them to i32 for a shorter
437 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
438 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
439 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
440 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
441 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
442 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
443 if (Subtarget->is64Bit())
444 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
446 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
447 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
448 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
449 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
450 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
451 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
452 if (Subtarget->is64Bit()) {
453 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
454 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
458 if (Subtarget->hasPOPCNT()) {
459 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
461 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
462 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
463 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
468 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
469 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
471 // These should be promoted to a larger select which is supported.
472 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
473 // X86 wants to expand cmov itself.
474 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
475 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
476 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
477 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
478 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
479 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
480 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
481 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
482 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
483 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
484 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
485 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
486 if (Subtarget->is64Bit()) {
487 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
488 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
490 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
491 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
492 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
493 // support continuation, user-level threading, and etc.. As a result, no
494 // other SjLj exception interfaces are implemented and please don't build
495 // your own exception handling based on them.
496 // LLVM/Clang supports zero-cost DWARF exception handling.
497 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
498 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
501 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
502 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
503 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
504 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
505 if (Subtarget->is64Bit())
506 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
507 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
508 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
509 if (Subtarget->is64Bit()) {
510 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
511 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
512 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
513 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
514 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
516 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
517 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
518 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
519 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
520 if (Subtarget->is64Bit()) {
521 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
522 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
523 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
526 if (Subtarget->hasSSE1())
527 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
529 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
531 // Expand certain atomics
532 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
534 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
535 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
536 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
539 if (!Subtarget->is64Bit()) {
540 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
541 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
542 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
543 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
544 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
545 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
546 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
547 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
548 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
549 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
550 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
551 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
554 if (Subtarget->hasCmpxchg16b()) {
555 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
558 // FIXME - use subtarget debug flags
559 if (!Subtarget->isTargetDarwin() &&
560 !Subtarget->isTargetELF() &&
561 !Subtarget->isTargetCygMing()) {
562 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
565 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
566 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
567 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
568 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
569 if (Subtarget->is64Bit()) {
570 setExceptionPointerRegister(X86::RAX);
571 setExceptionSelectorRegister(X86::RDX);
573 setExceptionPointerRegister(X86::EAX);
574 setExceptionSelectorRegister(X86::EDX);
576 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
577 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
579 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
580 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
582 setOperationAction(ISD::TRAP, MVT::Other, Legal);
583 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
585 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
586 setOperationAction(ISD::VASTART , MVT::Other, Custom);
587 setOperationAction(ISD::VAEND , MVT::Other, Expand);
588 if (Subtarget->is64Bit()) {
589 setOperationAction(ISD::VAARG , MVT::Other, Custom);
590 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
592 setOperationAction(ISD::VAARG , MVT::Other, Expand);
593 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
596 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
597 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
599 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
600 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
601 MVT::i64 : MVT::i32, Custom);
602 else if (TM.Options.EnableSegmentedStacks)
603 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
604 MVT::i64 : MVT::i32, Custom);
606 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
607 MVT::i64 : MVT::i32, Expand);
609 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
610 // f32 and f64 use SSE.
611 // Set up the FP register classes.
612 addRegisterClass(MVT::f32, &X86::FR32RegClass);
613 addRegisterClass(MVT::f64, &X86::FR64RegClass);
615 // Use ANDPD to simulate FABS.
616 setOperationAction(ISD::FABS , MVT::f64, Custom);
617 setOperationAction(ISD::FABS , MVT::f32, Custom);
619 // Use XORP to simulate FNEG.
620 setOperationAction(ISD::FNEG , MVT::f64, Custom);
621 setOperationAction(ISD::FNEG , MVT::f32, Custom);
623 // Use ANDPD and ORPD to simulate FCOPYSIGN.
624 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
625 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
627 // Lower this to FGETSIGNx86 plus an AND.
628 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
629 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
631 // We don't support sin/cos/fmod
632 setOperationAction(ISD::FSIN , MVT::f64, Expand);
633 setOperationAction(ISD::FCOS , MVT::f64, Expand);
634 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
635 setOperationAction(ISD::FSIN , MVT::f32, Expand);
636 setOperationAction(ISD::FCOS , MVT::f32, Expand);
637 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
639 // Expand FP immediates into loads from the stack, except for the special
641 addLegalFPImmediate(APFloat(+0.0)); // xorpd
642 addLegalFPImmediate(APFloat(+0.0f)); // xorps
643 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
644 // Use SSE for f32, x87 for f64.
645 // Set up the FP register classes.
646 addRegisterClass(MVT::f32, &X86::FR32RegClass);
647 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
649 // Use ANDPS to simulate FABS.
650 setOperationAction(ISD::FABS , MVT::f32, Custom);
652 // Use XORP to simulate FNEG.
653 setOperationAction(ISD::FNEG , MVT::f32, Custom);
655 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
657 // Use ANDPS and ORPS to simulate FCOPYSIGN.
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661 // We don't support sin/cos/fmod
662 setOperationAction(ISD::FSIN , MVT::f32, Expand);
663 setOperationAction(ISD::FCOS , MVT::f32, Expand);
664 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
666 // Special cases we handle for FP constants.
667 addLegalFPImmediate(APFloat(+0.0f)); // xorps
668 addLegalFPImmediate(APFloat(+0.0)); // FLD0
669 addLegalFPImmediate(APFloat(+1.0)); // FLD1
670 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
673 if (!TM.Options.UnsafeFPMath) {
674 setOperationAction(ISD::FSIN , MVT::f64, Expand);
675 setOperationAction(ISD::FCOS , MVT::f64, Expand);
676 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
678 } else if (!TM.Options.UseSoftFloat) {
679 // f32 and f64 in x87.
680 // Set up the FP register classes.
681 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
684 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
685 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
686 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
687 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
689 if (!TM.Options.UnsafeFPMath) {
690 setOperationAction(ISD::FSIN , MVT::f64, Expand);
691 setOperationAction(ISD::FSIN , MVT::f32, Expand);
692 setOperationAction(ISD::FCOS , MVT::f64, Expand);
693 setOperationAction(ISD::FCOS , MVT::f32, Expand);
694 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
695 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
697 addLegalFPImmediate(APFloat(+0.0)); // FLD0
698 addLegalFPImmediate(APFloat(+1.0)); // FLD1
699 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
700 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
701 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
702 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
703 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
704 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
707 // We don't support FMA.
708 setOperationAction(ISD::FMA, MVT::f64, Expand);
709 setOperationAction(ISD::FMA, MVT::f32, Expand);
711 // Long double always uses X87.
712 if (!TM.Options.UseSoftFloat) {
713 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
714 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
715 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
717 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
718 addLegalFPImmediate(TmpFlt); // FLD0
720 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
723 APFloat TmpFlt2(+1.0);
724 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
726 addLegalFPImmediate(TmpFlt2); // FLD1
727 TmpFlt2.changeSign();
728 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
731 if (!TM.Options.UnsafeFPMath) {
732 setOperationAction(ISD::FSIN , MVT::f80, Expand);
733 setOperationAction(ISD::FCOS , MVT::f80, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
737 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
738 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
739 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
740 setOperationAction(ISD::FRINT, MVT::f80, Expand);
741 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
742 setOperationAction(ISD::FMA, MVT::f80, Expand);
745 // Always use a library call for pow.
746 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
747 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
748 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
750 setOperationAction(ISD::FLOG, MVT::f80, Expand);
751 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
752 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
753 setOperationAction(ISD::FEXP, MVT::f80, Expand);
754 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
756 // First set operation action for all vector types to either promote
757 // (for widening) or expand (for scalarization). Then we will selectively
758 // turn on ones that can be effectively codegen'd.
759 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
760 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
761 MVT VT = (MVT::SimpleValueType)i;
762 setOperationAction(ISD::ADD , VT, Expand);
763 setOperationAction(ISD::SUB , VT, Expand);
764 setOperationAction(ISD::FADD, VT, Expand);
765 setOperationAction(ISD::FNEG, VT, Expand);
766 setOperationAction(ISD::FSUB, VT, Expand);
767 setOperationAction(ISD::MUL , VT, Expand);
768 setOperationAction(ISD::FMUL, VT, Expand);
769 setOperationAction(ISD::SDIV, VT, Expand);
770 setOperationAction(ISD::UDIV, VT, Expand);
771 setOperationAction(ISD::FDIV, VT, Expand);
772 setOperationAction(ISD::SREM, VT, Expand);
773 setOperationAction(ISD::UREM, VT, Expand);
774 setOperationAction(ISD::LOAD, VT, Expand);
775 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
777 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
778 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
779 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
780 setOperationAction(ISD::FABS, VT, Expand);
781 setOperationAction(ISD::FSIN, VT, Expand);
782 setOperationAction(ISD::FSINCOS, VT, Expand);
783 setOperationAction(ISD::FCOS, VT, Expand);
784 setOperationAction(ISD::FSINCOS, VT, Expand);
785 setOperationAction(ISD::FREM, VT, Expand);
786 setOperationAction(ISD::FMA, VT, Expand);
787 setOperationAction(ISD::FPOWI, VT, Expand);
788 setOperationAction(ISD::FSQRT, VT, Expand);
789 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
790 setOperationAction(ISD::FFLOOR, VT, Expand);
791 setOperationAction(ISD::FCEIL, VT, Expand);
792 setOperationAction(ISD::FTRUNC, VT, Expand);
793 setOperationAction(ISD::FRINT, VT, Expand);
794 setOperationAction(ISD::FNEARBYINT, VT, Expand);
795 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
796 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
797 setOperationAction(ISD::SDIVREM, VT, Expand);
798 setOperationAction(ISD::UDIVREM, VT, Expand);
799 setOperationAction(ISD::FPOW, VT, Expand);
800 setOperationAction(ISD::CTPOP, VT, Expand);
801 setOperationAction(ISD::CTTZ, VT, Expand);
802 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
803 setOperationAction(ISD::CTLZ, VT, Expand);
804 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
805 setOperationAction(ISD::SHL, VT, Expand);
806 setOperationAction(ISD::SRA, VT, Expand);
807 setOperationAction(ISD::SRL, VT, Expand);
808 setOperationAction(ISD::ROTL, VT, Expand);
809 setOperationAction(ISD::ROTR, VT, Expand);
810 setOperationAction(ISD::BSWAP, VT, Expand);
811 setOperationAction(ISD::SETCC, VT, Expand);
812 setOperationAction(ISD::FLOG, VT, Expand);
813 setOperationAction(ISD::FLOG2, VT, Expand);
814 setOperationAction(ISD::FLOG10, VT, Expand);
815 setOperationAction(ISD::FEXP, VT, Expand);
816 setOperationAction(ISD::FEXP2, VT, Expand);
817 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
818 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
819 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
820 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
821 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
822 setOperationAction(ISD::TRUNCATE, VT, Expand);
823 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
824 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
825 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
826 setOperationAction(ISD::VSELECT, VT, Expand);
827 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
828 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
829 setTruncStoreAction(VT,
830 (MVT::SimpleValueType)InnerVT, Expand);
831 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
832 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
833 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
836 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
837 // with -msoft-float, disable use of MMX as well.
838 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
839 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
840 // No operations on x86mmx supported, everything uses intrinsics.
843 // MMX-sized vectors (other than x86mmx) are expected to be expanded
844 // into smaller operations.
845 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
846 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
847 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
848 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
849 setOperationAction(ISD::AND, MVT::v8i8, Expand);
850 setOperationAction(ISD::AND, MVT::v4i16, Expand);
851 setOperationAction(ISD::AND, MVT::v2i32, Expand);
852 setOperationAction(ISD::AND, MVT::v1i64, Expand);
853 setOperationAction(ISD::OR, MVT::v8i8, Expand);
854 setOperationAction(ISD::OR, MVT::v4i16, Expand);
855 setOperationAction(ISD::OR, MVT::v2i32, Expand);
856 setOperationAction(ISD::OR, MVT::v1i64, Expand);
857 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
858 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
859 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
860 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
861 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
862 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
863 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
864 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
865 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
866 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
867 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
868 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
869 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
870 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
871 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
872 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
873 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
875 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
876 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
878 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
879 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
880 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
881 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
882 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
883 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
884 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
885 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
886 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
887 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
888 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
889 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
892 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
893 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
895 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
896 // registers cannot be used even for integer operations.
897 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
898 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
899 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
900 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
902 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
903 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
904 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
905 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
906 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
907 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
908 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
909 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
910 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
911 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
912 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
913 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
914 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
915 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
916 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
917 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
918 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
919 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
921 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
922 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
923 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
924 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
928 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
930 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
932 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
933 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
934 MVT VT = (MVT::SimpleValueType)i;
935 // Do not attempt to custom lower non-power-of-2 vectors
936 if (!isPowerOf2_32(VT.getVectorNumElements()))
938 // Do not attempt to custom lower non-128-bit vectors
939 if (!VT.is128BitVector())
941 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
942 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
946 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
947 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
948 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
949 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
950 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
951 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
953 if (Subtarget->is64Bit()) {
954 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
955 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
958 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
959 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
960 MVT VT = (MVT::SimpleValueType)i;
962 // Do not attempt to promote non-128-bit vectors
963 if (!VT.is128BitVector())
966 setOperationAction(ISD::AND, VT, Promote);
967 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
968 setOperationAction(ISD::OR, VT, Promote);
969 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
970 setOperationAction(ISD::XOR, VT, Promote);
971 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
972 setOperationAction(ISD::LOAD, VT, Promote);
973 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
974 setOperationAction(ISD::SELECT, VT, Promote);
975 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
978 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
980 // Custom lower v2i64 and v2f64 selects.
981 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
982 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
983 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
984 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
986 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
987 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
989 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
990 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
991 // As there is no 64-bit GPR available, we need build a special custom
992 // sequence to convert from v2i32 to v2f32.
993 if (!Subtarget->is64Bit())
994 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
996 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
997 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
999 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1002 if (Subtarget->hasSSE41()) {
1003 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1004 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1005 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1006 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1007 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1008 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1009 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1010 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1011 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1012 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1014 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1015 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1016 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1017 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1018 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1019 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1020 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1021 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1022 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1023 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1025 // FIXME: Do we need to handle scalar-to-vector here?
1026 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1028 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1029 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1030 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1031 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1032 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1034 // i8 and i16 vectors are custom , because the source register and source
1035 // source memory operand types are not the same width. f32 vectors are
1036 // custom since the immediate controlling the insert encodes additional
1038 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1039 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1040 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1041 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1043 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1044 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1045 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1046 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1048 // FIXME: these should be Legal but thats only for the case where
1049 // the index is constant. For now custom expand to deal with that.
1050 if (Subtarget->is64Bit()) {
1051 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1052 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1056 if (Subtarget->hasSSE2()) {
1057 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1058 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1060 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1061 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1063 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1064 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1066 // In the customized shift lowering, the legal cases in AVX2 will be
1068 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1069 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1071 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1072 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1074 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1076 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1077 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1080 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1081 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1082 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1083 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1084 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1085 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1086 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1088 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1089 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1090 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1092 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1093 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1094 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1095 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1096 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1097 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1098 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1099 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1100 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1101 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1102 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1103 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1105 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1106 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1107 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1108 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1109 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1110 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1111 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1112 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1113 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1114 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1115 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1116 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1118 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1119 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1121 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1123 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1124 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1125 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1126 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1128 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1129 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1130 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1132 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1134 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1135 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1137 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1138 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1140 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1141 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1143 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1145 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1146 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1147 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1148 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1150 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1151 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1152 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1154 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1155 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1156 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1157 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1159 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1160 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1161 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1162 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1163 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1164 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1166 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1167 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1168 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1169 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1170 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1171 setOperationAction(ISD::FMA, MVT::f32, Legal);
1172 setOperationAction(ISD::FMA, MVT::f64, Legal);
1175 if (Subtarget->hasInt256()) {
1176 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1177 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1178 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1179 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1181 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1182 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1183 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1184 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1186 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1187 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1188 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1189 // Don't lower v32i8 because there is no 128-bit byte mul
1191 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1193 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1195 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1196 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1197 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1198 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1200 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1201 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1202 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1203 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1205 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1206 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1207 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1208 // Don't lower v32i8 because there is no 128-bit byte mul
1211 // In the customized shift lowering, the legal cases in AVX2 will be
1213 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1214 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1216 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1217 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1219 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1221 // Custom lower several nodes for 256-bit types.
1222 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1223 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1224 MVT VT = (MVT::SimpleValueType)i;
1226 // Extract subvector is special because the value type
1227 // (result) is 128-bit but the source is 256-bit wide.
1228 if (VT.is128BitVector())
1229 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1231 // Do not attempt to custom lower other non-256-bit vectors
1232 if (!VT.is256BitVector())
1235 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1236 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1237 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1238 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1239 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1240 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1241 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1244 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1245 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1246 MVT VT = (MVT::SimpleValueType)i;
1248 // Do not attempt to promote non-256-bit vectors
1249 if (!VT.is256BitVector())
1252 setOperationAction(ISD::AND, VT, Promote);
1253 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1254 setOperationAction(ISD::OR, VT, Promote);
1255 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1256 setOperationAction(ISD::XOR, VT, Promote);
1257 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1258 setOperationAction(ISD::LOAD, VT, Promote);
1259 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1260 setOperationAction(ISD::SELECT, VT, Promote);
1261 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1266 // of this type with custom code.
1267 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1268 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1269 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1273 // We want to custom lower some of our intrinsics.
1274 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1275 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1277 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1278 // handle type legalization for these operations here.
1280 // FIXME: We really should do custom legalization for addition and
1281 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1282 // than generic legalization for 64-bit multiplication-with-overflow, though.
1283 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1284 // Add/Sub/Mul with overflow operations are custom lowered.
1286 setOperationAction(ISD::SADDO, VT, Custom);
1287 setOperationAction(ISD::UADDO, VT, Custom);
1288 setOperationAction(ISD::SSUBO, VT, Custom);
1289 setOperationAction(ISD::USUBO, VT, Custom);
1290 setOperationAction(ISD::SMULO, VT, Custom);
1291 setOperationAction(ISD::UMULO, VT, Custom);
1294 // There are no 8-bit 3-address imul/mul instructions
1295 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1296 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1298 if (!Subtarget->is64Bit()) {
1299 // These libcalls are not available in 32-bit.
1300 setLibcallName(RTLIB::SHL_I128, 0);
1301 setLibcallName(RTLIB::SRL_I128, 0);
1302 setLibcallName(RTLIB::SRA_I128, 0);
1305 // Combine sin / cos into one node or libcall if possible.
1306 if (Subtarget->hasSinCos()) {
1307 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1308 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1309 if (Subtarget->isTargetDarwin()) {
1310 // For MacOSX, we don't want to the normal expansion of a libcall to
1311 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1313 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1314 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1318 // We have target-specific dag combine patterns for the following nodes:
1319 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1320 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1321 setTargetDAGCombine(ISD::VSELECT);
1322 setTargetDAGCombine(ISD::SELECT);
1323 setTargetDAGCombine(ISD::SHL);
1324 setTargetDAGCombine(ISD::SRA);
1325 setTargetDAGCombine(ISD::SRL);
1326 setTargetDAGCombine(ISD::OR);
1327 setTargetDAGCombine(ISD::AND);
1328 setTargetDAGCombine(ISD::ADD);
1329 setTargetDAGCombine(ISD::FADD);
1330 setTargetDAGCombine(ISD::FSUB);
1331 setTargetDAGCombine(ISD::FMA);
1332 setTargetDAGCombine(ISD::SUB);
1333 setTargetDAGCombine(ISD::LOAD);
1334 setTargetDAGCombine(ISD::STORE);
1335 setTargetDAGCombine(ISD::ZERO_EXTEND);
1336 setTargetDAGCombine(ISD::ANY_EXTEND);
1337 setTargetDAGCombine(ISD::SIGN_EXTEND);
1338 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1339 setTargetDAGCombine(ISD::TRUNCATE);
1340 setTargetDAGCombine(ISD::SINT_TO_FP);
1341 setTargetDAGCombine(ISD::SETCC);
1342 if (Subtarget->is64Bit())
1343 setTargetDAGCombine(ISD::MUL);
1344 setTargetDAGCombine(ISD::XOR);
1346 computeRegisterProperties();
1348 // On Darwin, -Os means optimize for size without hurting performance,
1349 // do not reduce the limit.
1350 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1351 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1352 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1353 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1354 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1355 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1356 setPrefLoopAlignment(4); // 2^4 bytes.
1358 // Predictable cmov don't hurt on atom because it's in-order.
1359 PredictableSelectIsExpensive = !Subtarget->isAtom();
1361 setPrefFunctionAlignment(4); // 2^4 bytes.
1364 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1365 if (!VT.isVector()) return MVT::i8;
1366 return VT.changeVectorElementTypeToInteger();
1369 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1370 /// the desired ByVal argument alignment.
1371 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1374 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1375 if (VTy->getBitWidth() == 128)
1377 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1378 unsigned EltAlign = 0;
1379 getMaxByValAlign(ATy->getElementType(), EltAlign);
1380 if (EltAlign > MaxAlign)
1381 MaxAlign = EltAlign;
1382 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1383 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1384 unsigned EltAlign = 0;
1385 getMaxByValAlign(STy->getElementType(i), EltAlign);
1386 if (EltAlign > MaxAlign)
1387 MaxAlign = EltAlign;
1394 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1395 /// function arguments in the caller parameter area. For X86, aggregates
1396 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1397 /// are at 4-byte boundaries.
1398 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1399 if (Subtarget->is64Bit()) {
1400 // Max of 8 and alignment of type.
1401 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1408 if (Subtarget->hasSSE1())
1409 getMaxByValAlign(Ty, Align);
1413 /// getOptimalMemOpType - Returns the target specific optimal type for load
1414 /// and store operations as a result of memset, memcpy, and memmove
1415 /// lowering. If DstAlign is zero that means it's safe to destination
1416 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1417 /// means there isn't a need to check it against alignment requirement,
1418 /// probably because the source does not need to be loaded. If 'IsMemset' is
1419 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1420 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1421 /// source is constant so it does not need to be loaded.
1422 /// It returns EVT::Other if the type should be determined using generic
1423 /// target-independent logic.
1425 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1426 unsigned DstAlign, unsigned SrcAlign,
1427 bool IsMemset, bool ZeroMemset,
1429 MachineFunction &MF) const {
1430 const Function *F = MF.getFunction();
1431 if ((!IsMemset || ZeroMemset) &&
1432 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1433 Attribute::NoImplicitFloat)) {
1435 (Subtarget->isUnalignedMemAccessFast() ||
1436 ((DstAlign == 0 || DstAlign >= 16) &&
1437 (SrcAlign == 0 || SrcAlign >= 16)))) {
1439 if (Subtarget->hasInt256())
1441 if (Subtarget->hasFp256())
1444 if (Subtarget->hasSSE2())
1446 if (Subtarget->hasSSE1())
1448 } else if (!MemcpyStrSrc && Size >= 8 &&
1449 !Subtarget->is64Bit() &&
1450 Subtarget->hasSSE2()) {
1451 // Do not use f64 to lower memcpy if source is string constant. It's
1452 // better to use i32 to avoid the loads.
1456 if (Subtarget->is64Bit() && Size >= 8)
1461 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1463 return X86ScalarSSEf32;
1464 else if (VT == MVT::f64)
1465 return X86ScalarSSEf64;
1470 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1472 *Fast = Subtarget->isUnalignedMemAccessFast();
1476 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1477 /// current function. The returned value is a member of the
1478 /// MachineJumpTableInfo::JTEntryKind enum.
1479 unsigned X86TargetLowering::getJumpTableEncoding() const {
1480 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1482 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1483 Subtarget->isPICStyleGOT())
1484 return MachineJumpTableInfo::EK_Custom32;
1486 // Otherwise, use the normal jump table encoding heuristics.
1487 return TargetLowering::getJumpTableEncoding();
1491 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1492 const MachineBasicBlock *MBB,
1493 unsigned uid,MCContext &Ctx) const{
1494 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1495 Subtarget->isPICStyleGOT());
1496 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1498 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1499 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1502 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1504 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1505 SelectionDAG &DAG) const {
1506 if (!Subtarget->is64Bit())
1507 // This doesn't have SDLoc associated with it, but is not really the
1508 // same as a Register.
1509 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1513 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1514 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1516 const MCExpr *X86TargetLowering::
1517 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1518 MCContext &Ctx) const {
1519 // X86-64 uses RIP relative addressing based on the jump table label.
1520 if (Subtarget->isPICStyleRIPRel())
1521 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1523 // Otherwise, the reference is relative to the PIC base.
1524 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1527 // FIXME: Why this routine is here? Move to RegInfo!
1528 std::pair<const TargetRegisterClass*, uint8_t>
1529 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1530 const TargetRegisterClass *RRC = 0;
1532 switch (VT.SimpleTy) {
1534 return TargetLowering::findRepresentativeClass(VT);
1535 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1536 RRC = Subtarget->is64Bit() ?
1537 (const TargetRegisterClass*)&X86::GR64RegClass :
1538 (const TargetRegisterClass*)&X86::GR32RegClass;
1541 RRC = &X86::VR64RegClass;
1543 case MVT::f32: case MVT::f64:
1544 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1545 case MVT::v4f32: case MVT::v2f64:
1546 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1548 RRC = &X86::VR128RegClass;
1551 return std::make_pair(RRC, Cost);
1554 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1555 unsigned &Offset) const {
1556 if (!Subtarget->isTargetLinux())
1559 if (Subtarget->is64Bit()) {
1560 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1562 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1574 //===----------------------------------------------------------------------===//
1575 // Return Value Calling Convention Implementation
1576 //===----------------------------------------------------------------------===//
1578 #include "X86GenCallingConv.inc"
1581 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1582 MachineFunction &MF, bool isVarArg,
1583 const SmallVectorImpl<ISD::OutputArg> &Outs,
1584 LLVMContext &Context) const {
1585 SmallVector<CCValAssign, 16> RVLocs;
1586 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1588 return CCInfo.CheckReturn(Outs, RetCC_X86);
1592 X86TargetLowering::LowerReturn(SDValue Chain,
1593 CallingConv::ID CallConv, bool isVarArg,
1594 const SmallVectorImpl<ISD::OutputArg> &Outs,
1595 const SmallVectorImpl<SDValue> &OutVals,
1596 SDLoc dl, SelectionDAG &DAG) const {
1597 MachineFunction &MF = DAG.getMachineFunction();
1598 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1600 SmallVector<CCValAssign, 16> RVLocs;
1601 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1602 RVLocs, *DAG.getContext());
1603 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1606 SmallVector<SDValue, 6> RetOps;
1607 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1608 // Operand #1 = Bytes To Pop
1609 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1612 // Copy the result values into the output registers.
1613 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1614 CCValAssign &VA = RVLocs[i];
1615 assert(VA.isRegLoc() && "Can only return in registers!");
1616 SDValue ValToCopy = OutVals[i];
1617 EVT ValVT = ValToCopy.getValueType();
1619 // Promote values to the appropriate types
1620 if (VA.getLocInfo() == CCValAssign::SExt)
1621 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1622 else if (VA.getLocInfo() == CCValAssign::ZExt)
1623 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1624 else if (VA.getLocInfo() == CCValAssign::AExt)
1625 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1626 else if (VA.getLocInfo() == CCValAssign::BCvt)
1627 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1629 // If this is x86-64, and we disabled SSE, we can't return FP values,
1630 // or SSE or MMX vectors.
1631 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1632 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1633 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1634 report_fatal_error("SSE register return with SSE disabled");
1636 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1637 // llvm-gcc has never done it right and no one has noticed, so this
1638 // should be OK for now.
1639 if (ValVT == MVT::f64 &&
1640 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1641 report_fatal_error("SSE2 register return with SSE2 disabled");
1643 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1644 // the RET instruction and handled by the FP Stackifier.
1645 if (VA.getLocReg() == X86::ST0 ||
1646 VA.getLocReg() == X86::ST1) {
1647 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1648 // change the value to the FP stack register class.
1649 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1650 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1651 RetOps.push_back(ValToCopy);
1652 // Don't emit a copytoreg.
1656 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1657 // which is returned in RAX / RDX.
1658 if (Subtarget->is64Bit()) {
1659 if (ValVT == MVT::x86mmx) {
1660 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1661 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1662 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1664 // If we don't have SSE2 available, convert to v4f32 so the generated
1665 // register is legal.
1666 if (!Subtarget->hasSSE2())
1667 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1672 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1673 Flag = Chain.getValue(1);
1674 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1677 // The x86-64 ABIs require that for returning structs by value we copy
1678 // the sret argument into %rax/%eax (depending on ABI) for the return.
1679 // Win32 requires us to put the sret argument to %eax as well.
1680 // We saved the argument into a virtual register in the entry block,
1681 // so now we copy the value out and into %rax/%eax.
1682 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1683 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1684 MachineFunction &MF = DAG.getMachineFunction();
1685 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1686 unsigned Reg = FuncInfo->getSRetReturnReg();
1688 "SRetReturnReg should have been set in LowerFormalArguments().");
1689 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1692 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1693 X86::RAX : X86::EAX;
1694 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1695 Flag = Chain.getValue(1);
1697 // RAX/EAX now acts like a return value.
1698 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1701 RetOps[0] = Chain; // Update chain.
1703 // Add the flag if we have it.
1705 RetOps.push_back(Flag);
1707 return DAG.getNode(X86ISD::RET_FLAG, dl,
1708 MVT::Other, &RetOps[0], RetOps.size());
1711 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1712 if (N->getNumValues() != 1)
1714 if (!N->hasNUsesOfValue(1, 0))
1717 SDValue TCChain = Chain;
1718 SDNode *Copy = *N->use_begin();
1719 if (Copy->getOpcode() == ISD::CopyToReg) {
1720 // If the copy has a glue operand, we conservatively assume it isn't safe to
1721 // perform a tail call.
1722 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1724 TCChain = Copy->getOperand(0);
1725 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1728 bool HasRet = false;
1729 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1731 if (UI->getOpcode() != X86ISD::RET_FLAG)
1744 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1745 ISD::NodeType ExtendKind) const {
1747 // TODO: Is this also valid on 32-bit?
1748 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1749 ReturnMVT = MVT::i8;
1751 ReturnMVT = MVT::i32;
1753 MVT MinVT = getRegisterType(ReturnMVT);
1754 return VT.bitsLT(MinVT) ? MinVT : VT;
1757 /// LowerCallResult - Lower the result values of a call into the
1758 /// appropriate copies out of appropriate physical registers.
1761 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1762 CallingConv::ID CallConv, bool isVarArg,
1763 const SmallVectorImpl<ISD::InputArg> &Ins,
1764 SDLoc dl, SelectionDAG &DAG,
1765 SmallVectorImpl<SDValue> &InVals) const {
1767 // Assign locations to each value returned by this call.
1768 SmallVector<CCValAssign, 16> RVLocs;
1769 bool Is64Bit = Subtarget->is64Bit();
1770 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1771 getTargetMachine(), RVLocs, *DAG.getContext());
1772 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1774 // Copy all of the result registers out of their specified physreg.
1775 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1776 CCValAssign &VA = RVLocs[i];
1777 EVT CopyVT = VA.getValVT();
1779 // If this is x86-64, and we disabled SSE, we can't return FP values
1780 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1781 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1782 report_fatal_error("SSE register return with SSE disabled");
1787 // If this is a call to a function that returns an fp value on the floating
1788 // point stack, we must guarantee the value is popped from the stack, so
1789 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1790 // if the return value is not used. We use the FpPOP_RETVAL instruction
1792 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1793 // If we prefer to use the value in xmm registers, copy it out as f80 and
1794 // use a truncate to move it from fp stack reg to xmm reg.
1795 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1796 SDValue Ops[] = { Chain, InFlag };
1797 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1798 MVT::Other, MVT::Glue, Ops), 1);
1799 Val = Chain.getValue(0);
1801 // Round the f80 to the right size, which also moves it to the appropriate
1803 if (CopyVT != VA.getValVT())
1804 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1805 // This truncation won't change the value.
1806 DAG.getIntPtrConstant(1));
1808 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1809 CopyVT, InFlag).getValue(1);
1810 Val = Chain.getValue(0);
1812 InFlag = Chain.getValue(2);
1813 InVals.push_back(Val);
1819 //===----------------------------------------------------------------------===//
1820 // C & StdCall & Fast Calling Convention implementation
1821 //===----------------------------------------------------------------------===//
1822 // StdCall calling convention seems to be standard for many Windows' API
1823 // routines and around. It differs from C calling convention just a little:
1824 // callee should clean up the stack, not caller. Symbols should be also
1825 // decorated in some fancy way :) It doesn't support any vector arguments.
1826 // For info on fast calling convention see Fast Calling Convention (tail call)
1827 // implementation LowerX86_32FastCCCallTo.
1829 /// CallIsStructReturn - Determines whether a call uses struct return
1831 enum StructReturnType {
1836 static StructReturnType
1837 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1839 return NotStructReturn;
1841 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1842 if (!Flags.isSRet())
1843 return NotStructReturn;
1844 if (Flags.isInReg())
1845 return RegStructReturn;
1846 return StackStructReturn;
1849 /// ArgsAreStructReturn - Determines whether a function uses struct
1850 /// return semantics.
1851 static StructReturnType
1852 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1854 return NotStructReturn;
1856 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1857 if (!Flags.isSRet())
1858 return NotStructReturn;
1859 if (Flags.isInReg())
1860 return RegStructReturn;
1861 return StackStructReturn;
1864 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1865 /// by "Src" to address "Dst" with size and alignment information specified by
1866 /// the specific parameter attribute. The copy will be passed as a byval
1867 /// function parameter.
1869 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1870 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1872 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1874 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1875 /*isVolatile*/false, /*AlwaysInline=*/true,
1876 MachinePointerInfo(), MachinePointerInfo());
1879 /// IsTailCallConvention - Return true if the calling convention is one that
1880 /// supports tail call optimization.
1881 static bool IsTailCallConvention(CallingConv::ID CC) {
1882 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1883 CC == CallingConv::HiPE);
1886 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1887 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1891 CallingConv::ID CalleeCC = CS.getCallingConv();
1892 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1898 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1899 /// a tailcall target by changing its ABI.
1900 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1901 bool GuaranteedTailCallOpt) {
1902 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1906 X86TargetLowering::LowerMemArgument(SDValue Chain,
1907 CallingConv::ID CallConv,
1908 const SmallVectorImpl<ISD::InputArg> &Ins,
1909 SDLoc dl, SelectionDAG &DAG,
1910 const CCValAssign &VA,
1911 MachineFrameInfo *MFI,
1913 // Create the nodes corresponding to a load from this parameter slot.
1914 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1915 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1916 getTargetMachine().Options.GuaranteedTailCallOpt);
1917 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1920 // If value is passed by pointer we have address passed instead of the value
1922 if (VA.getLocInfo() == CCValAssign::Indirect)
1923 ValVT = VA.getLocVT();
1925 ValVT = VA.getValVT();
1927 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1928 // changed with more analysis.
1929 // In case of tail call optimization mark all arguments mutable. Since they
1930 // could be overwritten by lowering of arguments in case of a tail call.
1931 if (Flags.isByVal()) {
1932 unsigned Bytes = Flags.getByValSize();
1933 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1934 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1935 return DAG.getFrameIndex(FI, getPointerTy());
1937 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1938 VA.getLocMemOffset(), isImmutable);
1939 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1940 return DAG.getLoad(ValVT, dl, Chain, FIN,
1941 MachinePointerInfo::getFixedStack(FI),
1942 false, false, false, 0);
1947 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1948 CallingConv::ID CallConv,
1950 const SmallVectorImpl<ISD::InputArg> &Ins,
1953 SmallVectorImpl<SDValue> &InVals)
1955 MachineFunction &MF = DAG.getMachineFunction();
1956 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1958 const Function* Fn = MF.getFunction();
1959 if (Fn->hasExternalLinkage() &&
1960 Subtarget->isTargetCygMing() &&
1961 Fn->getName() == "main")
1962 FuncInfo->setForceFramePointer(true);
1964 MachineFrameInfo *MFI = MF.getFrameInfo();
1965 bool Is64Bit = Subtarget->is64Bit();
1966 bool IsWindows = Subtarget->isTargetWindows();
1967 bool IsWin64 = Subtarget->isTargetWin64();
1969 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1970 "Var args not supported with calling convention fastcc, ghc or hipe");
1972 // Assign locations to all of the incoming arguments.
1973 SmallVector<CCValAssign, 16> ArgLocs;
1974 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1975 ArgLocs, *DAG.getContext());
1977 // Allocate shadow area for Win64
1979 CCInfo.AllocateStack(32, 8);
1982 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1984 unsigned LastVal = ~0U;
1986 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1987 CCValAssign &VA = ArgLocs[i];
1988 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1990 assert(VA.getValNo() != LastVal &&
1991 "Don't support value assigned to multiple locs yet");
1993 LastVal = VA.getValNo();
1995 if (VA.isRegLoc()) {
1996 EVT RegVT = VA.getLocVT();
1997 const TargetRegisterClass *RC;
1998 if (RegVT == MVT::i32)
1999 RC = &X86::GR32RegClass;
2000 else if (Is64Bit && RegVT == MVT::i64)
2001 RC = &X86::GR64RegClass;
2002 else if (RegVT == MVT::f32)
2003 RC = &X86::FR32RegClass;
2004 else if (RegVT == MVT::f64)
2005 RC = &X86::FR64RegClass;
2006 else if (RegVT.is256BitVector())
2007 RC = &X86::VR256RegClass;
2008 else if (RegVT.is128BitVector())
2009 RC = &X86::VR128RegClass;
2010 else if (RegVT == MVT::x86mmx)
2011 RC = &X86::VR64RegClass;
2013 llvm_unreachable("Unknown argument type!");
2015 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2016 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2018 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2019 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2021 if (VA.getLocInfo() == CCValAssign::SExt)
2022 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2023 DAG.getValueType(VA.getValVT()));
2024 else if (VA.getLocInfo() == CCValAssign::ZExt)
2025 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2026 DAG.getValueType(VA.getValVT()));
2027 else if (VA.getLocInfo() == CCValAssign::BCvt)
2028 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2030 if (VA.isExtInLoc()) {
2031 // Handle MMX values passed in XMM regs.
2032 if (RegVT.isVector())
2033 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2035 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2038 assert(VA.isMemLoc());
2039 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2042 // If value is passed via pointer - do a load.
2043 if (VA.getLocInfo() == CCValAssign::Indirect)
2044 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2045 MachinePointerInfo(), false, false, false, 0);
2047 InVals.push_back(ArgValue);
2050 // The x86-64 ABIs require that for returning structs by value we copy
2051 // the sret argument into %rax/%eax (depending on ABI) for the return.
2052 // Win32 requires us to put the sret argument to %eax as well.
2053 // Save the argument into a virtual register so that we can access it
2054 // from the return points.
2055 if (MF.getFunction()->hasStructRetAttr() &&
2056 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2057 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2058 unsigned Reg = FuncInfo->getSRetReturnReg();
2060 MVT PtrTy = getPointerTy();
2061 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2062 FuncInfo->setSRetReturnReg(Reg);
2064 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2065 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2068 unsigned StackSize = CCInfo.getNextStackOffset();
2069 // Align stack specially for tail calls.
2070 if (FuncIsMadeTailCallSafe(CallConv,
2071 MF.getTarget().Options.GuaranteedTailCallOpt))
2072 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2074 // If the function takes variable number of arguments, make a frame index for
2075 // the start of the first vararg value... for expansion of llvm.va_start.
2077 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2078 CallConv != CallingConv::X86_ThisCall)) {
2079 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2082 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2084 // FIXME: We should really autogenerate these arrays
2085 static const uint16_t GPR64ArgRegsWin64[] = {
2086 X86::RCX, X86::RDX, X86::R8, X86::R9
2088 static const uint16_t GPR64ArgRegs64Bit[] = {
2089 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2091 static const uint16_t XMMArgRegs64Bit[] = {
2092 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2093 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2095 const uint16_t *GPR64ArgRegs;
2096 unsigned NumXMMRegs = 0;
2099 // The XMM registers which might contain var arg parameters are shadowed
2100 // in their paired GPR. So we only need to save the GPR to their home
2102 TotalNumIntRegs = 4;
2103 GPR64ArgRegs = GPR64ArgRegsWin64;
2105 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2106 GPR64ArgRegs = GPR64ArgRegs64Bit;
2108 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2111 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2114 bool NoImplicitFloatOps = Fn->getAttributes().
2115 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2116 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2117 "SSE register cannot be used when SSE is disabled!");
2118 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2119 NoImplicitFloatOps) &&
2120 "SSE register cannot be used when SSE is disabled!");
2121 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2122 !Subtarget->hasSSE1())
2123 // Kernel mode asks for SSE to be disabled, so don't push them
2125 TotalNumXMMRegs = 0;
2128 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2129 // Get to the caller-allocated home save location. Add 8 to account
2130 // for the return address.
2131 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2132 FuncInfo->setRegSaveFrameIndex(
2133 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2134 // Fixup to set vararg frame on shadow area (4 x i64).
2136 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2138 // For X86-64, if there are vararg parameters that are passed via
2139 // registers, then we must store them to their spots on the stack so
2140 // they may be loaded by deferencing the result of va_next.
2141 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2142 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2143 FuncInfo->setRegSaveFrameIndex(
2144 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2148 // Store the integer parameter registers.
2149 SmallVector<SDValue, 8> MemOps;
2150 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2152 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2153 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2154 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2155 DAG.getIntPtrConstant(Offset));
2156 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2157 &X86::GR64RegClass);
2158 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2160 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2161 MachinePointerInfo::getFixedStack(
2162 FuncInfo->getRegSaveFrameIndex(), Offset),
2164 MemOps.push_back(Store);
2168 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2169 // Now store the XMM (fp + vector) parameter registers.
2170 SmallVector<SDValue, 11> SaveXMMOps;
2171 SaveXMMOps.push_back(Chain);
2173 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2174 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2175 SaveXMMOps.push_back(ALVal);
2177 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2178 FuncInfo->getRegSaveFrameIndex()));
2179 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2180 FuncInfo->getVarArgsFPOffset()));
2182 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2183 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2184 &X86::VR128RegClass);
2185 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2186 SaveXMMOps.push_back(Val);
2188 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2190 &SaveXMMOps[0], SaveXMMOps.size()));
2193 if (!MemOps.empty())
2194 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2195 &MemOps[0], MemOps.size());
2199 // Some CCs need callee pop.
2200 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2201 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2202 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2204 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2205 // If this is an sret function, the return should pop the hidden pointer.
2206 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2207 argsAreStructReturn(Ins) == StackStructReturn)
2208 FuncInfo->setBytesToPopOnReturn(4);
2212 // RegSaveFrameIndex is X86-64 only.
2213 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2214 if (CallConv == CallingConv::X86_FastCall ||
2215 CallConv == CallingConv::X86_ThisCall)
2216 // fastcc functions can't have varargs.
2217 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2220 FuncInfo->setArgumentStackSize(StackSize);
2226 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2227 SDValue StackPtr, SDValue Arg,
2228 SDLoc dl, SelectionDAG &DAG,
2229 const CCValAssign &VA,
2230 ISD::ArgFlagsTy Flags) const {
2231 unsigned LocMemOffset = VA.getLocMemOffset();
2232 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2233 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2234 if (Flags.isByVal())
2235 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2237 return DAG.getStore(Chain, dl, Arg, PtrOff,
2238 MachinePointerInfo::getStack(LocMemOffset),
2242 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2243 /// optimization is performed and it is required.
2245 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2246 SDValue &OutRetAddr, SDValue Chain,
2247 bool IsTailCall, bool Is64Bit,
2248 int FPDiff, SDLoc dl) const {
2249 // Adjust the Return address stack slot.
2250 EVT VT = getPointerTy();
2251 OutRetAddr = getReturnAddressFrameIndex(DAG);
2253 // Load the "old" Return address.
2254 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2255 false, false, false, 0);
2256 return SDValue(OutRetAddr.getNode(), 1);
2259 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2260 /// optimization is performed and it is required (FPDiff!=0).
2262 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2263 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2264 unsigned SlotSize, int FPDiff, SDLoc dl) {
2265 // Store the return address to the appropriate stack slot.
2266 if (!FPDiff) return Chain;
2267 // Calculate the new stack slot for the return address.
2268 int NewReturnAddrFI =
2269 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2270 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2271 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2272 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2278 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2279 SmallVectorImpl<SDValue> &InVals) const {
2280 SelectionDAG &DAG = CLI.DAG;
2282 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2283 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2284 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2285 SDValue Chain = CLI.Chain;
2286 SDValue Callee = CLI.Callee;
2287 CallingConv::ID CallConv = CLI.CallConv;
2288 bool &isTailCall = CLI.IsTailCall;
2289 bool isVarArg = CLI.IsVarArg;
2291 MachineFunction &MF = DAG.getMachineFunction();
2292 bool Is64Bit = Subtarget->is64Bit();
2293 bool IsWin64 = Subtarget->isTargetWin64();
2294 bool IsWindows = Subtarget->isTargetWindows();
2295 StructReturnType SR = callIsStructReturn(Outs);
2296 bool IsSibcall = false;
2298 if (MF.getTarget().Options.DisableTailCalls)
2302 // Check if it's really possible to do a tail call.
2303 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2304 isVarArg, SR != NotStructReturn,
2305 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2306 Outs, OutVals, Ins, DAG);
2308 // Sibcalls are automatically detected tailcalls which do not require
2310 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2317 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2318 "Var args not supported with calling convention fastcc, ghc or hipe");
2320 // Analyze operands of the call, assigning locations to each operand.
2321 SmallVector<CCValAssign, 16> ArgLocs;
2322 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2323 ArgLocs, *DAG.getContext());
2325 // Allocate shadow area for Win64
2327 CCInfo.AllocateStack(32, 8);
2330 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2332 // Get a count of how many bytes are to be pushed on the stack.
2333 unsigned NumBytes = CCInfo.getNextStackOffset();
2335 // This is a sibcall. The memory operands are available in caller's
2336 // own caller's stack.
2338 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2339 IsTailCallConvention(CallConv))
2340 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2343 if (isTailCall && !IsSibcall) {
2344 // Lower arguments at fp - stackoffset + fpdiff.
2345 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2346 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2348 FPDiff = NumBytesCallerPushed - NumBytes;
2350 // Set the delta of movement of the returnaddr stackslot.
2351 // But only set if delta is greater than previous delta.
2352 if (FPDiff < X86Info->getTCReturnAddrDelta())
2353 X86Info->setTCReturnAddrDelta(FPDiff);
2357 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2360 SDValue RetAddrFrIdx;
2361 // Load return address for tail calls.
2362 if (isTailCall && FPDiff)
2363 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2364 Is64Bit, FPDiff, dl);
2366 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2367 SmallVector<SDValue, 8> MemOpChains;
2370 // Walk the register/memloc assignments, inserting copies/loads. In the case
2371 // of tail call optimization arguments are handle later.
2372 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2373 CCValAssign &VA = ArgLocs[i];
2374 EVT RegVT = VA.getLocVT();
2375 SDValue Arg = OutVals[i];
2376 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2377 bool isByVal = Flags.isByVal();
2379 // Promote the value if needed.
2380 switch (VA.getLocInfo()) {
2381 default: llvm_unreachable("Unknown loc info!");
2382 case CCValAssign::Full: break;
2383 case CCValAssign::SExt:
2384 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2386 case CCValAssign::ZExt:
2387 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2389 case CCValAssign::AExt:
2390 if (RegVT.is128BitVector()) {
2391 // Special case: passing MMX values in XMM registers.
2392 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2393 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2394 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2396 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2398 case CCValAssign::BCvt:
2399 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2401 case CCValAssign::Indirect: {
2402 // Store the argument.
2403 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2404 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2405 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2406 MachinePointerInfo::getFixedStack(FI),
2413 if (VA.isRegLoc()) {
2414 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2415 if (isVarArg && IsWin64) {
2416 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2417 // shadow reg if callee is a varargs function.
2418 unsigned ShadowReg = 0;
2419 switch (VA.getLocReg()) {
2420 case X86::XMM0: ShadowReg = X86::RCX; break;
2421 case X86::XMM1: ShadowReg = X86::RDX; break;
2422 case X86::XMM2: ShadowReg = X86::R8; break;
2423 case X86::XMM3: ShadowReg = X86::R9; break;
2426 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2428 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2429 assert(VA.isMemLoc());
2430 if (StackPtr.getNode() == 0)
2431 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2433 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2434 dl, DAG, VA, Flags));
2438 if (!MemOpChains.empty())
2439 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2440 &MemOpChains[0], MemOpChains.size());
2442 if (Subtarget->isPICStyleGOT()) {
2443 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2446 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2447 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2449 // If we are tail calling and generating PIC/GOT style code load the
2450 // address of the callee into ECX. The value in ecx is used as target of
2451 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2452 // for tail calls on PIC/GOT architectures. Normally we would just put the
2453 // address of GOT into ebx and then call target@PLT. But for tail calls
2454 // ebx would be restored (since ebx is callee saved) before jumping to the
2457 // Note: The actual moving to ECX is done further down.
2458 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2459 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2460 !G->getGlobal()->hasProtectedVisibility())
2461 Callee = LowerGlobalAddress(Callee, DAG);
2462 else if (isa<ExternalSymbolSDNode>(Callee))
2463 Callee = LowerExternalSymbol(Callee, DAG);
2467 if (Is64Bit && isVarArg && !IsWin64) {
2468 // From AMD64 ABI document:
2469 // For calls that may call functions that use varargs or stdargs
2470 // (prototype-less calls or calls to functions containing ellipsis (...) in
2471 // the declaration) %al is used as hidden argument to specify the number
2472 // of SSE registers used. The contents of %al do not need to match exactly
2473 // the number of registers, but must be an ubound on the number of SSE
2474 // registers used and is in the range 0 - 8 inclusive.
2476 // Count the number of XMM registers allocated.
2477 static const uint16_t XMMArgRegs[] = {
2478 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2479 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2481 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2482 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2483 && "SSE registers cannot be used when SSE is disabled");
2485 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2486 DAG.getConstant(NumXMMRegs, MVT::i8)));
2489 // For tail calls lower the arguments to the 'real' stack slot.
2491 // Force all the incoming stack arguments to be loaded from the stack
2492 // before any new outgoing arguments are stored to the stack, because the
2493 // outgoing stack slots may alias the incoming argument stack slots, and
2494 // the alias isn't otherwise explicit. This is slightly more conservative
2495 // than necessary, because it means that each store effectively depends
2496 // on every argument instead of just those arguments it would clobber.
2497 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2499 SmallVector<SDValue, 8> MemOpChains2;
2502 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2503 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2504 CCValAssign &VA = ArgLocs[i];
2507 assert(VA.isMemLoc());
2508 SDValue Arg = OutVals[i];
2509 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2510 // Create frame index.
2511 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2512 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2513 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2514 FIN = DAG.getFrameIndex(FI, getPointerTy());
2516 if (Flags.isByVal()) {
2517 // Copy relative to framepointer.
2518 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2519 if (StackPtr.getNode() == 0)
2520 StackPtr = DAG.getCopyFromReg(Chain, dl,
2521 RegInfo->getStackRegister(),
2523 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2525 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2529 // Store relative to framepointer.
2530 MemOpChains2.push_back(
2531 DAG.getStore(ArgChain, dl, Arg, FIN,
2532 MachinePointerInfo::getFixedStack(FI),
2538 if (!MemOpChains2.empty())
2539 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2540 &MemOpChains2[0], MemOpChains2.size());
2542 // Store the return address to the appropriate stack slot.
2543 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2544 getPointerTy(), RegInfo->getSlotSize(),
2548 // Build a sequence of copy-to-reg nodes chained together with token chain
2549 // and flag operands which copy the outgoing args into registers.
2551 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2552 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2553 RegsToPass[i].second, InFlag);
2554 InFlag = Chain.getValue(1);
2557 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2558 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2559 // In the 64-bit large code model, we have to make all calls
2560 // through a register, since the call instruction's 32-bit
2561 // pc-relative offset may not be large enough to hold the whole
2563 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2564 // If the callee is a GlobalAddress node (quite common, every direct call
2565 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2568 // We should use extra load for direct calls to dllimported functions in
2570 const GlobalValue *GV = G->getGlobal();
2571 if (!GV->hasDLLImportLinkage()) {
2572 unsigned char OpFlags = 0;
2573 bool ExtraLoad = false;
2574 unsigned WrapperKind = ISD::DELETED_NODE;
2576 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2577 // external symbols most go through the PLT in PIC mode. If the symbol
2578 // has hidden or protected visibility, or if it is static or local, then
2579 // we don't need to use the PLT - we can directly call it.
2580 if (Subtarget->isTargetELF() &&
2581 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2582 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2583 OpFlags = X86II::MO_PLT;
2584 } else if (Subtarget->isPICStyleStubAny() &&
2585 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2586 (!Subtarget->getTargetTriple().isMacOSX() ||
2587 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2588 // PC-relative references to external symbols should go through $stub,
2589 // unless we're building with the leopard linker or later, which
2590 // automatically synthesizes these stubs.
2591 OpFlags = X86II::MO_DARWIN_STUB;
2592 } else if (Subtarget->isPICStyleRIPRel() &&
2593 isa<Function>(GV) &&
2594 cast<Function>(GV)->getAttributes().
2595 hasAttribute(AttributeSet::FunctionIndex,
2596 Attribute::NonLazyBind)) {
2597 // If the function is marked as non-lazy, generate an indirect call
2598 // which loads from the GOT directly. This avoids runtime overhead
2599 // at the cost of eager binding (and one extra byte of encoding).
2600 OpFlags = X86II::MO_GOTPCREL;
2601 WrapperKind = X86ISD::WrapperRIP;
2605 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2606 G->getOffset(), OpFlags);
2608 // Add a wrapper if needed.
2609 if (WrapperKind != ISD::DELETED_NODE)
2610 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2611 // Add extra indirection if needed.
2613 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2614 MachinePointerInfo::getGOT(),
2615 false, false, false, 0);
2617 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2618 unsigned char OpFlags = 0;
2620 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2621 // external symbols should go through the PLT.
2622 if (Subtarget->isTargetELF() &&
2623 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2624 OpFlags = X86II::MO_PLT;
2625 } else if (Subtarget->isPICStyleStubAny() &&
2626 (!Subtarget->getTargetTriple().isMacOSX() ||
2627 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2628 // PC-relative references to external symbols should go through $stub,
2629 // unless we're building with the leopard linker or later, which
2630 // automatically synthesizes these stubs.
2631 OpFlags = X86II::MO_DARWIN_STUB;
2634 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2638 // Returns a chain & a flag for retval copy to use.
2639 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2640 SmallVector<SDValue, 8> Ops;
2642 if (!IsSibcall && isTailCall) {
2643 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2644 DAG.getIntPtrConstant(0, true), InFlag, dl);
2645 InFlag = Chain.getValue(1);
2648 Ops.push_back(Chain);
2649 Ops.push_back(Callee);
2652 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2654 // Add argument registers to the end of the list so that they are known live
2656 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2657 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2658 RegsToPass[i].second.getValueType()));
2660 // Add a register mask operand representing the call-preserved registers.
2661 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2662 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2663 assert(Mask && "Missing call preserved mask for calling convention");
2664 Ops.push_back(DAG.getRegisterMask(Mask));
2666 if (InFlag.getNode())
2667 Ops.push_back(InFlag);
2671 //// If this is the first return lowered for this function, add the regs
2672 //// to the liveout set for the function.
2673 // This isn't right, although it's probably harmless on x86; liveouts
2674 // should be computed from returns not tail calls. Consider a void
2675 // function making a tail call to a function returning int.
2676 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2679 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2680 InFlag = Chain.getValue(1);
2682 // Create the CALLSEQ_END node.
2683 unsigned NumBytesForCalleeToPush;
2684 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2685 getTargetMachine().Options.GuaranteedTailCallOpt))
2686 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2687 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2688 SR == StackStructReturn)
2689 // If this is a call to a struct-return function, the callee
2690 // pops the hidden struct pointer, so we have to push it back.
2691 // This is common for Darwin/X86, Linux & Mingw32 targets.
2692 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2693 NumBytesForCalleeToPush = 4;
2695 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2697 // Returns a flag for retval copy to use.
2699 Chain = DAG.getCALLSEQ_END(Chain,
2700 DAG.getIntPtrConstant(NumBytes, true),
2701 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2704 InFlag = Chain.getValue(1);
2707 // Handle result values, copying them out of physregs into vregs that we
2709 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2710 Ins, dl, DAG, InVals);
2713 //===----------------------------------------------------------------------===//
2714 // Fast Calling Convention (tail call) implementation
2715 //===----------------------------------------------------------------------===//
2717 // Like std call, callee cleans arguments, convention except that ECX is
2718 // reserved for storing the tail called function address. Only 2 registers are
2719 // free for argument passing (inreg). Tail call optimization is performed
2721 // * tailcallopt is enabled
2722 // * caller/callee are fastcc
2723 // On X86_64 architecture with GOT-style position independent code only local
2724 // (within module) calls are supported at the moment.
2725 // To keep the stack aligned according to platform abi the function
2726 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2727 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2728 // If a tail called function callee has more arguments than the caller the
2729 // caller needs to make sure that there is room to move the RETADDR to. This is
2730 // achieved by reserving an area the size of the argument delta right after the
2731 // original REtADDR, but before the saved framepointer or the spilled registers
2732 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2744 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2745 /// for a 16 byte align requirement.
2747 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2748 SelectionDAG& DAG) const {
2749 MachineFunction &MF = DAG.getMachineFunction();
2750 const TargetMachine &TM = MF.getTarget();
2751 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2752 unsigned StackAlignment = TFI.getStackAlignment();
2753 uint64_t AlignMask = StackAlignment - 1;
2754 int64_t Offset = StackSize;
2755 unsigned SlotSize = RegInfo->getSlotSize();
2756 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2757 // Number smaller than 12 so just add the difference.
2758 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2760 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2761 Offset = ((~AlignMask) & Offset) + StackAlignment +
2762 (StackAlignment-SlotSize);
2767 /// MatchingStackOffset - Return true if the given stack call argument is
2768 /// already available in the same position (relatively) of the caller's
2769 /// incoming argument stack.
2771 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2772 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2773 const X86InstrInfo *TII) {
2774 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2776 if (Arg.getOpcode() == ISD::CopyFromReg) {
2777 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2778 if (!TargetRegisterInfo::isVirtualRegister(VR))
2780 MachineInstr *Def = MRI->getVRegDef(VR);
2783 if (!Flags.isByVal()) {
2784 if (!TII->isLoadFromStackSlot(Def, FI))
2787 unsigned Opcode = Def->getOpcode();
2788 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2789 Def->getOperand(1).isFI()) {
2790 FI = Def->getOperand(1).getIndex();
2791 Bytes = Flags.getByValSize();
2795 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2796 if (Flags.isByVal())
2797 // ByVal argument is passed in as a pointer but it's now being
2798 // dereferenced. e.g.
2799 // define @foo(%struct.X* %A) {
2800 // tail call @bar(%struct.X* byval %A)
2803 SDValue Ptr = Ld->getBasePtr();
2804 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2807 FI = FINode->getIndex();
2808 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2809 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2810 FI = FINode->getIndex();
2811 Bytes = Flags.getByValSize();
2815 assert(FI != INT_MAX);
2816 if (!MFI->isFixedObjectIndex(FI))
2818 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2821 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2822 /// for tail call optimization. Targets which want to do tail call
2823 /// optimization should implement this function.
2825 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2826 CallingConv::ID CalleeCC,
2828 bool isCalleeStructRet,
2829 bool isCallerStructRet,
2831 const SmallVectorImpl<ISD::OutputArg> &Outs,
2832 const SmallVectorImpl<SDValue> &OutVals,
2833 const SmallVectorImpl<ISD::InputArg> &Ins,
2834 SelectionDAG &DAG) const {
2835 if (!IsTailCallConvention(CalleeCC) &&
2836 CalleeCC != CallingConv::C)
2839 // If -tailcallopt is specified, make fastcc functions tail-callable.
2840 const MachineFunction &MF = DAG.getMachineFunction();
2841 const Function *CallerF = DAG.getMachineFunction().getFunction();
2843 // If the function return type is x86_fp80 and the callee return type is not,
2844 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2845 // perform a tailcall optimization here.
2846 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2849 CallingConv::ID CallerCC = CallerF->getCallingConv();
2850 bool CCMatch = CallerCC == CalleeCC;
2852 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2853 if (IsTailCallConvention(CalleeCC) && CCMatch)
2858 // Look for obvious safe cases to perform tail call optimization that do not
2859 // require ABI changes. This is what gcc calls sibcall.
2861 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2862 // emit a special epilogue.
2863 if (RegInfo->needsStackRealignment(MF))
2866 // Also avoid sibcall optimization if either caller or callee uses struct
2867 // return semantics.
2868 if (isCalleeStructRet || isCallerStructRet)
2871 // An stdcall caller is expected to clean up its arguments; the callee
2872 // isn't going to do that.
2873 if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2876 // Do not sibcall optimize vararg calls unless all arguments are passed via
2878 if (isVarArg && !Outs.empty()) {
2880 // Optimizing for varargs on Win64 is unlikely to be safe without
2881 // additional testing.
2882 if (Subtarget->isTargetWin64())
2885 SmallVector<CCValAssign, 16> ArgLocs;
2886 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2887 getTargetMachine(), ArgLocs, *DAG.getContext());
2889 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2890 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2891 if (!ArgLocs[i].isRegLoc())
2895 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2896 // stack. Therefore, if it's not used by the call it is not safe to optimize
2897 // this into a sibcall.
2898 bool Unused = false;
2899 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2906 SmallVector<CCValAssign, 16> RVLocs;
2907 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2908 getTargetMachine(), RVLocs, *DAG.getContext());
2909 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2910 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2911 CCValAssign &VA = RVLocs[i];
2912 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2917 // If the calling conventions do not match, then we'd better make sure the
2918 // results are returned in the same way as what the caller expects.
2920 SmallVector<CCValAssign, 16> RVLocs1;
2921 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2922 getTargetMachine(), RVLocs1, *DAG.getContext());
2923 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2925 SmallVector<CCValAssign, 16> RVLocs2;
2926 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2927 getTargetMachine(), RVLocs2, *DAG.getContext());
2928 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2930 if (RVLocs1.size() != RVLocs2.size())
2932 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2933 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2935 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2937 if (RVLocs1[i].isRegLoc()) {
2938 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2941 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2947 // If the callee takes no arguments then go on to check the results of the
2949 if (!Outs.empty()) {
2950 // Check if stack adjustment is needed. For now, do not do this if any
2951 // argument is passed on the stack.
2952 SmallVector<CCValAssign, 16> ArgLocs;
2953 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2954 getTargetMachine(), ArgLocs, *DAG.getContext());
2956 // Allocate shadow area for Win64
2957 if (Subtarget->isTargetWin64()) {
2958 CCInfo.AllocateStack(32, 8);
2961 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2962 if (CCInfo.getNextStackOffset()) {
2963 MachineFunction &MF = DAG.getMachineFunction();
2964 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2967 // Check if the arguments are already laid out in the right way as
2968 // the caller's fixed stack objects.
2969 MachineFrameInfo *MFI = MF.getFrameInfo();
2970 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2971 const X86InstrInfo *TII =
2972 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2973 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2974 CCValAssign &VA = ArgLocs[i];
2975 SDValue Arg = OutVals[i];
2976 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2977 if (VA.getLocInfo() == CCValAssign::Indirect)
2979 if (!VA.isRegLoc()) {
2980 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2987 // If the tailcall address may be in a register, then make sure it's
2988 // possible to register allocate for it. In 32-bit, the call address can
2989 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2990 // callee-saved registers are restored. These happen to be the same
2991 // registers used to pass 'inreg' arguments so watch out for those.
2992 if (!Subtarget->is64Bit() &&
2993 ((!isa<GlobalAddressSDNode>(Callee) &&
2994 !isa<ExternalSymbolSDNode>(Callee)) ||
2995 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2996 unsigned NumInRegs = 0;
2997 // In PIC we need an extra register to formulate the address computation
2999 unsigned MaxInRegs =
3000 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3002 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3003 CCValAssign &VA = ArgLocs[i];
3006 unsigned Reg = VA.getLocReg();
3009 case X86::EAX: case X86::EDX: case X86::ECX:
3010 if (++NumInRegs == MaxInRegs)
3022 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3023 const TargetLibraryInfo *libInfo) const {
3024 return X86::createFastISel(funcInfo, libInfo);
3027 //===----------------------------------------------------------------------===//
3028 // Other Lowering Hooks
3029 //===----------------------------------------------------------------------===//
3031 static bool MayFoldLoad(SDValue Op) {
3032 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3035 static bool MayFoldIntoStore(SDValue Op) {
3036 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3039 static bool isTargetShuffle(unsigned Opcode) {
3041 default: return false;
3042 case X86ISD::PSHUFD:
3043 case X86ISD::PSHUFHW:
3044 case X86ISD::PSHUFLW:
3046 case X86ISD::PALIGNR:
3047 case X86ISD::MOVLHPS:
3048 case X86ISD::MOVLHPD:
3049 case X86ISD::MOVHLPS:
3050 case X86ISD::MOVLPS:
3051 case X86ISD::MOVLPD:
3052 case X86ISD::MOVSHDUP:
3053 case X86ISD::MOVSLDUP:
3054 case X86ISD::MOVDDUP:
3057 case X86ISD::UNPCKL:
3058 case X86ISD::UNPCKH:
3059 case X86ISD::VPERMILP:
3060 case X86ISD::VPERM2X128:
3061 case X86ISD::VPERMI:
3066 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3067 SDValue V1, SelectionDAG &DAG) {
3069 default: llvm_unreachable("Unknown x86 shuffle node");
3070 case X86ISD::MOVSHDUP:
3071 case X86ISD::MOVSLDUP:
3072 case X86ISD::MOVDDUP:
3073 return DAG.getNode(Opc, dl, VT, V1);
3077 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3078 SDValue V1, unsigned TargetMask,
3079 SelectionDAG &DAG) {
3081 default: llvm_unreachable("Unknown x86 shuffle node");
3082 case X86ISD::PSHUFD:
3083 case X86ISD::PSHUFHW:
3084 case X86ISD::PSHUFLW:
3085 case X86ISD::VPERMILP:
3086 case X86ISD::VPERMI:
3087 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3091 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3092 SDValue V1, SDValue V2, unsigned TargetMask,
3093 SelectionDAG &DAG) {
3095 default: llvm_unreachable("Unknown x86 shuffle node");
3096 case X86ISD::PALIGNR:
3098 case X86ISD::VPERM2X128:
3099 return DAG.getNode(Opc, dl, VT, V1, V2,
3100 DAG.getConstant(TargetMask, MVT::i8));
3104 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3105 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3107 default: llvm_unreachable("Unknown x86 shuffle node");
3108 case X86ISD::MOVLHPS:
3109 case X86ISD::MOVLHPD:
3110 case X86ISD::MOVHLPS:
3111 case X86ISD::MOVLPS:
3112 case X86ISD::MOVLPD:
3115 case X86ISD::UNPCKL:
3116 case X86ISD::UNPCKH:
3117 return DAG.getNode(Opc, dl, VT, V1, V2);
3121 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3122 MachineFunction &MF = DAG.getMachineFunction();
3123 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3124 int ReturnAddrIndex = FuncInfo->getRAIndex();
3126 if (ReturnAddrIndex == 0) {
3127 // Set up a frame object for the return address.
3128 unsigned SlotSize = RegInfo->getSlotSize();
3129 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3131 FuncInfo->setRAIndex(ReturnAddrIndex);
3134 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3137 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3138 bool hasSymbolicDisplacement) {
3139 // Offset should fit into 32 bit immediate field.
3140 if (!isInt<32>(Offset))
3143 // If we don't have a symbolic displacement - we don't have any extra
3145 if (!hasSymbolicDisplacement)
3148 // FIXME: Some tweaks might be needed for medium code model.
3149 if (M != CodeModel::Small && M != CodeModel::Kernel)
3152 // For small code model we assume that latest object is 16MB before end of 31
3153 // bits boundary. We may also accept pretty large negative constants knowing
3154 // that all objects are in the positive half of address space.
3155 if (M == CodeModel::Small && Offset < 16*1024*1024)
3158 // For kernel code model we know that all object resist in the negative half
3159 // of 32bits address space. We may not accept negative offsets, since they may
3160 // be just off and we may accept pretty large positive ones.
3161 if (M == CodeModel::Kernel && Offset > 0)
3167 /// isCalleePop - Determines whether the callee is required to pop its
3168 /// own arguments. Callee pop is necessary to support tail calls.
3169 bool X86::isCalleePop(CallingConv::ID CallingConv,
3170 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3174 switch (CallingConv) {
3177 case CallingConv::X86_StdCall:
3179 case CallingConv::X86_FastCall:
3181 case CallingConv::X86_ThisCall:
3183 case CallingConv::Fast:
3185 case CallingConv::GHC:
3187 case CallingConv::HiPE:
3192 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3193 /// specific condition code, returning the condition code and the LHS/RHS of the
3194 /// comparison to make.
3195 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3196 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3198 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3199 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3200 // X > -1 -> X == 0, jump !sign.
3201 RHS = DAG.getConstant(0, RHS.getValueType());
3202 return X86::COND_NS;
3204 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3205 // X < 0 -> X == 0, jump on sign.
3208 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3210 RHS = DAG.getConstant(0, RHS.getValueType());
3211 return X86::COND_LE;
3215 switch (SetCCOpcode) {
3216 default: llvm_unreachable("Invalid integer condition!");
3217 case ISD::SETEQ: return X86::COND_E;
3218 case ISD::SETGT: return X86::COND_G;
3219 case ISD::SETGE: return X86::COND_GE;
3220 case ISD::SETLT: return X86::COND_L;
3221 case ISD::SETLE: return X86::COND_LE;
3222 case ISD::SETNE: return X86::COND_NE;
3223 case ISD::SETULT: return X86::COND_B;
3224 case ISD::SETUGT: return X86::COND_A;
3225 case ISD::SETULE: return X86::COND_BE;
3226 case ISD::SETUGE: return X86::COND_AE;
3230 // First determine if it is required or is profitable to flip the operands.
3232 // If LHS is a foldable load, but RHS is not, flip the condition.
3233 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3234 !ISD::isNON_EXTLoad(RHS.getNode())) {
3235 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3236 std::swap(LHS, RHS);
3239 switch (SetCCOpcode) {
3245 std::swap(LHS, RHS);
3249 // On a floating point condition, the flags are set as follows:
3251 // 0 | 0 | 0 | X > Y
3252 // 0 | 0 | 1 | X < Y
3253 // 1 | 0 | 0 | X == Y
3254 // 1 | 1 | 1 | unordered
3255 switch (SetCCOpcode) {
3256 default: llvm_unreachable("Condcode should be pre-legalized away");
3258 case ISD::SETEQ: return X86::COND_E;
3259 case ISD::SETOLT: // flipped
3261 case ISD::SETGT: return X86::COND_A;
3262 case ISD::SETOLE: // flipped
3264 case ISD::SETGE: return X86::COND_AE;
3265 case ISD::SETUGT: // flipped
3267 case ISD::SETLT: return X86::COND_B;
3268 case ISD::SETUGE: // flipped
3270 case ISD::SETLE: return X86::COND_BE;
3272 case ISD::SETNE: return X86::COND_NE;
3273 case ISD::SETUO: return X86::COND_P;
3274 case ISD::SETO: return X86::COND_NP;
3276 case ISD::SETUNE: return X86::COND_INVALID;
3280 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3281 /// code. Current x86 isa includes the following FP cmov instructions:
3282 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3283 static bool hasFPCMov(unsigned X86CC) {
3299 /// isFPImmLegal - Returns true if the target can instruction select the
3300 /// specified FP immediate natively. If false, the legalizer will
3301 /// materialize the FP immediate as a load from a constant pool.
3302 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3303 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3304 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3310 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3311 /// the specified range (L, H].
3312 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3313 return (Val < 0) || (Val >= Low && Val < Hi);
3316 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3317 /// specified value.
3318 static bool isUndefOrEqual(int Val, int CmpVal) {
3319 return (Val < 0 || Val == CmpVal);
3322 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3323 /// from position Pos and ending in Pos+Size, falls within the specified
3324 /// sequential range (L, L+Pos]. or is undef.
3325 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3326 unsigned Pos, unsigned Size, int Low) {
3327 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3328 if (!isUndefOrEqual(Mask[i], Low))
3333 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3334 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3335 /// the second operand.
3336 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3337 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3338 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3339 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3340 return (Mask[0] < 2 && Mask[1] < 2);
3344 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3345 /// is suitable for input to PSHUFHW.
3346 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3347 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3350 // Lower quadword copied in order or undef.
3351 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3354 // Upper quadword shuffled.
3355 for (unsigned i = 4; i != 8; ++i)
3356 if (!isUndefOrInRange(Mask[i], 4, 8))
3359 if (VT == MVT::v16i16) {
3360 // Lower quadword copied in order or undef.
3361 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3364 // Upper quadword shuffled.
3365 for (unsigned i = 12; i != 16; ++i)
3366 if (!isUndefOrInRange(Mask[i], 12, 16))
3373 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3374 /// is suitable for input to PSHUFLW.
3375 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3376 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3379 // Upper quadword copied in order.
3380 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3383 // Lower quadword shuffled.
3384 for (unsigned i = 0; i != 4; ++i)
3385 if (!isUndefOrInRange(Mask[i], 0, 4))
3388 if (VT == MVT::v16i16) {
3389 // Upper quadword copied in order.
3390 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3393 // Lower quadword shuffled.
3394 for (unsigned i = 8; i != 12; ++i)
3395 if (!isUndefOrInRange(Mask[i], 8, 12))
3402 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3403 /// is suitable for input to PALIGNR.
3404 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3405 const X86Subtarget *Subtarget) {
3406 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3407 (VT.is256BitVector() && !Subtarget->hasInt256()))
3410 unsigned NumElts = VT.getVectorNumElements();
3411 unsigned NumLanes = VT.getSizeInBits()/128;
3412 unsigned NumLaneElts = NumElts/NumLanes;
3414 // Do not handle 64-bit element shuffles with palignr.
3415 if (NumLaneElts == 2)
3418 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3420 for (i = 0; i != NumLaneElts; ++i) {
3425 // Lane is all undef, go to next lane
3426 if (i == NumLaneElts)
3429 int Start = Mask[i+l];
3431 // Make sure its in this lane in one of the sources
3432 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3433 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3436 // If not lane 0, then we must match lane 0
3437 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3440 // Correct second source to be contiguous with first source
3441 if (Start >= (int)NumElts)
3442 Start -= NumElts - NumLaneElts;
3444 // Make sure we're shifting in the right direction.
3445 if (Start <= (int)(i+l))
3450 // Check the rest of the elements to see if they are consecutive.
3451 for (++i; i != NumLaneElts; ++i) {
3452 int Idx = Mask[i+l];
3454 // Make sure its in this lane
3455 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3456 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3459 // If not lane 0, then we must match lane 0
3460 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3463 if (Idx >= (int)NumElts)
3464 Idx -= NumElts - NumLaneElts;
3466 if (!isUndefOrEqual(Idx, Start+i))
3475 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3476 /// the two vector operands have swapped position.
3477 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3478 unsigned NumElems) {
3479 for (unsigned i = 0; i != NumElems; ++i) {
3483 else if (idx < (int)NumElems)
3484 Mask[i] = idx + NumElems;
3486 Mask[i] = idx - NumElems;
3490 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3491 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3492 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3493 /// reverse of what x86 shuffles want.
3494 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3495 bool Commuted = false) {
3496 if (!HasFp256 && VT.is256BitVector())
3499 unsigned NumElems = VT.getVectorNumElements();
3500 unsigned NumLanes = VT.getSizeInBits()/128;
3501 unsigned NumLaneElems = NumElems/NumLanes;
3503 if (NumLaneElems != 2 && NumLaneElems != 4)
3506 // VSHUFPSY divides the resulting vector into 4 chunks.
3507 // The sources are also splitted into 4 chunks, and each destination
3508 // chunk must come from a different source chunk.
3510 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3511 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3513 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3514 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3516 // VSHUFPDY divides the resulting vector into 4 chunks.
3517 // The sources are also splitted into 4 chunks, and each destination
3518 // chunk must come from a different source chunk.
3520 // SRC1 => X3 X2 X1 X0
3521 // SRC2 => Y3 Y2 Y1 Y0
3523 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3525 unsigned HalfLaneElems = NumLaneElems/2;
3526 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3527 for (unsigned i = 0; i != NumLaneElems; ++i) {
3528 int Idx = Mask[i+l];
3529 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3530 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3532 // For VSHUFPSY, the mask of the second half must be the same as the
3533 // first but with the appropriate offsets. This works in the same way as
3534 // VPERMILPS works with masks.
3535 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3537 if (!isUndefOrEqual(Idx, Mask[i]+l))
3545 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3546 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3547 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3548 if (!VT.is128BitVector())
3551 unsigned NumElems = VT.getVectorNumElements();
3556 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3557 return isUndefOrEqual(Mask[0], 6) &&
3558 isUndefOrEqual(Mask[1], 7) &&
3559 isUndefOrEqual(Mask[2], 2) &&
3560 isUndefOrEqual(Mask[3], 3);
3563 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3564 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3566 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3567 if (!VT.is128BitVector())
3570 unsigned NumElems = VT.getVectorNumElements();
3575 return isUndefOrEqual(Mask[0], 2) &&
3576 isUndefOrEqual(Mask[1], 3) &&
3577 isUndefOrEqual(Mask[2], 2) &&
3578 isUndefOrEqual(Mask[3], 3);
3581 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3582 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3583 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3584 if (!VT.is128BitVector())
3587 unsigned NumElems = VT.getVectorNumElements();
3589 if (NumElems != 2 && NumElems != 4)
3592 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3593 if (!isUndefOrEqual(Mask[i], i + NumElems))
3596 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3597 if (!isUndefOrEqual(Mask[i], i))
3603 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3604 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3605 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3606 if (!VT.is128BitVector())
3609 unsigned NumElems = VT.getVectorNumElements();
3611 if (NumElems != 2 && NumElems != 4)
3614 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3615 if (!isUndefOrEqual(Mask[i], i))
3618 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3619 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3626 // Some special combinations that can be optimized.
3629 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3630 SelectionDAG &DAG) {
3631 MVT VT = SVOp->getValueType(0).getSimpleVT();
3634 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3637 ArrayRef<int> Mask = SVOp->getMask();
3639 // These are the special masks that may be optimized.
3640 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3641 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3642 bool MatchEvenMask = true;
3643 bool MatchOddMask = true;
3644 for (int i=0; i<8; ++i) {
3645 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3646 MatchEvenMask = false;
3647 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3648 MatchOddMask = false;
3651 if (!MatchEvenMask && !MatchOddMask)
3654 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3656 SDValue Op0 = SVOp->getOperand(0);
3657 SDValue Op1 = SVOp->getOperand(1);
3659 if (MatchEvenMask) {
3660 // Shift the second operand right to 32 bits.
3661 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3662 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3664 // Shift the first operand left to 32 bits.
3665 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3666 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3668 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3669 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3672 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3673 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3674 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3675 bool HasInt256, bool V2IsSplat = false) {
3676 unsigned NumElts = VT.getVectorNumElements();
3678 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3679 "Unsupported vector type for unpckh");
3681 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3682 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3685 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3686 // independently on 128-bit lanes.
3687 unsigned NumLanes = VT.getSizeInBits()/128;
3688 unsigned NumLaneElts = NumElts/NumLanes;
3690 for (unsigned l = 0; l != NumLanes; ++l) {
3691 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3692 i != (l+1)*NumLaneElts;
3695 int BitI1 = Mask[i+1];
3696 if (!isUndefOrEqual(BitI, j))
3699 if (!isUndefOrEqual(BitI1, NumElts))
3702 if (!isUndefOrEqual(BitI1, j + NumElts))
3711 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3712 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3713 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3714 bool HasInt256, bool V2IsSplat = false) {
3715 unsigned NumElts = VT.getVectorNumElements();
3717 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3718 "Unsupported vector type for unpckh");
3720 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3721 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3724 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3725 // independently on 128-bit lanes.
3726 unsigned NumLanes = VT.getSizeInBits()/128;
3727 unsigned NumLaneElts = NumElts/NumLanes;
3729 for (unsigned l = 0; l != NumLanes; ++l) {
3730 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3731 i != (l+1)*NumLaneElts; i += 2, ++j) {
3733 int BitI1 = Mask[i+1];
3734 if (!isUndefOrEqual(BitI, j))
3737 if (isUndefOrEqual(BitI1, NumElts))
3740 if (!isUndefOrEqual(BitI1, j+NumElts))
3748 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3749 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3751 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3752 unsigned NumElts = VT.getVectorNumElements();
3753 bool Is256BitVec = VT.is256BitVector();
3755 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3756 "Unsupported vector type for unpckh");
3758 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3759 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3762 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3763 // FIXME: Need a better way to get rid of this, there's no latency difference
3764 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3765 // the former later. We should also remove the "_undef" special mask.
3766 if (NumElts == 4 && Is256BitVec)
3769 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3770 // independently on 128-bit lanes.
3771 unsigned NumLanes = VT.getSizeInBits()/128;
3772 unsigned NumLaneElts = NumElts/NumLanes;
3774 for (unsigned l = 0; l != NumLanes; ++l) {
3775 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3776 i != (l+1)*NumLaneElts;
3779 int BitI1 = Mask[i+1];
3781 if (!isUndefOrEqual(BitI, j))
3783 if (!isUndefOrEqual(BitI1, j))
3791 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3792 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3794 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3795 unsigned NumElts = VT.getVectorNumElements();
3797 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3798 "Unsupported vector type for unpckh");
3800 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3801 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3804 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3805 // independently on 128-bit lanes.
3806 unsigned NumLanes = VT.getSizeInBits()/128;
3807 unsigned NumLaneElts = NumElts/NumLanes;
3809 for (unsigned l = 0; l != NumLanes; ++l) {
3810 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3811 i != (l+1)*NumLaneElts; i += 2, ++j) {
3813 int BitI1 = Mask[i+1];
3814 if (!isUndefOrEqual(BitI, j))
3816 if (!isUndefOrEqual(BitI1, j))
3823 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3824 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3825 /// MOVSD, and MOVD, i.e. setting the lowest element.
3826 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3827 if (VT.getVectorElementType().getSizeInBits() < 32)
3829 if (!VT.is128BitVector())
3832 unsigned NumElts = VT.getVectorNumElements();
3834 if (!isUndefOrEqual(Mask[0], NumElts))
3837 for (unsigned i = 1; i != NumElts; ++i)
3838 if (!isUndefOrEqual(Mask[i], i))
3844 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3845 /// as permutations between 128-bit chunks or halves. As an example: this
3847 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3848 /// The first half comes from the second half of V1 and the second half from the
3849 /// the second half of V2.
3850 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3851 if (!HasFp256 || !VT.is256BitVector())
3854 // The shuffle result is divided into half A and half B. In total the two
3855 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3856 // B must come from C, D, E or F.
3857 unsigned HalfSize = VT.getVectorNumElements()/2;
3858 bool MatchA = false, MatchB = false;
3860 // Check if A comes from one of C, D, E, F.
3861 for (unsigned Half = 0; Half != 4; ++Half) {
3862 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3868 // Check if B comes from one of C, D, E, F.
3869 for (unsigned Half = 0; Half != 4; ++Half) {
3870 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3876 return MatchA && MatchB;
3879 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3880 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3881 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3882 MVT VT = SVOp->getValueType(0).getSimpleVT();
3884 unsigned HalfSize = VT.getVectorNumElements()/2;
3886 unsigned FstHalf = 0, SndHalf = 0;
3887 for (unsigned i = 0; i < HalfSize; ++i) {
3888 if (SVOp->getMaskElt(i) > 0) {
3889 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3893 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3894 if (SVOp->getMaskElt(i) > 0) {
3895 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3900 return (FstHalf | (SndHalf << 4));
3903 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3905 /// Note that VPERMIL mask matching is different depending whether theunderlying
3906 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3907 /// to the same elements of the low, but to the higher half of the source.
3908 /// In VPERMILPD the two lanes could be shuffled independently of each other
3909 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3910 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3914 unsigned NumElts = VT.getVectorNumElements();
3915 // Only match 256-bit with 32/64-bit types
3916 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3919 unsigned NumLanes = VT.getSizeInBits()/128;
3920 unsigned LaneSize = NumElts/NumLanes;
3921 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3922 for (unsigned i = 0; i != LaneSize; ++i) {
3923 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3925 if (NumElts != 8 || l == 0)
3927 // VPERMILPS handling
3930 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3938 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3939 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3940 /// element of vector 2 and the other elements to come from vector 1 in order.
3941 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3942 bool V2IsSplat = false, bool V2IsUndef = false) {
3943 if (!VT.is128BitVector())
3946 unsigned NumOps = VT.getVectorNumElements();
3947 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3950 if (!isUndefOrEqual(Mask[0], 0))
3953 for (unsigned i = 1; i != NumOps; ++i)
3954 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3955 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3956 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3962 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3963 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3964 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3965 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3966 const X86Subtarget *Subtarget) {
3967 if (!Subtarget->hasSSE3())
3970 unsigned NumElems = VT.getVectorNumElements();
3972 if ((VT.is128BitVector() && NumElems != 4) ||
3973 (VT.is256BitVector() && NumElems != 8))
3976 // "i+1" is the value the indexed mask element must have
3977 for (unsigned i = 0; i != NumElems; i += 2)
3978 if (!isUndefOrEqual(Mask[i], i+1) ||
3979 !isUndefOrEqual(Mask[i+1], i+1))
3985 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3986 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3987 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3988 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3989 const X86Subtarget *Subtarget) {
3990 if (!Subtarget->hasSSE3())
3993 unsigned NumElems = VT.getVectorNumElements();
3995 if ((VT.is128BitVector() && NumElems != 4) ||
3996 (VT.is256BitVector() && NumElems != 8))
3999 // "i" is the value the indexed mask element must have
4000 for (unsigned i = 0; i != NumElems; i += 2)
4001 if (!isUndefOrEqual(Mask[i], i) ||
4002 !isUndefOrEqual(Mask[i+1], i))
4008 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4009 /// specifies a shuffle of elements that is suitable for input to 256-bit
4010 /// version of MOVDDUP.
4011 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4012 if (!HasFp256 || !VT.is256BitVector())
4015 unsigned NumElts = VT.getVectorNumElements();
4019 for (unsigned i = 0; i != NumElts/2; ++i)
4020 if (!isUndefOrEqual(Mask[i], 0))
4022 for (unsigned i = NumElts/2; i != NumElts; ++i)
4023 if (!isUndefOrEqual(Mask[i], NumElts/2))
4028 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4029 /// specifies a shuffle of elements that is suitable for input to 128-bit
4030 /// version of MOVDDUP.
4031 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4032 if (!VT.is128BitVector())
4035 unsigned e = VT.getVectorNumElements() / 2;
4036 for (unsigned i = 0; i != e; ++i)
4037 if (!isUndefOrEqual(Mask[i], i))
4039 for (unsigned i = 0; i != e; ++i)
4040 if (!isUndefOrEqual(Mask[e+i], i))
4045 /// isVEXTRACTF128Index - Return true if the specified
4046 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4047 /// suitable for input to VEXTRACTF128.
4048 bool X86::isVEXTRACTF128Index(SDNode *N) {
4049 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4052 // The index should be aligned on a 128-bit boundary.
4054 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4056 MVT VT = N->getValueType(0).getSimpleVT();
4057 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4058 bool Result = (Index * ElSize) % 128 == 0;
4063 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4064 /// operand specifies a subvector insert that is suitable for input to
4066 bool X86::isVINSERTF128Index(SDNode *N) {
4067 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4070 // The index should be aligned on a 128-bit boundary.
4072 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4074 MVT VT = N->getValueType(0).getSimpleVT();
4075 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4076 bool Result = (Index * ElSize) % 128 == 0;
4081 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4083 /// Handles 128-bit and 256-bit.
4084 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4085 MVT VT = N->getValueType(0).getSimpleVT();
4087 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4088 "Unsupported vector type for PSHUF/SHUFP");
4090 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4091 // independently on 128-bit lanes.
4092 unsigned NumElts = VT.getVectorNumElements();
4093 unsigned NumLanes = VT.getSizeInBits()/128;
4094 unsigned NumLaneElts = NumElts/NumLanes;
4096 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4097 "Only supports 2 or 4 elements per lane");
4099 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4101 for (unsigned i = 0; i != NumElts; ++i) {
4102 int Elt = N->getMaskElt(i);
4103 if (Elt < 0) continue;
4104 Elt &= NumLaneElts - 1;
4105 unsigned ShAmt = (i << Shift) % 8;
4106 Mask |= Elt << ShAmt;
4112 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4113 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4114 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4115 MVT VT = N->getValueType(0).getSimpleVT();
4117 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4118 "Unsupported vector type for PSHUFHW");
4120 unsigned NumElts = VT.getVectorNumElements();
4123 for (unsigned l = 0; l != NumElts; l += 8) {
4124 // 8 nodes per lane, but we only care about the last 4.
4125 for (unsigned i = 0; i < 4; ++i) {
4126 int Elt = N->getMaskElt(l+i+4);
4127 if (Elt < 0) continue;
4128 Elt &= 0x3; // only 2-bits.
4129 Mask |= Elt << (i * 2);
4136 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4137 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4138 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4139 MVT VT = N->getValueType(0).getSimpleVT();
4141 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4142 "Unsupported vector type for PSHUFHW");
4144 unsigned NumElts = VT.getVectorNumElements();
4147 for (unsigned l = 0; l != NumElts; l += 8) {
4148 // 8 nodes per lane, but we only care about the first 4.
4149 for (unsigned i = 0; i < 4; ++i) {
4150 int Elt = N->getMaskElt(l+i);
4151 if (Elt < 0) continue;
4152 Elt &= 0x3; // only 2-bits
4153 Mask |= Elt << (i * 2);
4160 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4161 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4162 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4163 MVT VT = SVOp->getValueType(0).getSimpleVT();
4164 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4166 unsigned NumElts = VT.getVectorNumElements();
4167 unsigned NumLanes = VT.getSizeInBits()/128;
4168 unsigned NumLaneElts = NumElts/NumLanes;
4172 for (i = 0; i != NumElts; ++i) {
4173 Val = SVOp->getMaskElt(i);
4177 if (Val >= (int)NumElts)
4178 Val -= NumElts - NumLaneElts;
4180 assert(Val - i > 0 && "PALIGNR imm should be positive");
4181 return (Val - i) * EltSize;
4184 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4185 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4187 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4188 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4189 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4192 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4194 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4195 MVT ElVT = VecVT.getVectorElementType();
4197 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4198 return Index / NumElemsPerChunk;
4201 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4202 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4204 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4205 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4206 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4209 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4211 MVT VecVT = N->getValueType(0).getSimpleVT();
4212 MVT ElVT = VecVT.getVectorElementType();
4214 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4215 return Index / NumElemsPerChunk;
4218 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4219 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4220 /// Handles 256-bit.
4221 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4222 MVT VT = N->getValueType(0).getSimpleVT();
4224 unsigned NumElts = VT.getVectorNumElements();
4226 assert((VT.is256BitVector() && NumElts == 4) &&
4227 "Unsupported vector type for VPERMQ/VPERMPD");
4230 for (unsigned i = 0; i != NumElts; ++i) {
4231 int Elt = N->getMaskElt(i);
4234 Mask |= Elt << (i*2);
4239 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4241 bool X86::isZeroNode(SDValue Elt) {
4242 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4243 return CN->isNullValue();
4244 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4245 return CFP->getValueAPF().isPosZero();
4249 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4250 /// their permute mask.
4251 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4252 SelectionDAG &DAG) {
4253 MVT VT = SVOp->getValueType(0).getSimpleVT();
4254 unsigned NumElems = VT.getVectorNumElements();
4255 SmallVector<int, 8> MaskVec;
4257 for (unsigned i = 0; i != NumElems; ++i) {
4258 int Idx = SVOp->getMaskElt(i);
4260 if (Idx < (int)NumElems)
4265 MaskVec.push_back(Idx);
4267 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4268 SVOp->getOperand(0), &MaskVec[0]);
4271 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4272 /// match movhlps. The lower half elements should come from upper half of
4273 /// V1 (and in order), and the upper half elements should come from the upper
4274 /// half of V2 (and in order).
4275 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4276 if (!VT.is128BitVector())
4278 if (VT.getVectorNumElements() != 4)
4280 for (unsigned i = 0, e = 2; i != e; ++i)
4281 if (!isUndefOrEqual(Mask[i], i+2))
4283 for (unsigned i = 2; i != 4; ++i)
4284 if (!isUndefOrEqual(Mask[i], i+4))
4289 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4290 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4292 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4293 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4295 N = N->getOperand(0).getNode();
4296 if (!ISD::isNON_EXTLoad(N))
4299 *LD = cast<LoadSDNode>(N);
4303 // Test whether the given value is a vector value which will be legalized
4305 static bool WillBeConstantPoolLoad(SDNode *N) {
4306 if (N->getOpcode() != ISD::BUILD_VECTOR)
4309 // Check for any non-constant elements.
4310 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4311 switch (N->getOperand(i).getNode()->getOpcode()) {
4313 case ISD::ConstantFP:
4320 // Vectors of all-zeros and all-ones are materialized with special
4321 // instructions rather than being loaded.
4322 return !ISD::isBuildVectorAllZeros(N) &&
4323 !ISD::isBuildVectorAllOnes(N);
4326 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4327 /// match movlp{s|d}. The lower half elements should come from lower half of
4328 /// V1 (and in order), and the upper half elements should come from the upper
4329 /// half of V2 (and in order). And since V1 will become the source of the
4330 /// MOVLP, it must be either a vector load or a scalar load to vector.
4331 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4332 ArrayRef<int> Mask, EVT VT) {
4333 if (!VT.is128BitVector())
4336 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4338 // Is V2 is a vector load, don't do this transformation. We will try to use
4339 // load folding shufps op.
4340 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4343 unsigned NumElems = VT.getVectorNumElements();
4345 if (NumElems != 2 && NumElems != 4)
4347 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4348 if (!isUndefOrEqual(Mask[i], i))
4350 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4351 if (!isUndefOrEqual(Mask[i], i+NumElems))
4356 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4358 static bool isSplatVector(SDNode *N) {
4359 if (N->getOpcode() != ISD::BUILD_VECTOR)
4362 SDValue SplatValue = N->getOperand(0);
4363 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4364 if (N->getOperand(i) != SplatValue)
4369 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4370 /// to an zero vector.
4371 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4372 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4373 SDValue V1 = N->getOperand(0);
4374 SDValue V2 = N->getOperand(1);
4375 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4376 for (unsigned i = 0; i != NumElems; ++i) {
4377 int Idx = N->getMaskElt(i);
4378 if (Idx >= (int)NumElems) {
4379 unsigned Opc = V2.getOpcode();
4380 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4382 if (Opc != ISD::BUILD_VECTOR ||
4383 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4385 } else if (Idx >= 0) {
4386 unsigned Opc = V1.getOpcode();
4387 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4389 if (Opc != ISD::BUILD_VECTOR ||
4390 !X86::isZeroNode(V1.getOperand(Idx)))
4397 /// getZeroVector - Returns a vector of specified type with all zero elements.
4399 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4400 SelectionDAG &DAG, SDLoc dl) {
4401 assert(VT.isVector() && "Expected a vector type");
4403 // Always build SSE zero vectors as <4 x i32> bitcasted
4404 // to their dest type. This ensures they get CSE'd.
4406 if (VT.is128BitVector()) { // SSE
4407 if (Subtarget->hasSSE2()) { // SSE2
4408 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4409 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4411 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4412 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4414 } else if (VT.is256BitVector()) { // AVX
4415 if (Subtarget->hasInt256()) { // AVX2
4416 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4417 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4418 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4419 array_lengthof(Ops));
4421 // 256-bit logic and arithmetic instructions in AVX are all
4422 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4423 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4424 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4425 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4426 array_lengthof(Ops));
4429 llvm_unreachable("Unexpected vector type");
4431 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4434 /// getOnesVector - Returns a vector of specified type with all bits set.
4435 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4436 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4437 /// Then bitcast to their original type, ensuring they get CSE'd.
4438 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4440 assert(VT.isVector() && "Expected a vector type");
4442 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4444 if (VT.is256BitVector()) {
4445 if (HasInt256) { // AVX2
4446 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4447 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4448 array_lengthof(Ops));
4450 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4451 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4453 } else if (VT.is128BitVector()) {
4454 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4456 llvm_unreachable("Unexpected vector type");
4458 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4461 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4462 /// that point to V2 points to its first element.
4463 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4464 for (unsigned i = 0; i != NumElems; ++i) {
4465 if (Mask[i] > (int)NumElems) {
4471 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4472 /// operation of specified width.
4473 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4475 unsigned NumElems = VT.getVectorNumElements();
4476 SmallVector<int, 8> Mask;
4477 Mask.push_back(NumElems);
4478 for (unsigned i = 1; i != NumElems; ++i)
4480 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4483 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4484 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4486 unsigned NumElems = VT.getVectorNumElements();
4487 SmallVector<int, 8> Mask;
4488 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4490 Mask.push_back(i + NumElems);
4492 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4495 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4496 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4498 unsigned NumElems = VT.getVectorNumElements();
4499 SmallVector<int, 8> Mask;
4500 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4501 Mask.push_back(i + Half);
4502 Mask.push_back(i + NumElems + Half);
4504 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4507 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4508 // a generic shuffle instruction because the target has no such instructions.
4509 // Generate shuffles which repeat i16 and i8 several times until they can be
4510 // represented by v4f32 and then be manipulated by target suported shuffles.
4511 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4512 EVT VT = V.getValueType();
4513 int NumElems = VT.getVectorNumElements();
4516 while (NumElems > 4) {
4517 if (EltNo < NumElems/2) {
4518 V = getUnpackl(DAG, dl, VT, V, V);
4520 V = getUnpackh(DAG, dl, VT, V, V);
4521 EltNo -= NumElems/2;
4528 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4529 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4530 EVT VT = V.getValueType();
4533 if (VT.is128BitVector()) {
4534 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4535 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4536 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4538 } else if (VT.is256BitVector()) {
4539 // To use VPERMILPS to splat scalars, the second half of indicies must
4540 // refer to the higher part, which is a duplication of the lower one,
4541 // because VPERMILPS can only handle in-lane permutations.
4542 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4543 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4545 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4546 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4549 llvm_unreachable("Vector size not supported");
4551 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4554 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4555 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4556 EVT SrcVT = SV->getValueType(0);
4557 SDValue V1 = SV->getOperand(0);
4560 int EltNo = SV->getSplatIndex();
4561 int NumElems = SrcVT.getVectorNumElements();
4562 bool Is256BitVec = SrcVT.is256BitVector();
4564 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4565 "Unknown how to promote splat for type");
4567 // Extract the 128-bit part containing the splat element and update
4568 // the splat element index when it refers to the higher register.
4570 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4571 if (EltNo >= NumElems/2)
4572 EltNo -= NumElems/2;
4575 // All i16 and i8 vector types can't be used directly by a generic shuffle
4576 // instruction because the target has no such instruction. Generate shuffles
4577 // which repeat i16 and i8 several times until they fit in i32, and then can
4578 // be manipulated by target suported shuffles.
4579 EVT EltVT = SrcVT.getVectorElementType();
4580 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4581 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4583 // Recreate the 256-bit vector and place the same 128-bit vector
4584 // into the low and high part. This is necessary because we want
4585 // to use VPERM* to shuffle the vectors
4587 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4590 return getLegalSplat(DAG, V1, EltNo);
4593 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4594 /// vector of zero or undef vector. This produces a shuffle where the low
4595 /// element of V2 is swizzled into the zero/undef vector, landing at element
4596 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4597 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4599 const X86Subtarget *Subtarget,
4600 SelectionDAG &DAG) {
4601 EVT VT = V2.getValueType();
4603 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4604 unsigned NumElems = VT.getVectorNumElements();
4605 SmallVector<int, 16> MaskVec;
4606 for (unsigned i = 0; i != NumElems; ++i)
4607 // If this is the insertion idx, put the low elt of V2 here.
4608 MaskVec.push_back(i == Idx ? NumElems : i);
4609 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4612 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4613 /// target specific opcode. Returns true if the Mask could be calculated.
4614 /// Sets IsUnary to true if only uses one source.
4615 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4616 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4617 unsigned NumElems = VT.getVectorNumElements();
4621 switch(N->getOpcode()) {
4623 ImmN = N->getOperand(N->getNumOperands()-1);
4624 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4626 case X86ISD::UNPCKH:
4627 DecodeUNPCKHMask(VT, Mask);
4629 case X86ISD::UNPCKL:
4630 DecodeUNPCKLMask(VT, Mask);
4632 case X86ISD::MOVHLPS:
4633 DecodeMOVHLPSMask(NumElems, Mask);
4635 case X86ISD::MOVLHPS:
4636 DecodeMOVLHPSMask(NumElems, Mask);
4638 case X86ISD::PALIGNR:
4639 ImmN = N->getOperand(N->getNumOperands()-1);
4640 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4642 case X86ISD::PSHUFD:
4643 case X86ISD::VPERMILP:
4644 ImmN = N->getOperand(N->getNumOperands()-1);
4645 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4648 case X86ISD::PSHUFHW:
4649 ImmN = N->getOperand(N->getNumOperands()-1);
4650 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4653 case X86ISD::PSHUFLW:
4654 ImmN = N->getOperand(N->getNumOperands()-1);
4655 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4658 case X86ISD::VPERMI:
4659 ImmN = N->getOperand(N->getNumOperands()-1);
4660 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4664 case X86ISD::MOVSD: {
4665 // The index 0 always comes from the first element of the second source,
4666 // this is why MOVSS and MOVSD are used in the first place. The other
4667 // elements come from the other positions of the first source vector
4668 Mask.push_back(NumElems);
4669 for (unsigned i = 1; i != NumElems; ++i) {
4674 case X86ISD::VPERM2X128:
4675 ImmN = N->getOperand(N->getNumOperands()-1);
4676 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4677 if (Mask.empty()) return false;
4679 case X86ISD::MOVDDUP:
4680 case X86ISD::MOVLHPD:
4681 case X86ISD::MOVLPD:
4682 case X86ISD::MOVLPS:
4683 case X86ISD::MOVSHDUP:
4684 case X86ISD::MOVSLDUP:
4685 // Not yet implemented
4687 default: llvm_unreachable("unknown target shuffle node");
4693 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4694 /// element of the result of the vector shuffle.
4695 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4698 return SDValue(); // Limit search depth.
4700 SDValue V = SDValue(N, 0);
4701 EVT VT = V.getValueType();
4702 unsigned Opcode = V.getOpcode();
4704 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4705 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4706 int Elt = SV->getMaskElt(Index);
4709 return DAG.getUNDEF(VT.getVectorElementType());
4711 unsigned NumElems = VT.getVectorNumElements();
4712 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4713 : SV->getOperand(1);
4714 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4717 // Recurse into target specific vector shuffles to find scalars.
4718 if (isTargetShuffle(Opcode)) {
4719 MVT ShufVT = V.getValueType().getSimpleVT();
4720 unsigned NumElems = ShufVT.getVectorNumElements();
4721 SmallVector<int, 16> ShuffleMask;
4724 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4727 int Elt = ShuffleMask[Index];
4729 return DAG.getUNDEF(ShufVT.getVectorElementType());
4731 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4733 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4737 // Actual nodes that may contain scalar elements
4738 if (Opcode == ISD::BITCAST) {
4739 V = V.getOperand(0);
4740 EVT SrcVT = V.getValueType();
4741 unsigned NumElems = VT.getVectorNumElements();
4743 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4747 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4748 return (Index == 0) ? V.getOperand(0)
4749 : DAG.getUNDEF(VT.getVectorElementType());
4751 if (V.getOpcode() == ISD::BUILD_VECTOR)
4752 return V.getOperand(Index);
4757 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4758 /// shuffle operation which come from a consecutively from a zero. The
4759 /// search can start in two different directions, from left or right.
4760 /// We count undefs as zeros until PreferredNum is reached.
4761 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4762 unsigned NumElems, bool ZerosFromLeft,
4764 unsigned PreferredNum = -1U) {
4765 unsigned NumZeros = 0;
4766 for (unsigned i = 0; i != NumElems; ++i) {
4767 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
4768 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4772 if (X86::isZeroNode(Elt))
4774 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
4775 NumZeros = std::min(NumZeros + 1, PreferredNum);
4783 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4784 /// correspond consecutively to elements from one of the vector operands,
4785 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4787 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4788 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4789 unsigned NumElems, unsigned &OpNum) {
4790 bool SeenV1 = false;
4791 bool SeenV2 = false;
4793 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4794 int Idx = SVOp->getMaskElt(i);
4795 // Ignore undef indicies
4799 if (Idx < (int)NumElems)
4804 // Only accept consecutive elements from the same vector
4805 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4809 OpNum = SeenV1 ? 0 : 1;
4813 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4814 /// logical left shift of a vector.
4815 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4816 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4817 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4818 unsigned NumZeros = getNumOfConsecutiveZeros(
4819 SVOp, NumElems, false /* check zeros from right */, DAG,
4820 SVOp->getMaskElt(0));
4826 // Considering the elements in the mask that are not consecutive zeros,
4827 // check if they consecutively come from only one of the source vectors.
4829 // V1 = {X, A, B, C} 0
4831 // vector_shuffle V1, V2 <1, 2, 3, X>
4833 if (!isShuffleMaskConsecutive(SVOp,
4834 0, // Mask Start Index
4835 NumElems-NumZeros, // Mask End Index(exclusive)
4836 NumZeros, // Where to start looking in the src vector
4837 NumElems, // Number of elements in vector
4838 OpSrc)) // Which source operand ?
4843 ShVal = SVOp->getOperand(OpSrc);
4847 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4848 /// logical left shift of a vector.
4849 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4850 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4851 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4852 unsigned NumZeros = getNumOfConsecutiveZeros(
4853 SVOp, NumElems, true /* check zeros from left */, DAG,
4854 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
4860 // Considering the elements in the mask that are not consecutive zeros,
4861 // check if they consecutively come from only one of the source vectors.
4863 // 0 { A, B, X, X } = V2
4865 // vector_shuffle V1, V2 <X, X, 4, 5>
4867 if (!isShuffleMaskConsecutive(SVOp,
4868 NumZeros, // Mask Start Index
4869 NumElems, // Mask End Index(exclusive)
4870 0, // Where to start looking in the src vector
4871 NumElems, // Number of elements in vector
4872 OpSrc)) // Which source operand ?
4877 ShVal = SVOp->getOperand(OpSrc);
4881 /// isVectorShift - Returns true if the shuffle can be implemented as a
4882 /// logical left or right shift of a vector.
4883 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4884 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4885 // Although the logic below support any bitwidth size, there are no
4886 // shift instructions which handle more than 128-bit vectors.
4887 if (!SVOp->getValueType(0).is128BitVector())
4890 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4891 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4897 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4899 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4900 unsigned NumNonZero, unsigned NumZero,
4902 const X86Subtarget* Subtarget,
4903 const TargetLowering &TLI) {
4910 for (unsigned i = 0; i < 16; ++i) {
4911 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4912 if (ThisIsNonZero && First) {
4914 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4916 V = DAG.getUNDEF(MVT::v8i16);
4921 SDValue ThisElt(0, 0), LastElt(0, 0);
4922 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4923 if (LastIsNonZero) {
4924 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4925 MVT::i16, Op.getOperand(i-1));
4927 if (ThisIsNonZero) {
4928 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4929 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4930 ThisElt, DAG.getConstant(8, MVT::i8));
4932 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4936 if (ThisElt.getNode())
4937 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4938 DAG.getIntPtrConstant(i/2));
4942 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4945 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4947 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4948 unsigned NumNonZero, unsigned NumZero,
4950 const X86Subtarget* Subtarget,
4951 const TargetLowering &TLI) {
4958 for (unsigned i = 0; i < 8; ++i) {
4959 bool isNonZero = (NonZeros & (1 << i)) != 0;
4963 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4965 V = DAG.getUNDEF(MVT::v8i16);
4968 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4969 MVT::v8i16, V, Op.getOperand(i),
4970 DAG.getIntPtrConstant(i));
4977 /// getVShift - Return a vector logical shift node.
4979 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4980 unsigned NumBits, SelectionDAG &DAG,
4981 const TargetLowering &TLI, SDLoc dl) {
4982 assert(VT.is128BitVector() && "Unknown type for VShift");
4983 EVT ShVT = MVT::v2i64;
4984 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4985 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4986 return DAG.getNode(ISD::BITCAST, dl, VT,
4987 DAG.getNode(Opc, dl, ShVT, SrcOp,
4988 DAG.getConstant(NumBits,
4989 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4993 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
4994 SelectionDAG &DAG) const {
4996 // Check if the scalar load can be widened into a vector load. And if
4997 // the address is "base + cst" see if the cst can be "absorbed" into
4998 // the shuffle mask.
4999 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5000 SDValue Ptr = LD->getBasePtr();
5001 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5003 EVT PVT = LD->getValueType(0);
5004 if (PVT != MVT::i32 && PVT != MVT::f32)
5009 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5010 FI = FINode->getIndex();
5012 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5013 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5014 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5015 Offset = Ptr.getConstantOperandVal(1);
5016 Ptr = Ptr.getOperand(0);
5021 // FIXME: 256-bit vector instructions don't require a strict alignment,
5022 // improve this code to support it better.
5023 unsigned RequiredAlign = VT.getSizeInBits()/8;
5024 SDValue Chain = LD->getChain();
5025 // Make sure the stack object alignment is at least 16 or 32.
5026 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5027 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5028 if (MFI->isFixedObjectIndex(FI)) {
5029 // Can't change the alignment. FIXME: It's possible to compute
5030 // the exact stack offset and reference FI + adjust offset instead.
5031 // If someone *really* cares about this. That's the way to implement it.
5034 MFI->setObjectAlignment(FI, RequiredAlign);
5038 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5039 // Ptr + (Offset & ~15).
5042 if ((Offset % RequiredAlign) & 3)
5044 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5046 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5047 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5049 int EltNo = (Offset - StartOffset) >> 2;
5050 unsigned NumElems = VT.getVectorNumElements();
5052 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5053 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5054 LD->getPointerInfo().getWithOffset(StartOffset),
5055 false, false, false, 0);
5057 SmallVector<int, 8> Mask;
5058 for (unsigned i = 0; i != NumElems; ++i)
5059 Mask.push_back(EltNo);
5061 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5067 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5068 /// vector of type 'VT', see if the elements can be replaced by a single large
5069 /// load which has the same value as a build_vector whose operands are 'elts'.
5071 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5073 /// FIXME: we'd also like to handle the case where the last elements are zero
5074 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5075 /// There's even a handy isZeroNode for that purpose.
5076 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5077 SDLoc &DL, SelectionDAG &DAG) {
5078 EVT EltVT = VT.getVectorElementType();
5079 unsigned NumElems = Elts.size();
5081 LoadSDNode *LDBase = NULL;
5082 unsigned LastLoadedElt = -1U;
5084 // For each element in the initializer, see if we've found a load or an undef.
5085 // If we don't find an initial load element, or later load elements are
5086 // non-consecutive, bail out.
5087 for (unsigned i = 0; i < NumElems; ++i) {
5088 SDValue Elt = Elts[i];
5090 if (!Elt.getNode() ||
5091 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5094 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5096 LDBase = cast<LoadSDNode>(Elt.getNode());
5100 if (Elt.getOpcode() == ISD::UNDEF)
5103 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5104 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5109 // If we have found an entire vector of loads and undefs, then return a large
5110 // load of the entire vector width starting at the base pointer. If we found
5111 // consecutive loads for the low half, generate a vzext_load node.
5112 if (LastLoadedElt == NumElems - 1) {
5113 SDValue NewLd = SDValue();
5114 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5115 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5116 LDBase->getPointerInfo(),
5117 LDBase->isVolatile(), LDBase->isNonTemporal(),
5118 LDBase->isInvariant(), 0);
5119 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5120 LDBase->getPointerInfo(),
5121 LDBase->isVolatile(), LDBase->isNonTemporal(),
5122 LDBase->isInvariant(), LDBase->getAlignment());
5124 if (LDBase->hasAnyUseOfValue(1)) {
5125 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5127 SDValue(NewLd.getNode(), 1));
5128 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5129 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5130 SDValue(NewLd.getNode(), 1));
5135 if (NumElems == 4 && LastLoadedElt == 1 &&
5136 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5137 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5138 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5140 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5141 array_lengthof(Ops), MVT::i64,
5142 LDBase->getPointerInfo(),
5143 LDBase->getAlignment(),
5144 false/*isVolatile*/, true/*ReadMem*/,
5147 // Make sure the newly-created LOAD is in the same position as LDBase in
5148 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5149 // update uses of LDBase's output chain to use the TokenFactor.
5150 if (LDBase->hasAnyUseOfValue(1)) {
5151 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5152 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5153 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5154 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5155 SDValue(ResNode.getNode(), 1));
5158 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5163 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5164 /// to generate a splat value for the following cases:
5165 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5166 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5167 /// a scalar load, or a constant.
5168 /// The VBROADCAST node is returned when a pattern is found,
5169 /// or SDValue() otherwise.
5171 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5172 if (!Subtarget->hasFp256())
5175 MVT VT = Op.getValueType().getSimpleVT();
5178 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5179 "Unsupported vector type for broadcast.");
5184 switch (Op.getOpcode()) {
5186 // Unknown pattern found.
5189 case ISD::BUILD_VECTOR: {
5190 // The BUILD_VECTOR node must be a splat.
5191 if (!isSplatVector(Op.getNode()))
5194 Ld = Op.getOperand(0);
5195 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5196 Ld.getOpcode() == ISD::ConstantFP);
5198 // The suspected load node has several users. Make sure that all
5199 // of its users are from the BUILD_VECTOR node.
5200 // Constants may have multiple users.
5201 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5206 case ISD::VECTOR_SHUFFLE: {
5207 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5209 // Shuffles must have a splat mask where the first element is
5211 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5214 SDValue Sc = Op.getOperand(0);
5215 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5216 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5218 if (!Subtarget->hasInt256())
5221 // Use the register form of the broadcast instruction available on AVX2.
5222 if (VT.is256BitVector())
5223 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5224 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5227 Ld = Sc.getOperand(0);
5228 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5229 Ld.getOpcode() == ISD::ConstantFP);
5231 // The scalar_to_vector node and the suspected
5232 // load node must have exactly one user.
5233 // Constants may have multiple users.
5234 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5240 bool Is256 = VT.is256BitVector();
5242 // Handle the broadcasting a single constant scalar from the constant pool
5243 // into a vector. On Sandybridge it is still better to load a constant vector
5244 // from the constant pool and not to broadcast it from a scalar.
5245 if (ConstSplatVal && Subtarget->hasInt256()) {
5246 EVT CVT = Ld.getValueType();
5247 assert(!CVT.isVector() && "Must not broadcast a vector type");
5248 unsigned ScalarSize = CVT.getSizeInBits();
5250 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5251 const Constant *C = 0;
5252 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5253 C = CI->getConstantIntValue();
5254 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5255 C = CF->getConstantFPValue();
5257 assert(C && "Invalid constant type");
5259 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5260 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5261 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5262 MachinePointerInfo::getConstantPool(),
5263 false, false, false, Alignment);
5265 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5269 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5270 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5272 // Handle AVX2 in-register broadcasts.
5273 if (!IsLoad && Subtarget->hasInt256() &&
5274 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5275 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5277 // The scalar source must be a normal load.
5281 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5282 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5284 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5285 // double since there is no vbroadcastsd xmm
5286 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5287 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5288 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5291 // Unsupported broadcast.
5296 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5297 EVT VT = Op.getValueType();
5299 // Skip if insert_vec_elt is not supported.
5300 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5304 unsigned NumElems = Op.getNumOperands();
5308 SmallVector<unsigned, 4> InsertIndices;
5309 SmallVector<int, 8> Mask(NumElems, -1);
5311 for (unsigned i = 0; i != NumElems; ++i) {
5312 unsigned Opc = Op.getOperand(i).getOpcode();
5314 if (Opc == ISD::UNDEF)
5317 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5318 // Quit if more than 1 elements need inserting.
5319 if (InsertIndices.size() > 1)
5322 InsertIndices.push_back(i);
5326 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5327 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5329 // Quit if extracted from vector of different type.
5330 if (ExtractedFromVec.getValueType() != VT)
5333 // Quit if non-constant index.
5334 if (!isa<ConstantSDNode>(ExtIdx))
5337 if (VecIn1.getNode() == 0)
5338 VecIn1 = ExtractedFromVec;
5339 else if (VecIn1 != ExtractedFromVec) {
5340 if (VecIn2.getNode() == 0)
5341 VecIn2 = ExtractedFromVec;
5342 else if (VecIn2 != ExtractedFromVec)
5343 // Quit if more than 2 vectors to shuffle
5347 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5349 if (ExtractedFromVec == VecIn1)
5351 else if (ExtractedFromVec == VecIn2)
5352 Mask[i] = Idx + NumElems;
5355 if (VecIn1.getNode() == 0)
5358 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5359 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5360 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5361 unsigned Idx = InsertIndices[i];
5362 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5363 DAG.getIntPtrConstant(Idx));
5370 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5373 MVT VT = Op.getValueType().getSimpleVT();
5374 MVT ExtVT = VT.getVectorElementType();
5375 unsigned NumElems = Op.getNumOperands();
5377 // Vectors containing all zeros can be matched by pxor and xorps later
5378 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5379 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5380 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5381 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5384 return getZeroVector(VT, Subtarget, DAG, dl);
5387 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5388 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5389 // vpcmpeqd on 256-bit vectors.
5390 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5391 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5394 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5397 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5398 if (Broadcast.getNode())
5401 unsigned EVTBits = ExtVT.getSizeInBits();
5403 unsigned NumZero = 0;
5404 unsigned NumNonZero = 0;
5405 unsigned NonZeros = 0;
5406 bool IsAllConstants = true;
5407 SmallSet<SDValue, 8> Values;
5408 for (unsigned i = 0; i < NumElems; ++i) {
5409 SDValue Elt = Op.getOperand(i);
5410 if (Elt.getOpcode() == ISD::UNDEF)
5413 if (Elt.getOpcode() != ISD::Constant &&
5414 Elt.getOpcode() != ISD::ConstantFP)
5415 IsAllConstants = false;
5416 if (X86::isZeroNode(Elt))
5419 NonZeros |= (1 << i);
5424 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5425 if (NumNonZero == 0)
5426 return DAG.getUNDEF(VT);
5428 // Special case for single non-zero, non-undef, element.
5429 if (NumNonZero == 1) {
5430 unsigned Idx = countTrailingZeros(NonZeros);
5431 SDValue Item = Op.getOperand(Idx);
5433 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5434 // the value are obviously zero, truncate the value to i32 and do the
5435 // insertion that way. Only do this if the value is non-constant or if the
5436 // value is a constant being inserted into element 0. It is cheaper to do
5437 // a constant pool load than it is to do a movd + shuffle.
5438 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5439 (!IsAllConstants || Idx == 0)) {
5440 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5442 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5443 EVT VecVT = MVT::v4i32;
5444 unsigned VecElts = 4;
5446 // Truncate the value (which may itself be a constant) to i32, and
5447 // convert it to a vector with movd (S2V+shuffle to zero extend).
5448 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5449 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5450 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5452 // Now we have our 32-bit value zero extended in the low element of
5453 // a vector. If Idx != 0, swizzle it into place.
5455 SmallVector<int, 4> Mask;
5456 Mask.push_back(Idx);
5457 for (unsigned i = 1; i != VecElts; ++i)
5459 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5462 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5466 // If we have a constant or non-constant insertion into the low element of
5467 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5468 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5469 // depending on what the source datatype is.
5472 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5474 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5475 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5476 if (VT.is256BitVector()) {
5477 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5478 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5479 Item, DAG.getIntPtrConstant(0));
5481 assert(VT.is128BitVector() && "Expected an SSE value type!");
5482 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5483 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5484 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5487 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5488 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5489 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5490 if (VT.is256BitVector()) {
5491 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5492 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5494 assert(VT.is128BitVector() && "Expected an SSE value type!");
5495 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5497 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5501 // Is it a vector logical left shift?
5502 if (NumElems == 2 && Idx == 1 &&
5503 X86::isZeroNode(Op.getOperand(0)) &&
5504 !X86::isZeroNode(Op.getOperand(1))) {
5505 unsigned NumBits = VT.getSizeInBits();
5506 return getVShift(true, VT,
5507 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5508 VT, Op.getOperand(1)),
5509 NumBits/2, DAG, *this, dl);
5512 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5515 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5516 // is a non-constant being inserted into an element other than the low one,
5517 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5518 // movd/movss) to move this into the low element, then shuffle it into
5520 if (EVTBits == 32) {
5521 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5523 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5524 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5525 SmallVector<int, 8> MaskVec;
5526 for (unsigned i = 0; i != NumElems; ++i)
5527 MaskVec.push_back(i == Idx ? 0 : 1);
5528 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5532 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5533 if (Values.size() == 1) {
5534 if (EVTBits == 32) {
5535 // Instead of a shuffle like this:
5536 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5537 // Check if it's possible to issue this instead.
5538 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5539 unsigned Idx = countTrailingZeros(NonZeros);
5540 SDValue Item = Op.getOperand(Idx);
5541 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5542 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5547 // A vector full of immediates; various special cases are already
5548 // handled, so this is best done with a single constant-pool load.
5552 // For AVX-length vectors, build the individual 128-bit pieces and use
5553 // shuffles to put them in place.
5554 if (VT.is256BitVector()) {
5555 SmallVector<SDValue, 32> V;
5556 for (unsigned i = 0; i != NumElems; ++i)
5557 V.push_back(Op.getOperand(i));
5559 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5561 // Build both the lower and upper subvector.
5562 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5563 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5566 // Recreate the wider vector with the lower and upper part.
5567 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5570 // Let legalizer expand 2-wide build_vectors.
5571 if (EVTBits == 64) {
5572 if (NumNonZero == 1) {
5573 // One half is zero or undef.
5574 unsigned Idx = countTrailingZeros(NonZeros);
5575 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5576 Op.getOperand(Idx));
5577 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5582 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5583 if (EVTBits == 8 && NumElems == 16) {
5584 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5586 if (V.getNode()) return V;
5589 if (EVTBits == 16 && NumElems == 8) {
5590 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5592 if (V.getNode()) return V;
5595 // If element VT is == 32 bits, turn it into a number of shuffles.
5596 SmallVector<SDValue, 8> V(NumElems);
5597 if (NumElems == 4 && NumZero > 0) {
5598 for (unsigned i = 0; i < 4; ++i) {
5599 bool isZero = !(NonZeros & (1 << i));
5601 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5603 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5606 for (unsigned i = 0; i < 2; ++i) {
5607 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5610 V[i] = V[i*2]; // Must be a zero vector.
5613 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5616 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5619 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5624 bool Reverse1 = (NonZeros & 0x3) == 2;
5625 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5629 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5630 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5632 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5635 if (Values.size() > 1 && VT.is128BitVector()) {
5636 // Check for a build vector of consecutive loads.
5637 for (unsigned i = 0; i < NumElems; ++i)
5638 V[i] = Op.getOperand(i);
5640 // Check for elements which are consecutive loads.
5641 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5645 // Check for a build vector from mostly shuffle plus few inserting.
5646 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5650 // For SSE 4.1, use insertps to put the high elements into the low element.
5651 if (getSubtarget()->hasSSE41()) {
5653 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5654 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5656 Result = DAG.getUNDEF(VT);
5658 for (unsigned i = 1; i < NumElems; ++i) {
5659 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5660 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5661 Op.getOperand(i), DAG.getIntPtrConstant(i));
5666 // Otherwise, expand into a number of unpckl*, start by extending each of
5667 // our (non-undef) elements to the full vector width with the element in the
5668 // bottom slot of the vector (which generates no code for SSE).
5669 for (unsigned i = 0; i < NumElems; ++i) {
5670 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5671 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5673 V[i] = DAG.getUNDEF(VT);
5676 // Next, we iteratively mix elements, e.g. for v4f32:
5677 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5678 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5679 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5680 unsigned EltStride = NumElems >> 1;
5681 while (EltStride != 0) {
5682 for (unsigned i = 0; i < EltStride; ++i) {
5683 // If V[i+EltStride] is undef and this is the first round of mixing,
5684 // then it is safe to just drop this shuffle: V[i] is already in the
5685 // right place, the one element (since it's the first round) being
5686 // inserted as undef can be dropped. This isn't safe for successive
5687 // rounds because they will permute elements within both vectors.
5688 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5689 EltStride == NumElems/2)
5692 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5701 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5702 // to create 256-bit vectors from two other 128-bit ones.
5703 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5705 MVT ResVT = Op.getValueType().getSimpleVT();
5707 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5709 SDValue V1 = Op.getOperand(0);
5710 SDValue V2 = Op.getOperand(1);
5711 unsigned NumElems = ResVT.getVectorNumElements();
5713 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5716 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5717 assert(Op.getNumOperands() == 2);
5719 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5720 // from two other 128-bit ones.
5721 return LowerAVXCONCAT_VECTORS(Op, DAG);
5724 // Try to lower a shuffle node into a simple blend instruction.
5726 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5727 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5728 SDValue V1 = SVOp->getOperand(0);
5729 SDValue V2 = SVOp->getOperand(1);
5731 MVT VT = SVOp->getValueType(0).getSimpleVT();
5732 MVT EltVT = VT.getVectorElementType();
5733 unsigned NumElems = VT.getVectorNumElements();
5735 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5737 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5740 // Check the mask for BLEND and build the value.
5741 unsigned MaskValue = 0;
5742 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5743 unsigned NumLanes = (NumElems-1)/8 + 1;
5744 unsigned NumElemsInLane = NumElems / NumLanes;
5746 // Blend for v16i16 should be symetric for the both lanes.
5747 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5749 int SndLaneEltIdx = (NumLanes == 2) ?
5750 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5751 int EltIdx = SVOp->getMaskElt(i);
5753 if ((EltIdx < 0 || EltIdx == (int)i) &&
5754 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5757 if (((unsigned)EltIdx == (i + NumElems)) &&
5758 (SndLaneEltIdx < 0 ||
5759 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5760 MaskValue |= (1<<i);
5765 // Convert i32 vectors to floating point if it is not AVX2.
5766 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5768 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5769 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5771 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5772 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5775 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5776 DAG.getConstant(MaskValue, MVT::i32));
5777 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5780 // v8i16 shuffles - Prefer shuffles in the following order:
5781 // 1. [all] pshuflw, pshufhw, optional move
5782 // 2. [ssse3] 1 x pshufb
5783 // 3. [ssse3] 2 x pshufb + 1 x por
5784 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5786 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5787 SelectionDAG &DAG) {
5788 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5789 SDValue V1 = SVOp->getOperand(0);
5790 SDValue V2 = SVOp->getOperand(1);
5792 SmallVector<int, 8> MaskVals;
5794 // Determine if more than 1 of the words in each of the low and high quadwords
5795 // of the result come from the same quadword of one of the two inputs. Undef
5796 // mask values count as coming from any quadword, for better codegen.
5797 unsigned LoQuad[] = { 0, 0, 0, 0 };
5798 unsigned HiQuad[] = { 0, 0, 0, 0 };
5799 std::bitset<4> InputQuads;
5800 for (unsigned i = 0; i < 8; ++i) {
5801 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5802 int EltIdx = SVOp->getMaskElt(i);
5803 MaskVals.push_back(EltIdx);
5812 InputQuads.set(EltIdx / 4);
5815 int BestLoQuad = -1;
5816 unsigned MaxQuad = 1;
5817 for (unsigned i = 0; i < 4; ++i) {
5818 if (LoQuad[i] > MaxQuad) {
5820 MaxQuad = LoQuad[i];
5824 int BestHiQuad = -1;
5826 for (unsigned i = 0; i < 4; ++i) {
5827 if (HiQuad[i] > MaxQuad) {
5829 MaxQuad = HiQuad[i];
5833 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5834 // of the two input vectors, shuffle them into one input vector so only a
5835 // single pshufb instruction is necessary. If There are more than 2 input
5836 // quads, disable the next transformation since it does not help SSSE3.
5837 bool V1Used = InputQuads[0] || InputQuads[1];
5838 bool V2Used = InputQuads[2] || InputQuads[3];
5839 if (Subtarget->hasSSSE3()) {
5840 if (InputQuads.count() == 2 && V1Used && V2Used) {
5841 BestLoQuad = InputQuads[0] ? 0 : 1;
5842 BestHiQuad = InputQuads[2] ? 2 : 3;
5844 if (InputQuads.count() > 2) {
5850 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5851 // the shuffle mask. If a quad is scored as -1, that means that it contains
5852 // words from all 4 input quadwords.
5854 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5856 BestLoQuad < 0 ? 0 : BestLoQuad,
5857 BestHiQuad < 0 ? 1 : BestHiQuad
5859 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5860 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5861 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5862 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5864 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5865 // source words for the shuffle, to aid later transformations.
5866 bool AllWordsInNewV = true;
5867 bool InOrder[2] = { true, true };
5868 for (unsigned i = 0; i != 8; ++i) {
5869 int idx = MaskVals[i];
5871 InOrder[i/4] = false;
5872 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5874 AllWordsInNewV = false;
5878 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5879 if (AllWordsInNewV) {
5880 for (int i = 0; i != 8; ++i) {
5881 int idx = MaskVals[i];
5884 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5885 if ((idx != i) && idx < 4)
5887 if ((idx != i) && idx > 3)
5896 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5897 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5898 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5899 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5900 unsigned TargetMask = 0;
5901 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5902 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5903 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5904 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5905 getShufflePSHUFLWImmediate(SVOp);
5906 V1 = NewV.getOperand(0);
5907 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5911 // Promote splats to a larger type which usually leads to more efficient code.
5912 // FIXME: Is this true if pshufb is available?
5913 if (SVOp->isSplat())
5914 return PromoteSplat(SVOp, DAG);
5916 // If we have SSSE3, and all words of the result are from 1 input vector,
5917 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5918 // is present, fall back to case 4.
5919 if (Subtarget->hasSSSE3()) {
5920 SmallVector<SDValue,16> pshufbMask;
5922 // If we have elements from both input vectors, set the high bit of the
5923 // shuffle mask element to zero out elements that come from V2 in the V1
5924 // mask, and elements that come from V1 in the V2 mask, so that the two
5925 // results can be OR'd together.
5926 bool TwoInputs = V1Used && V2Used;
5927 for (unsigned i = 0; i != 8; ++i) {
5928 int EltIdx = MaskVals[i] * 2;
5929 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5930 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5931 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5932 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5934 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5935 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5936 DAG.getNode(ISD::BUILD_VECTOR, dl,
5937 MVT::v16i8, &pshufbMask[0], 16));
5939 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5941 // Calculate the shuffle mask for the second input, shuffle it, and
5942 // OR it with the first shuffled input.
5944 for (unsigned i = 0; i != 8; ++i) {
5945 int EltIdx = MaskVals[i] * 2;
5946 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5947 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5948 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5949 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5951 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5952 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5953 DAG.getNode(ISD::BUILD_VECTOR, dl,
5954 MVT::v16i8, &pshufbMask[0], 16));
5955 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5956 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5959 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5960 // and update MaskVals with new element order.
5961 std::bitset<8> InOrder;
5962 if (BestLoQuad >= 0) {
5963 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5964 for (int i = 0; i != 4; ++i) {
5965 int idx = MaskVals[i];
5968 } else if ((idx / 4) == BestLoQuad) {
5973 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5976 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5977 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5978 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5980 getShufflePSHUFLWImmediate(SVOp), DAG);
5984 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5985 // and update MaskVals with the new element order.
5986 if (BestHiQuad >= 0) {
5987 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5988 for (unsigned i = 4; i != 8; ++i) {
5989 int idx = MaskVals[i];
5992 } else if ((idx / 4) == BestHiQuad) {
5993 MaskV[i] = (idx & 3) + 4;
5997 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6000 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6001 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6002 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6004 getShufflePSHUFHWImmediate(SVOp), DAG);
6008 // In case BestHi & BestLo were both -1, which means each quadword has a word
6009 // from each of the four input quadwords, calculate the InOrder bitvector now
6010 // before falling through to the insert/extract cleanup.
6011 if (BestLoQuad == -1 && BestHiQuad == -1) {
6013 for (int i = 0; i != 8; ++i)
6014 if (MaskVals[i] < 0 || MaskVals[i] == i)
6018 // The other elements are put in the right place using pextrw and pinsrw.
6019 for (unsigned i = 0; i != 8; ++i) {
6022 int EltIdx = MaskVals[i];
6025 SDValue ExtOp = (EltIdx < 8) ?
6026 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6027 DAG.getIntPtrConstant(EltIdx)) :
6028 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6029 DAG.getIntPtrConstant(EltIdx - 8));
6030 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6031 DAG.getIntPtrConstant(i));
6036 // v16i8 shuffles - Prefer shuffles in the following order:
6037 // 1. [ssse3] 1 x pshufb
6038 // 2. [ssse3] 2 x pshufb + 1 x por
6039 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6041 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6043 const X86TargetLowering &TLI) {
6044 SDValue V1 = SVOp->getOperand(0);
6045 SDValue V2 = SVOp->getOperand(1);
6047 ArrayRef<int> MaskVals = SVOp->getMask();
6049 // Promote splats to a larger type which usually leads to more efficient code.
6050 // FIXME: Is this true if pshufb is available?
6051 if (SVOp->isSplat())
6052 return PromoteSplat(SVOp, DAG);
6054 // If we have SSSE3, case 1 is generated when all result bytes come from
6055 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6056 // present, fall back to case 3.
6058 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6059 if (TLI.getSubtarget()->hasSSSE3()) {
6060 SmallVector<SDValue,16> pshufbMask;
6062 // If all result elements are from one input vector, then only translate
6063 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6065 // Otherwise, we have elements from both input vectors, and must zero out
6066 // elements that come from V2 in the first mask, and V1 in the second mask
6067 // so that we can OR them together.
6068 for (unsigned i = 0; i != 16; ++i) {
6069 int EltIdx = MaskVals[i];
6070 if (EltIdx < 0 || EltIdx >= 16)
6072 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6074 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6075 DAG.getNode(ISD::BUILD_VECTOR, dl,
6076 MVT::v16i8, &pshufbMask[0], 16));
6078 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6079 // the 2nd operand if it's undefined or zero.
6080 if (V2.getOpcode() == ISD::UNDEF ||
6081 ISD::isBuildVectorAllZeros(V2.getNode()))
6084 // Calculate the shuffle mask for the second input, shuffle it, and
6085 // OR it with the first shuffled input.
6087 for (unsigned i = 0; i != 16; ++i) {
6088 int EltIdx = MaskVals[i];
6089 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6090 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6092 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6093 DAG.getNode(ISD::BUILD_VECTOR, dl,
6094 MVT::v16i8, &pshufbMask[0], 16));
6095 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6098 // No SSSE3 - Calculate in place words and then fix all out of place words
6099 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6100 // the 16 different words that comprise the two doublequadword input vectors.
6101 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6102 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6104 for (int i = 0; i != 8; ++i) {
6105 int Elt0 = MaskVals[i*2];
6106 int Elt1 = MaskVals[i*2+1];
6108 // This word of the result is all undef, skip it.
6109 if (Elt0 < 0 && Elt1 < 0)
6112 // This word of the result is already in the correct place, skip it.
6113 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6116 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6117 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6120 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6121 // using a single extract together, load it and store it.
6122 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6123 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6124 DAG.getIntPtrConstant(Elt1 / 2));
6125 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6126 DAG.getIntPtrConstant(i));
6130 // If Elt1 is defined, extract it from the appropriate source. If the
6131 // source byte is not also odd, shift the extracted word left 8 bits
6132 // otherwise clear the bottom 8 bits if we need to do an or.
6134 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6135 DAG.getIntPtrConstant(Elt1 / 2));
6136 if ((Elt1 & 1) == 0)
6137 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6139 TLI.getShiftAmountTy(InsElt.getValueType())));
6141 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6142 DAG.getConstant(0xFF00, MVT::i16));
6144 // If Elt0 is defined, extract it from the appropriate source. If the
6145 // source byte is not also even, shift the extracted word right 8 bits. If
6146 // Elt1 was also defined, OR the extracted values together before
6147 // inserting them in the result.
6149 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6150 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6151 if ((Elt0 & 1) != 0)
6152 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6154 TLI.getShiftAmountTy(InsElt0.getValueType())));
6156 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6157 DAG.getConstant(0x00FF, MVT::i16));
6158 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6161 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6162 DAG.getIntPtrConstant(i));
6164 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6167 // v32i8 shuffles - Translate to VPSHUFB if possible.
6169 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6170 const X86Subtarget *Subtarget,
6171 SelectionDAG &DAG) {
6172 MVT VT = SVOp->getValueType(0).getSimpleVT();
6173 SDValue V1 = SVOp->getOperand(0);
6174 SDValue V2 = SVOp->getOperand(1);
6176 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6178 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6179 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6180 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6182 // VPSHUFB may be generated if
6183 // (1) one of input vector is undefined or zeroinitializer.
6184 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6185 // And (2) the mask indexes don't cross the 128-bit lane.
6186 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6187 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6190 if (V1IsAllZero && !V2IsAllZero) {
6191 CommuteVectorShuffleMask(MaskVals, 32);
6194 SmallVector<SDValue, 32> pshufbMask;
6195 for (unsigned i = 0; i != 32; i++) {
6196 int EltIdx = MaskVals[i];
6197 if (EltIdx < 0 || EltIdx >= 32)
6200 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6201 // Cross lane is not allowed.
6205 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6207 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6208 DAG.getNode(ISD::BUILD_VECTOR, dl,
6209 MVT::v32i8, &pshufbMask[0], 32));
6212 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6213 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6214 /// done when every pair / quad of shuffle mask elements point to elements in
6215 /// the right sequence. e.g.
6216 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6218 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6219 SelectionDAG &DAG) {
6220 MVT VT = SVOp->getValueType(0).getSimpleVT();
6222 unsigned NumElems = VT.getVectorNumElements();
6225 switch (VT.SimpleTy) {
6226 default: llvm_unreachable("Unexpected!");
6227 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6228 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6229 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6230 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6231 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6232 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6235 SmallVector<int, 8> MaskVec;
6236 for (unsigned i = 0; i != NumElems; i += Scale) {
6238 for (unsigned j = 0; j != Scale; ++j) {
6239 int EltIdx = SVOp->getMaskElt(i+j);
6243 StartIdx = (EltIdx / Scale);
6244 if (EltIdx != (int)(StartIdx*Scale + j))
6247 MaskVec.push_back(StartIdx);
6250 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6251 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6252 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6255 /// getVZextMovL - Return a zero-extending vector move low node.
6257 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6258 SDValue SrcOp, SelectionDAG &DAG,
6259 const X86Subtarget *Subtarget, SDLoc dl) {
6260 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6261 LoadSDNode *LD = NULL;
6262 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6263 LD = dyn_cast<LoadSDNode>(SrcOp);
6265 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6267 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6268 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6269 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6270 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6271 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6273 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6274 return DAG.getNode(ISD::BITCAST, dl, VT,
6275 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6276 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6284 return DAG.getNode(ISD::BITCAST, dl, VT,
6285 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6286 DAG.getNode(ISD::BITCAST, dl,
6290 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6291 /// which could not be matched by any known target speficic shuffle
6293 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6295 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6296 if (NewOp.getNode())
6299 MVT VT = SVOp->getValueType(0).getSimpleVT();
6301 unsigned NumElems = VT.getVectorNumElements();
6302 unsigned NumLaneElems = NumElems / 2;
6305 MVT EltVT = VT.getVectorElementType();
6306 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6309 SmallVector<int, 16> Mask;
6310 for (unsigned l = 0; l < 2; ++l) {
6311 // Build a shuffle mask for the output, discovering on the fly which
6312 // input vectors to use as shuffle operands (recorded in InputUsed).
6313 // If building a suitable shuffle vector proves too hard, then bail
6314 // out with UseBuildVector set.
6315 bool UseBuildVector = false;
6316 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6317 unsigned LaneStart = l * NumLaneElems;
6318 for (unsigned i = 0; i != NumLaneElems; ++i) {
6319 // The mask element. This indexes into the input.
6320 int Idx = SVOp->getMaskElt(i+LaneStart);
6322 // the mask element does not index into any input vector.
6327 // The input vector this mask element indexes into.
6328 int Input = Idx / NumLaneElems;
6330 // Turn the index into an offset from the start of the input vector.
6331 Idx -= Input * NumLaneElems;
6333 // Find or create a shuffle vector operand to hold this input.
6335 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6336 if (InputUsed[OpNo] == Input)
6337 // This input vector is already an operand.
6339 if (InputUsed[OpNo] < 0) {
6340 // Create a new operand for this input vector.
6341 InputUsed[OpNo] = Input;
6346 if (OpNo >= array_lengthof(InputUsed)) {
6347 // More than two input vectors used! Give up on trying to create a
6348 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6349 UseBuildVector = true;
6353 // Add the mask index for the new shuffle vector.
6354 Mask.push_back(Idx + OpNo * NumLaneElems);
6357 if (UseBuildVector) {
6358 SmallVector<SDValue, 16> SVOps;
6359 for (unsigned i = 0; i != NumLaneElems; ++i) {
6360 // The mask element. This indexes into the input.
6361 int Idx = SVOp->getMaskElt(i+LaneStart);
6363 SVOps.push_back(DAG.getUNDEF(EltVT));
6367 // The input vector this mask element indexes into.
6368 int Input = Idx / NumElems;
6370 // Turn the index into an offset from the start of the input vector.
6371 Idx -= Input * NumElems;
6373 // Extract the vector element by hand.
6374 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6375 SVOp->getOperand(Input),
6376 DAG.getIntPtrConstant(Idx)));
6379 // Construct the output using a BUILD_VECTOR.
6380 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6382 } else if (InputUsed[0] < 0) {
6383 // No input vectors were used! The result is undefined.
6384 Output[l] = DAG.getUNDEF(NVT);
6386 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6387 (InputUsed[0] % 2) * NumLaneElems,
6389 // If only one input was used, use an undefined vector for the other.
6390 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6391 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6392 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6393 // At least one input vector was used. Create a new shuffle vector.
6394 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6400 // Concatenate the result back
6401 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6404 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6405 /// 4 elements, and match them with several different shuffle types.
6407 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6408 SDValue V1 = SVOp->getOperand(0);
6409 SDValue V2 = SVOp->getOperand(1);
6411 MVT VT = SVOp->getValueType(0).getSimpleVT();
6413 assert(VT.is128BitVector() && "Unsupported vector size");
6415 std::pair<int, int> Locs[4];
6416 int Mask1[] = { -1, -1, -1, -1 };
6417 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6421 for (unsigned i = 0; i != 4; ++i) {
6422 int Idx = PermMask[i];
6424 Locs[i] = std::make_pair(-1, -1);
6426 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6428 Locs[i] = std::make_pair(0, NumLo);
6432 Locs[i] = std::make_pair(1, NumHi);
6434 Mask1[2+NumHi] = Idx;
6440 if (NumLo <= 2 && NumHi <= 2) {
6441 // If no more than two elements come from either vector. This can be
6442 // implemented with two shuffles. First shuffle gather the elements.
6443 // The second shuffle, which takes the first shuffle as both of its
6444 // vector operands, put the elements into the right order.
6445 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6447 int Mask2[] = { -1, -1, -1, -1 };
6449 for (unsigned i = 0; i != 4; ++i)
6450 if (Locs[i].first != -1) {
6451 unsigned Idx = (i < 2) ? 0 : 4;
6452 Idx += Locs[i].first * 2 + Locs[i].second;
6456 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6459 if (NumLo == 3 || NumHi == 3) {
6460 // Otherwise, we must have three elements from one vector, call it X, and
6461 // one element from the other, call it Y. First, use a shufps to build an
6462 // intermediate vector with the one element from Y and the element from X
6463 // that will be in the same half in the final destination (the indexes don't
6464 // matter). Then, use a shufps to build the final vector, taking the half
6465 // containing the element from Y from the intermediate, and the other half
6468 // Normalize it so the 3 elements come from V1.
6469 CommuteVectorShuffleMask(PermMask, 4);
6473 // Find the element from V2.
6475 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6476 int Val = PermMask[HiIndex];
6483 Mask1[0] = PermMask[HiIndex];
6485 Mask1[2] = PermMask[HiIndex^1];
6487 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6490 Mask1[0] = PermMask[0];
6491 Mask1[1] = PermMask[1];
6492 Mask1[2] = HiIndex & 1 ? 6 : 4;
6493 Mask1[3] = HiIndex & 1 ? 4 : 6;
6494 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6497 Mask1[0] = HiIndex & 1 ? 2 : 0;
6498 Mask1[1] = HiIndex & 1 ? 0 : 2;
6499 Mask1[2] = PermMask[2];
6500 Mask1[3] = PermMask[3];
6505 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6508 // Break it into (shuffle shuffle_hi, shuffle_lo).
6509 int LoMask[] = { -1, -1, -1, -1 };
6510 int HiMask[] = { -1, -1, -1, -1 };
6512 int *MaskPtr = LoMask;
6513 unsigned MaskIdx = 0;
6516 for (unsigned i = 0; i != 4; ++i) {
6523 int Idx = PermMask[i];
6525 Locs[i] = std::make_pair(-1, -1);
6526 } else if (Idx < 4) {
6527 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6528 MaskPtr[LoIdx] = Idx;
6531 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6532 MaskPtr[HiIdx] = Idx;
6537 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6538 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6539 int MaskOps[] = { -1, -1, -1, -1 };
6540 for (unsigned i = 0; i != 4; ++i)
6541 if (Locs[i].first != -1)
6542 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6543 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6546 static bool MayFoldVectorLoad(SDValue V) {
6547 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6548 V = V.getOperand(0);
6550 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6551 V = V.getOperand(0);
6552 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6553 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6554 // BUILD_VECTOR (load), undef
6555 V = V.getOperand(0);
6557 return MayFoldLoad(V);
6561 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6562 EVT VT = Op.getValueType();
6564 // Canonizalize to v2f64.
6565 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6566 return DAG.getNode(ISD::BITCAST, dl, VT,
6567 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6572 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6574 SDValue V1 = Op.getOperand(0);
6575 SDValue V2 = Op.getOperand(1);
6576 EVT VT = Op.getValueType();
6578 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6580 if (HasSSE2 && VT == MVT::v2f64)
6581 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6583 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6584 return DAG.getNode(ISD::BITCAST, dl, VT,
6585 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6586 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6587 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6591 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6592 SDValue V1 = Op.getOperand(0);
6593 SDValue V2 = Op.getOperand(1);
6594 EVT VT = Op.getValueType();
6596 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6597 "unsupported shuffle type");
6599 if (V2.getOpcode() == ISD::UNDEF)
6603 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6607 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6608 SDValue V1 = Op.getOperand(0);
6609 SDValue V2 = Op.getOperand(1);
6610 EVT VT = Op.getValueType();
6611 unsigned NumElems = VT.getVectorNumElements();
6613 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6614 // operand of these instructions is only memory, so check if there's a
6615 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6617 bool CanFoldLoad = false;
6619 // Trivial case, when V2 comes from a load.
6620 if (MayFoldVectorLoad(V2))
6623 // When V1 is a load, it can be folded later into a store in isel, example:
6624 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6626 // (MOVLPSmr addr:$src1, VR128:$src2)
6627 // So, recognize this potential and also use MOVLPS or MOVLPD
6628 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6631 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6633 if (HasSSE2 && NumElems == 2)
6634 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6637 // If we don't care about the second element, proceed to use movss.
6638 if (SVOp->getMaskElt(1) != -1)
6639 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6642 // movl and movlp will both match v2i64, but v2i64 is never matched by
6643 // movl earlier because we make it strict to avoid messing with the movlp load
6644 // folding logic (see the code above getMOVLP call). Match it here then,
6645 // this is horrible, but will stay like this until we move all shuffle
6646 // matching to x86 specific nodes. Note that for the 1st condition all
6647 // types are matched with movsd.
6649 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6650 // as to remove this logic from here, as much as possible
6651 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6652 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6653 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6656 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6658 // Invert the operand order and use SHUFPS to match it.
6659 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6660 getShuffleSHUFImmediate(SVOp), DAG);
6663 // Reduce a vector shuffle to zext.
6665 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6666 // PMOVZX is only available from SSE41.
6667 if (!Subtarget->hasSSE41())
6670 EVT VT = Op.getValueType();
6672 // Only AVX2 support 256-bit vector integer extending.
6673 if (!Subtarget->hasInt256() && VT.is256BitVector())
6676 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6678 SDValue V1 = Op.getOperand(0);
6679 SDValue V2 = Op.getOperand(1);
6680 unsigned NumElems = VT.getVectorNumElements();
6682 // Extending is an unary operation and the element type of the source vector
6683 // won't be equal to or larger than i64.
6684 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6685 VT.getVectorElementType() == MVT::i64)
6688 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6689 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6690 while ((1U << Shift) < NumElems) {
6691 if (SVOp->getMaskElt(1U << Shift) == 1)
6694 // The maximal ratio is 8, i.e. from i8 to i64.
6699 // Check the shuffle mask.
6700 unsigned Mask = (1U << Shift) - 1;
6701 for (unsigned i = 0; i != NumElems; ++i) {
6702 int EltIdx = SVOp->getMaskElt(i);
6703 if ((i & Mask) != 0 && EltIdx != -1)
6705 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6709 LLVMContext *Context = DAG.getContext();
6710 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6711 EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6712 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6714 if (!isTypeLegal(NVT))
6717 // Simplify the operand as it's prepared to be fed into shuffle.
6718 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6719 if (V1.getOpcode() == ISD::BITCAST &&
6720 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6721 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6723 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6724 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6725 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6726 ConstantSDNode *CIdx =
6727 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6728 // If it's foldable, i.e. normal load with single use, we will let code
6729 // selection to fold it. Otherwise, we will short the conversion sequence.
6730 if (CIdx && CIdx->getZExtValue() == 0 &&
6731 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6732 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6733 // The "ext_vec_elt" node is wider than the result node.
6734 // In this case we should extract subvector from V.
6735 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6736 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6737 EVT FullVT = V.getValueType();
6738 EVT SubVecVT = EVT::getVectorVT(*Context,
6739 FullVT.getVectorElementType(),
6740 FullVT.getVectorNumElements()/Ratio);
6741 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6742 DAG.getIntPtrConstant(0));
6744 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6748 return DAG.getNode(ISD::BITCAST, DL, VT,
6749 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6753 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6754 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6755 MVT VT = Op.getValueType().getSimpleVT();
6757 SDValue V1 = Op.getOperand(0);
6758 SDValue V2 = Op.getOperand(1);
6760 if (isZeroShuffle(SVOp))
6761 return getZeroVector(VT, Subtarget, DAG, dl);
6763 // Handle splat operations
6764 if (SVOp->isSplat()) {
6765 // Use vbroadcast whenever the splat comes from a foldable load
6766 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6767 if (Broadcast.getNode())
6771 // Check integer expanding shuffles.
6772 SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6773 if (NewOp.getNode())
6776 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6778 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6779 VT == MVT::v16i16 || VT == MVT::v32i8) {
6780 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6781 if (NewOp.getNode())
6782 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6783 } else if ((VT == MVT::v4i32 ||
6784 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6785 // FIXME: Figure out a cleaner way to do this.
6786 // Try to make use of movq to zero out the top part.
6787 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6788 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6789 if (NewOp.getNode()) {
6790 MVT NewVT = NewOp.getValueType().getSimpleVT();
6791 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6792 NewVT, true, false))
6793 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6794 DAG, Subtarget, dl);
6796 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6797 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6798 if (NewOp.getNode()) {
6799 MVT NewVT = NewOp.getValueType().getSimpleVT();
6800 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6801 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6802 DAG, Subtarget, dl);
6810 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6811 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6812 SDValue V1 = Op.getOperand(0);
6813 SDValue V2 = Op.getOperand(1);
6814 MVT VT = Op.getValueType().getSimpleVT();
6816 unsigned NumElems = VT.getVectorNumElements();
6817 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6818 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6819 bool V1IsSplat = false;
6820 bool V2IsSplat = false;
6821 bool HasSSE2 = Subtarget->hasSSE2();
6822 bool HasFp256 = Subtarget->hasFp256();
6823 bool HasInt256 = Subtarget->hasInt256();
6824 MachineFunction &MF = DAG.getMachineFunction();
6825 bool OptForSize = MF.getFunction()->getAttributes().
6826 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6828 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6830 if (V1IsUndef && V2IsUndef)
6831 return DAG.getUNDEF(VT);
6833 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6835 // Vector shuffle lowering takes 3 steps:
6837 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6838 // narrowing and commutation of operands should be handled.
6839 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6841 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6842 // so the shuffle can be broken into other shuffles and the legalizer can
6843 // try the lowering again.
6845 // The general idea is that no vector_shuffle operation should be left to
6846 // be matched during isel, all of them must be converted to a target specific
6849 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6850 // narrowing and commutation of operands should be handled. The actual code
6851 // doesn't include all of those, work in progress...
6852 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6853 if (NewOp.getNode())
6856 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6858 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6859 // unpckh_undef). Only use pshufd if speed is more important than size.
6860 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6861 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6862 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6863 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6865 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6866 V2IsUndef && MayFoldVectorLoad(V1))
6867 return getMOVDDup(Op, dl, V1, DAG);
6869 if (isMOVHLPS_v_undef_Mask(M, VT))
6870 return getMOVHighToLow(Op, dl, DAG);
6872 // Use to match splats
6873 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6874 (VT == MVT::v2f64 || VT == MVT::v2i64))
6875 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6877 if (isPSHUFDMask(M, VT)) {
6878 // The actual implementation will match the mask in the if above and then
6879 // during isel it can match several different instructions, not only pshufd
6880 // as its name says, sad but true, emulate the behavior for now...
6881 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6882 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6884 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6886 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6887 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6889 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6890 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6893 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6897 if (isPALIGNRMask(M, VT, Subtarget))
6898 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6899 getShufflePALIGNRImmediate(SVOp),
6902 // Check if this can be converted into a logical shift.
6903 bool isLeft = false;
6906 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6907 if (isShift && ShVal.hasOneUse()) {
6908 // If the shifted value has multiple uses, it may be cheaper to use
6909 // v_set0 + movlhps or movhlps, etc.
6910 MVT EltVT = VT.getVectorElementType();
6911 ShAmt *= EltVT.getSizeInBits();
6912 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6915 if (isMOVLMask(M, VT)) {
6916 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6917 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6918 if (!isMOVLPMask(M, VT)) {
6919 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6920 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6922 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6923 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6927 // FIXME: fold these into legal mask.
6928 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6929 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6931 if (isMOVHLPSMask(M, VT))
6932 return getMOVHighToLow(Op, dl, DAG);
6934 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6935 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6937 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6938 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6940 if (isMOVLPMask(M, VT))
6941 return getMOVLP(Op, dl, DAG, HasSSE2);
6943 if (ShouldXformToMOVHLPS(M, VT) ||
6944 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6945 return CommuteVectorShuffle(SVOp, DAG);
6948 // No better options. Use a vshldq / vsrldq.
6949 MVT EltVT = VT.getVectorElementType();
6950 ShAmt *= EltVT.getSizeInBits();
6951 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6954 bool Commuted = false;
6955 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6956 // 1,1,1,1 -> v8i16 though.
6957 V1IsSplat = isSplatVector(V1.getNode());
6958 V2IsSplat = isSplatVector(V2.getNode());
6960 // Canonicalize the splat or undef, if present, to be on the RHS.
6961 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6962 CommuteVectorShuffleMask(M, NumElems);
6964 std::swap(V1IsSplat, V2IsSplat);
6968 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6969 // Shuffling low element of v1 into undef, just return v1.
6972 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6973 // the instruction selector will not match, so get a canonical MOVL with
6974 // swapped operands to undo the commute.
6975 return getMOVL(DAG, dl, VT, V2, V1);
6978 if (isUNPCKLMask(M, VT, HasInt256))
6979 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6981 if (isUNPCKHMask(M, VT, HasInt256))
6982 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6985 // Normalize mask so all entries that point to V2 points to its first
6986 // element then try to match unpck{h|l} again. If match, return a
6987 // new vector_shuffle with the corrected mask.p
6988 SmallVector<int, 8> NewMask(M.begin(), M.end());
6989 NormalizeMask(NewMask, NumElems);
6990 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6991 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6992 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6993 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6997 // Commute is back and try unpck* again.
6998 // FIXME: this seems wrong.
6999 CommuteVectorShuffleMask(M, NumElems);
7001 std::swap(V1IsSplat, V2IsSplat);
7004 if (isUNPCKLMask(M, VT, HasInt256))
7005 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7007 if (isUNPCKHMask(M, VT, HasInt256))
7008 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7011 // Normalize the node to match x86 shuffle ops if needed
7012 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7013 return CommuteVectorShuffle(SVOp, DAG);
7015 // The checks below are all present in isShuffleMaskLegal, but they are
7016 // inlined here right now to enable us to directly emit target specific
7017 // nodes, and remove one by one until they don't return Op anymore.
7019 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7020 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7021 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7022 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7025 if (isPSHUFHWMask(M, VT, HasInt256))
7026 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7027 getShufflePSHUFHWImmediate(SVOp),
7030 if (isPSHUFLWMask(M, VT, HasInt256))
7031 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7032 getShufflePSHUFLWImmediate(SVOp),
7035 if (isSHUFPMask(M, VT, HasFp256))
7036 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7037 getShuffleSHUFImmediate(SVOp), DAG);
7039 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7040 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7041 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7042 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7044 //===--------------------------------------------------------------------===//
7045 // Generate target specific nodes for 128 or 256-bit shuffles only
7046 // supported in the AVX instruction set.
7049 // Handle VMOVDDUPY permutations
7050 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7051 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7053 // Handle VPERMILPS/D* permutations
7054 if (isVPERMILPMask(M, VT, HasFp256)) {
7055 if (HasInt256 && VT == MVT::v8i32)
7056 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7057 getShuffleSHUFImmediate(SVOp), DAG);
7058 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7059 getShuffleSHUFImmediate(SVOp), DAG);
7062 // Handle VPERM2F128/VPERM2I128 permutations
7063 if (isVPERM2X128Mask(M, VT, HasFp256))
7064 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7065 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7067 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7068 if (BlendOp.getNode())
7071 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7072 SmallVector<SDValue, 8> permclMask;
7073 for (unsigned i = 0; i != 8; ++i) {
7074 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7076 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7078 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7079 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7080 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7083 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7084 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7085 getShuffleCLImmediate(SVOp), DAG);
7087 //===--------------------------------------------------------------------===//
7088 // Since no target specific shuffle was selected for this generic one,
7089 // lower it into other known shuffles. FIXME: this isn't true yet, but
7090 // this is the plan.
7093 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7094 if (VT == MVT::v8i16) {
7095 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7096 if (NewOp.getNode())
7100 if (VT == MVT::v16i8) {
7101 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7102 if (NewOp.getNode())
7106 if (VT == MVT::v32i8) {
7107 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7108 if (NewOp.getNode())
7112 // Handle all 128-bit wide vectors with 4 elements, and match them with
7113 // several different shuffle types.
7114 if (NumElems == 4 && VT.is128BitVector())
7115 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7117 // Handle general 256-bit shuffles
7118 if (VT.is256BitVector())
7119 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7124 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7125 MVT VT = Op.getValueType().getSimpleVT();
7128 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7131 if (VT.getSizeInBits() == 8) {
7132 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7133 Op.getOperand(0), Op.getOperand(1));
7134 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7135 DAG.getValueType(VT));
7136 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7139 if (VT.getSizeInBits() == 16) {
7140 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7141 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7143 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7144 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7145 DAG.getNode(ISD::BITCAST, dl,
7149 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7150 Op.getOperand(0), Op.getOperand(1));
7151 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7152 DAG.getValueType(VT));
7153 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7156 if (VT == MVT::f32) {
7157 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7158 // the result back to FR32 register. It's only worth matching if the
7159 // result has a single use which is a store or a bitcast to i32. And in
7160 // the case of a store, it's not worth it if the index is a constant 0,
7161 // because a MOVSSmr can be used instead, which is smaller and faster.
7162 if (!Op.hasOneUse())
7164 SDNode *User = *Op.getNode()->use_begin();
7165 if ((User->getOpcode() != ISD::STORE ||
7166 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7167 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7168 (User->getOpcode() != ISD::BITCAST ||
7169 User->getValueType(0) != MVT::i32))
7171 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7172 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7175 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7178 if (VT == MVT::i32 || VT == MVT::i64) {
7179 // ExtractPS/pextrq works with constant index.
7180 if (isa<ConstantSDNode>(Op.getOperand(1)))
7187 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7188 SelectionDAG &DAG) const {
7189 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7192 SDValue Vec = Op.getOperand(0);
7193 MVT VecVT = Vec.getValueType().getSimpleVT();
7195 // If this is a 256-bit vector result, first extract the 128-bit vector and
7196 // then extract the element from the 128-bit vector.
7197 if (VecVT.is256BitVector()) {
7198 SDLoc dl(Op.getNode());
7199 unsigned NumElems = VecVT.getVectorNumElements();
7200 SDValue Idx = Op.getOperand(1);
7201 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7203 // Get the 128-bit vector.
7204 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7206 if (IdxVal >= NumElems/2)
7207 IdxVal -= NumElems/2;
7208 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7209 DAG.getConstant(IdxVal, MVT::i32));
7212 assert(VecVT.is128BitVector() && "Unexpected vector length");
7214 if (Subtarget->hasSSE41()) {
7215 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7220 MVT VT = Op.getValueType().getSimpleVT();
7222 // TODO: handle v16i8.
7223 if (VT.getSizeInBits() == 16) {
7224 SDValue Vec = Op.getOperand(0);
7225 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7227 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7228 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7229 DAG.getNode(ISD::BITCAST, dl,
7232 // Transform it so it match pextrw which produces a 32-bit result.
7233 MVT EltVT = MVT::i32;
7234 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7235 Op.getOperand(0), Op.getOperand(1));
7236 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7237 DAG.getValueType(VT));
7238 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7241 if (VT.getSizeInBits() == 32) {
7242 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7246 // SHUFPS the element to the lowest double word, then movss.
7247 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7248 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7249 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7250 DAG.getUNDEF(VVT), Mask);
7251 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7252 DAG.getIntPtrConstant(0));
7255 if (VT.getSizeInBits() == 64) {
7256 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7257 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7258 // to match extract_elt for f64.
7259 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7263 // UNPCKHPD the element to the lowest double word, then movsd.
7264 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7265 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7266 int Mask[2] = { 1, -1 };
7267 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7268 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7269 DAG.getUNDEF(VVT), Mask);
7270 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7271 DAG.getIntPtrConstant(0));
7277 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7278 MVT VT = Op.getValueType().getSimpleVT();
7279 MVT EltVT = VT.getVectorElementType();
7282 SDValue N0 = Op.getOperand(0);
7283 SDValue N1 = Op.getOperand(1);
7284 SDValue N2 = Op.getOperand(2);
7286 if (!VT.is128BitVector())
7289 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7290 isa<ConstantSDNode>(N2)) {
7292 if (VT == MVT::v8i16)
7293 Opc = X86ISD::PINSRW;
7294 else if (VT == MVT::v16i8)
7295 Opc = X86ISD::PINSRB;
7297 Opc = X86ISD::PINSRB;
7299 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7301 if (N1.getValueType() != MVT::i32)
7302 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7303 if (N2.getValueType() != MVT::i32)
7304 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7305 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7308 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7309 // Bits [7:6] of the constant are the source select. This will always be
7310 // zero here. The DAG Combiner may combine an extract_elt index into these
7311 // bits. For example (insert (extract, 3), 2) could be matched by putting
7312 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7313 // Bits [5:4] of the constant are the destination select. This is the
7314 // value of the incoming immediate.
7315 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7316 // combine either bitwise AND or insert of float 0.0 to set these bits.
7317 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7318 // Create this as a scalar to vector..
7319 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7320 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7323 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7324 // PINSR* works with constant index.
7331 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7332 MVT VT = Op.getValueType().getSimpleVT();
7333 MVT EltVT = VT.getVectorElementType();
7336 SDValue N0 = Op.getOperand(0);
7337 SDValue N1 = Op.getOperand(1);
7338 SDValue N2 = Op.getOperand(2);
7340 // If this is a 256-bit vector result, first extract the 128-bit vector,
7341 // insert the element into the extracted half and then place it back.
7342 if (VT.is256BitVector()) {
7343 if (!isa<ConstantSDNode>(N2))
7346 // Get the desired 128-bit vector half.
7347 unsigned NumElems = VT.getVectorNumElements();
7348 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7349 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7351 // Insert the element into the desired half.
7352 bool Upper = IdxVal >= NumElems/2;
7353 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7354 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7356 // Insert the changed part back to the 256-bit vector
7357 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7360 if (Subtarget->hasSSE41())
7361 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7363 if (EltVT == MVT::i8)
7366 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7367 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7368 // as its second argument.
7369 if (N1.getValueType() != MVT::i32)
7370 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7371 if (N2.getValueType() != MVT::i32)
7372 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7373 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7378 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7379 LLVMContext *Context = DAG.getContext();
7381 MVT OpVT = Op.getValueType().getSimpleVT();
7383 // If this is a 256-bit vector result, first insert into a 128-bit
7384 // vector and then insert into the 256-bit vector.
7385 if (!OpVT.is128BitVector()) {
7386 // Insert into a 128-bit vector.
7387 EVT VT128 = EVT::getVectorVT(*Context,
7388 OpVT.getVectorElementType(),
7389 OpVT.getVectorNumElements() / 2);
7391 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7393 // Insert the 128-bit vector.
7394 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7397 if (OpVT == MVT::v1i64 &&
7398 Op.getOperand(0).getValueType() == MVT::i64)
7399 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7401 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7402 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7403 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7404 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7407 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7408 // a simple subregister reference or explicit instructions to grab
7409 // upper bits of a vector.
7410 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7411 SelectionDAG &DAG) {
7412 if (Subtarget->hasFp256()) {
7413 SDLoc dl(Op.getNode());
7414 SDValue Vec = Op.getNode()->getOperand(0);
7415 SDValue Idx = Op.getNode()->getOperand(1);
7417 if (Op.getNode()->getValueType(0).is128BitVector() &&
7418 Vec.getNode()->getValueType(0).is256BitVector() &&
7419 isa<ConstantSDNode>(Idx)) {
7420 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7421 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7427 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7428 // simple superregister reference or explicit instructions to insert
7429 // the upper bits of a vector.
7430 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7431 SelectionDAG &DAG) {
7432 if (Subtarget->hasFp256()) {
7433 SDLoc dl(Op.getNode());
7434 SDValue Vec = Op.getNode()->getOperand(0);
7435 SDValue SubVec = Op.getNode()->getOperand(1);
7436 SDValue Idx = Op.getNode()->getOperand(2);
7438 if (Op.getNode()->getValueType(0).is256BitVector() &&
7439 SubVec.getNode()->getValueType(0).is128BitVector() &&
7440 isa<ConstantSDNode>(Idx)) {
7441 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7442 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7448 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7449 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7450 // one of the above mentioned nodes. It has to be wrapped because otherwise
7451 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7452 // be used to form addressing mode. These wrapped nodes will be selected
7455 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7456 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7458 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7460 unsigned char OpFlag = 0;
7461 unsigned WrapperKind = X86ISD::Wrapper;
7462 CodeModel::Model M = getTargetMachine().getCodeModel();
7464 if (Subtarget->isPICStyleRIPRel() &&
7465 (M == CodeModel::Small || M == CodeModel::Kernel))
7466 WrapperKind = X86ISD::WrapperRIP;
7467 else if (Subtarget->isPICStyleGOT())
7468 OpFlag = X86II::MO_GOTOFF;
7469 else if (Subtarget->isPICStyleStubPIC())
7470 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7472 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7474 CP->getOffset(), OpFlag);
7476 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7477 // With PIC, the address is actually $g + Offset.
7479 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7480 DAG.getNode(X86ISD::GlobalBaseReg,
7481 SDLoc(), getPointerTy()),
7488 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7489 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7491 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7493 unsigned char OpFlag = 0;
7494 unsigned WrapperKind = X86ISD::Wrapper;
7495 CodeModel::Model M = getTargetMachine().getCodeModel();
7497 if (Subtarget->isPICStyleRIPRel() &&
7498 (M == CodeModel::Small || M == CodeModel::Kernel))
7499 WrapperKind = X86ISD::WrapperRIP;
7500 else if (Subtarget->isPICStyleGOT())
7501 OpFlag = X86II::MO_GOTOFF;
7502 else if (Subtarget->isPICStyleStubPIC())
7503 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7505 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7508 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7510 // With PIC, the address is actually $g + Offset.
7512 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7513 DAG.getNode(X86ISD::GlobalBaseReg,
7514 SDLoc(), getPointerTy()),
7521 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7522 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7524 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7526 unsigned char OpFlag = 0;
7527 unsigned WrapperKind = X86ISD::Wrapper;
7528 CodeModel::Model M = getTargetMachine().getCodeModel();
7530 if (Subtarget->isPICStyleRIPRel() &&
7531 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7532 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7533 OpFlag = X86II::MO_GOTPCREL;
7534 WrapperKind = X86ISD::WrapperRIP;
7535 } else if (Subtarget->isPICStyleGOT()) {
7536 OpFlag = X86II::MO_GOT;
7537 } else if (Subtarget->isPICStyleStubPIC()) {
7538 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7539 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7540 OpFlag = X86II::MO_DARWIN_NONLAZY;
7543 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7546 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7548 // With PIC, the address is actually $g + Offset.
7549 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7550 !Subtarget->is64Bit()) {
7551 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7552 DAG.getNode(X86ISD::GlobalBaseReg,
7553 SDLoc(), getPointerTy()),
7557 // For symbols that require a load from a stub to get the address, emit the
7559 if (isGlobalStubReference(OpFlag))
7560 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7561 MachinePointerInfo::getGOT(), false, false, false, 0);
7567 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7568 // Create the TargetBlockAddressAddress node.
7569 unsigned char OpFlags =
7570 Subtarget->ClassifyBlockAddressReference();
7571 CodeModel::Model M = getTargetMachine().getCodeModel();
7572 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7573 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7575 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7578 if (Subtarget->isPICStyleRIPRel() &&
7579 (M == CodeModel::Small || M == CodeModel::Kernel))
7580 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7582 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7584 // With PIC, the address is actually $g + Offset.
7585 if (isGlobalRelativeToPICBase(OpFlags)) {
7586 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7587 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7595 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7596 int64_t Offset, SelectionDAG &DAG) const {
7597 // Create the TargetGlobalAddress node, folding in the constant
7598 // offset if it is legal.
7599 unsigned char OpFlags =
7600 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7601 CodeModel::Model M = getTargetMachine().getCodeModel();
7603 if (OpFlags == X86II::MO_NO_FLAG &&
7604 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7605 // A direct static reference to a global.
7606 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7609 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7612 if (Subtarget->isPICStyleRIPRel() &&
7613 (M == CodeModel::Small || M == CodeModel::Kernel))
7614 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7616 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7618 // With PIC, the address is actually $g + Offset.
7619 if (isGlobalRelativeToPICBase(OpFlags)) {
7620 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7621 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7625 // For globals that require a load from a stub to get the address, emit the
7627 if (isGlobalStubReference(OpFlags))
7628 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7629 MachinePointerInfo::getGOT(), false, false, false, 0);
7631 // If there was a non-zero offset that we didn't fold, create an explicit
7634 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7635 DAG.getConstant(Offset, getPointerTy()));
7641 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7642 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7643 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7644 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7648 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7649 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7650 unsigned char OperandFlags, bool LocalDynamic = false) {
7651 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7652 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7654 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7655 GA->getValueType(0),
7659 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7663 SDValue Ops[] = { Chain, TGA, *InFlag };
7664 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7666 SDValue Ops[] = { Chain, TGA };
7667 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7670 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7671 MFI->setAdjustsStack(true);
7673 SDValue Flag = Chain.getValue(1);
7674 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7677 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7679 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7682 SDLoc dl(GA); // ? function entry point might be better
7683 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7684 DAG.getNode(X86ISD::GlobalBaseReg,
7685 SDLoc(), PtrVT), InFlag);
7686 InFlag = Chain.getValue(1);
7688 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7691 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7693 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7695 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7696 X86::RAX, X86II::MO_TLSGD);
7699 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7705 // Get the start address of the TLS block for this module.
7706 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7707 .getInfo<X86MachineFunctionInfo>();
7708 MFI->incNumLocalDynamicTLSAccesses();
7712 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7713 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7716 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7717 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7718 InFlag = Chain.getValue(1);
7719 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7720 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7723 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7727 unsigned char OperandFlags = X86II::MO_DTPOFF;
7728 unsigned WrapperKind = X86ISD::Wrapper;
7729 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7730 GA->getValueType(0),
7731 GA->getOffset(), OperandFlags);
7732 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7734 // Add x@dtpoff with the base.
7735 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7738 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7739 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7740 const EVT PtrVT, TLSModel::Model model,
7741 bool is64Bit, bool isPIC) {
7744 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7745 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7746 is64Bit ? 257 : 256));
7748 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7749 DAG.getIntPtrConstant(0),
7750 MachinePointerInfo(Ptr),
7751 false, false, false, 0);
7753 unsigned char OperandFlags = 0;
7754 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7756 unsigned WrapperKind = X86ISD::Wrapper;
7757 if (model == TLSModel::LocalExec) {
7758 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7759 } else if (model == TLSModel::InitialExec) {
7761 OperandFlags = X86II::MO_GOTTPOFF;
7762 WrapperKind = X86ISD::WrapperRIP;
7764 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7767 llvm_unreachable("Unexpected model");
7770 // emit "addl x@ntpoff,%eax" (local exec)
7771 // or "addl x@indntpoff,%eax" (initial exec)
7772 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7773 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7774 GA->getValueType(0),
7775 GA->getOffset(), OperandFlags);
7776 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7778 if (model == TLSModel::InitialExec) {
7779 if (isPIC && !is64Bit) {
7780 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7781 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
7785 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7786 MachinePointerInfo::getGOT(), false, false, false,
7790 // The address of the thread local variable is the add of the thread
7791 // pointer with the offset of the variable.
7792 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7796 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7798 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7799 const GlobalValue *GV = GA->getGlobal();
7801 if (Subtarget->isTargetELF()) {
7802 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7805 case TLSModel::GeneralDynamic:
7806 if (Subtarget->is64Bit())
7807 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7808 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7809 case TLSModel::LocalDynamic:
7810 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7811 Subtarget->is64Bit());
7812 case TLSModel::InitialExec:
7813 case TLSModel::LocalExec:
7814 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7815 Subtarget->is64Bit(),
7816 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7818 llvm_unreachable("Unknown TLS model.");
7821 if (Subtarget->isTargetDarwin()) {
7822 // Darwin only has one model of TLS. Lower to that.
7823 unsigned char OpFlag = 0;
7824 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7825 X86ISD::WrapperRIP : X86ISD::Wrapper;
7827 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7829 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7830 !Subtarget->is64Bit();
7832 OpFlag = X86II::MO_TLVP_PIC_BASE;
7834 OpFlag = X86II::MO_TLVP;
7836 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7837 GA->getValueType(0),
7838 GA->getOffset(), OpFlag);
7839 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7841 // With PIC32, the address is actually $g + Offset.
7843 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7844 DAG.getNode(X86ISD::GlobalBaseReg,
7845 SDLoc(), getPointerTy()),
7848 // Lowering the machine isd will make sure everything is in the right
7850 SDValue Chain = DAG.getEntryNode();
7851 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7852 SDValue Args[] = { Chain, Offset };
7853 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7855 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7856 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7857 MFI->setAdjustsStack(true);
7859 // And our return value (tls address) is in the standard call return value
7861 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7862 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7866 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7867 // Just use the implicit TLS architecture
7868 // Need to generate someting similar to:
7869 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7871 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7872 // mov rcx, qword [rdx+rcx*8]
7873 // mov eax, .tls$:tlsvar
7874 // [rax+rcx] contains the address
7875 // Windows 64bit: gs:0x58
7876 // Windows 32bit: fs:__tls_array
7878 // If GV is an alias then use the aliasee for determining
7879 // thread-localness.
7880 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7881 GV = GA->resolveAliasedGlobal(false);
7883 SDValue Chain = DAG.getEntryNode();
7885 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7886 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7887 // use its literal value of 0x2C.
7888 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7889 ? Type::getInt8PtrTy(*DAG.getContext(),
7891 : Type::getInt32PtrTy(*DAG.getContext(),
7894 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7895 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7896 DAG.getExternalSymbol("_tls_array", getPointerTy()));
7898 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7899 MachinePointerInfo(Ptr),
7900 false, false, false, 0);
7902 // Load the _tls_index variable
7903 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7904 if (Subtarget->is64Bit())
7905 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7906 IDX, MachinePointerInfo(), MVT::i32,
7909 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7910 false, false, false, 0);
7912 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7914 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7916 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7917 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7918 false, false, false, 0);
7920 // Get the offset of start of .tls section
7921 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7922 GA->getValueType(0),
7923 GA->getOffset(), X86II::MO_SECREL);
7924 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7926 // The address of the thread local variable is the add of the thread
7927 // pointer with the offset of the variable.
7928 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7931 llvm_unreachable("TLS not implemented for this target.");
7934 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7935 /// and take a 2 x i32 value to shift plus a shift amount.
7936 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7937 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7938 EVT VT = Op.getValueType();
7939 unsigned VTBits = VT.getSizeInBits();
7941 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7942 SDValue ShOpLo = Op.getOperand(0);
7943 SDValue ShOpHi = Op.getOperand(1);
7944 SDValue ShAmt = Op.getOperand(2);
7945 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7946 DAG.getConstant(VTBits - 1, MVT::i8))
7947 : DAG.getConstant(0, VT);
7950 if (Op.getOpcode() == ISD::SHL_PARTS) {
7951 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7952 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7954 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7955 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7958 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7959 DAG.getConstant(VTBits, MVT::i8));
7960 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7961 AndNode, DAG.getConstant(0, MVT::i8));
7964 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7965 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7966 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7968 if (Op.getOpcode() == ISD::SHL_PARTS) {
7969 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7970 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7972 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7973 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7976 SDValue Ops[2] = { Lo, Hi };
7977 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7980 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7981 SelectionDAG &DAG) const {
7982 EVT SrcVT = Op.getOperand(0).getValueType();
7984 if (SrcVT.isVector())
7987 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7988 "Unknown SINT_TO_FP to lower!");
7990 // These are really Legal; return the operand so the caller accepts it as
7992 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7994 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7995 Subtarget->is64Bit()) {
8000 unsigned Size = SrcVT.getSizeInBits()/8;
8001 MachineFunction &MF = DAG.getMachineFunction();
8002 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8003 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8004 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8006 MachinePointerInfo::getFixedStack(SSFI),
8008 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8011 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8013 SelectionDAG &DAG) const {
8017 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8019 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8021 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8023 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8025 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8026 MachineMemOperand *MMO;
8028 int SSFI = FI->getIndex();
8030 DAG.getMachineFunction()
8031 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8032 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8034 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8035 StackSlot = StackSlot.getOperand(1);
8037 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8038 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8040 Tys, Ops, array_lengthof(Ops),
8044 Chain = Result.getValue(1);
8045 SDValue InFlag = Result.getValue(2);
8047 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8048 // shouldn't be necessary except that RFP cannot be live across
8049 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8050 MachineFunction &MF = DAG.getMachineFunction();
8051 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8052 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8053 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8054 Tys = DAG.getVTList(MVT::Other);
8056 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8058 MachineMemOperand *MMO =
8059 DAG.getMachineFunction()
8060 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8061 MachineMemOperand::MOStore, SSFISize, SSFISize);
8063 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8064 Ops, array_lengthof(Ops),
8065 Op.getValueType(), MMO);
8066 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8067 MachinePointerInfo::getFixedStack(SSFI),
8068 false, false, false, 0);
8074 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8075 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8076 SelectionDAG &DAG) const {
8077 // This algorithm is not obvious. Here it is what we're trying to output:
8080 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8081 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8085 pshufd $0x4e, %xmm0, %xmm1
8091 LLVMContext *Context = DAG.getContext();
8093 // Build some magic constants.
8094 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8095 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8096 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8098 SmallVector<Constant*,2> CV1;
8100 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8101 APInt(64, 0x4330000000000000ULL))));
8103 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8104 APInt(64, 0x4530000000000000ULL))));
8105 Constant *C1 = ConstantVector::get(CV1);
8106 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8108 // Load the 64-bit value into an XMM register.
8109 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8111 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8112 MachinePointerInfo::getConstantPool(),
8113 false, false, false, 16);
8114 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8115 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8118 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8119 MachinePointerInfo::getConstantPool(),
8120 false, false, false, 16);
8121 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8122 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8125 if (Subtarget->hasSSE3()) {
8126 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8127 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8129 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8130 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8132 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8133 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8137 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8138 DAG.getIntPtrConstant(0));
8141 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8142 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8143 SelectionDAG &DAG) const {
8145 // FP constant to bias correct the final result.
8146 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8149 // Load the 32-bit value into an XMM register.
8150 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8153 // Zero out the upper parts of the register.
8154 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8156 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8157 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8158 DAG.getIntPtrConstant(0));
8160 // Or the load with the bias.
8161 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8162 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8163 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8165 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8166 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8167 MVT::v2f64, Bias)));
8168 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8169 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8170 DAG.getIntPtrConstant(0));
8172 // Subtract the bias.
8173 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8175 // Handle final rounding.
8176 EVT DestVT = Op.getValueType();
8178 if (DestVT.bitsLT(MVT::f64))
8179 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8180 DAG.getIntPtrConstant(0));
8181 if (DestVT.bitsGT(MVT::f64))
8182 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8184 // Handle final rounding.
8188 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8189 SelectionDAG &DAG) const {
8190 SDValue N0 = Op.getOperand(0);
8191 EVT SVT = N0.getValueType();
8194 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8195 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8196 "Custom UINT_TO_FP is not supported!");
8198 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8199 SVT.getVectorNumElements());
8200 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8201 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8204 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8205 SelectionDAG &DAG) const {
8206 SDValue N0 = Op.getOperand(0);
8209 if (Op.getValueType().isVector())
8210 return lowerUINT_TO_FP_vec(Op, DAG);
8212 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8213 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8214 // the optimization here.
8215 if (DAG.SignBitIsZero(N0))
8216 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8218 EVT SrcVT = N0.getValueType();
8219 EVT DstVT = Op.getValueType();
8220 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8221 return LowerUINT_TO_FP_i64(Op, DAG);
8222 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8223 return LowerUINT_TO_FP_i32(Op, DAG);
8224 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8227 // Make a 64-bit buffer, and use it to build an FILD.
8228 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8229 if (SrcVT == MVT::i32) {
8230 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8231 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8232 getPointerTy(), StackSlot, WordOff);
8233 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8234 StackSlot, MachinePointerInfo(),
8236 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8237 OffsetSlot, MachinePointerInfo(),
8239 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8243 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8244 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8245 StackSlot, MachinePointerInfo(),
8247 // For i64 source, we need to add the appropriate power of 2 if the input
8248 // was negative. This is the same as the optimization in
8249 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8250 // we must be careful to do the computation in x87 extended precision, not
8251 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8252 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8253 MachineMemOperand *MMO =
8254 DAG.getMachineFunction()
8255 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8256 MachineMemOperand::MOLoad, 8, 8);
8258 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8259 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8260 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8261 array_lengthof(Ops), MVT::i64, MMO);
8263 APInt FF(32, 0x5F800000ULL);
8265 // Check whether the sign bit is set.
8266 SDValue SignSet = DAG.getSetCC(dl,
8267 getSetCCResultType(*DAG.getContext(), MVT::i64),
8268 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8271 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8272 SDValue FudgePtr = DAG.getConstantPool(
8273 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8276 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8277 SDValue Zero = DAG.getIntPtrConstant(0);
8278 SDValue Four = DAG.getIntPtrConstant(4);
8279 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8281 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8283 // Load the value out, extending it from f32 to f80.
8284 // FIXME: Avoid the extend by constructing the right constant pool?
8285 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8286 FudgePtr, MachinePointerInfo::getConstantPool(),
8287 MVT::f32, false, false, 4);
8288 // Extend everything to 80 bits to force it to be done on x87.
8289 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8290 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8293 std::pair<SDValue,SDValue>
8294 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8295 bool IsSigned, bool IsReplace) const {
8298 EVT DstTy = Op.getValueType();
8300 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8301 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8305 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8306 DstTy.getSimpleVT() >= MVT::i16 &&
8307 "Unknown FP_TO_INT to lower!");
8309 // These are really Legal.
8310 if (DstTy == MVT::i32 &&
8311 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8312 return std::make_pair(SDValue(), SDValue());
8313 if (Subtarget->is64Bit() &&
8314 DstTy == MVT::i64 &&
8315 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8316 return std::make_pair(SDValue(), SDValue());
8318 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8319 // stack slot, or into the FTOL runtime function.
8320 MachineFunction &MF = DAG.getMachineFunction();
8321 unsigned MemSize = DstTy.getSizeInBits()/8;
8322 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8323 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8326 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8327 Opc = X86ISD::WIN_FTOL;
8329 switch (DstTy.getSimpleVT().SimpleTy) {
8330 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8331 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8332 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8333 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8336 SDValue Chain = DAG.getEntryNode();
8337 SDValue Value = Op.getOperand(0);
8338 EVT TheVT = Op.getOperand(0).getValueType();
8339 // FIXME This causes a redundant load/store if the SSE-class value is already
8340 // in memory, such as if it is on the callstack.
8341 if (isScalarFPTypeInSSEReg(TheVT)) {
8342 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8343 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8344 MachinePointerInfo::getFixedStack(SSFI),
8346 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8348 Chain, StackSlot, DAG.getValueType(TheVT)
8351 MachineMemOperand *MMO =
8352 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8353 MachineMemOperand::MOLoad, MemSize, MemSize);
8354 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8355 array_lengthof(Ops), DstTy, MMO);
8356 Chain = Value.getValue(1);
8357 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8358 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8361 MachineMemOperand *MMO =
8362 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8363 MachineMemOperand::MOStore, MemSize, MemSize);
8365 if (Opc != X86ISD::WIN_FTOL) {
8366 // Build the FP_TO_INT*_IN_MEM
8367 SDValue Ops[] = { Chain, Value, StackSlot };
8368 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8369 Ops, array_lengthof(Ops), DstTy,
8371 return std::make_pair(FIST, StackSlot);
8373 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8374 DAG.getVTList(MVT::Other, MVT::Glue),
8376 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8377 MVT::i32, ftol.getValue(1));
8378 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8379 MVT::i32, eax.getValue(2));
8380 SDValue Ops[] = { eax, edx };
8381 SDValue pair = IsReplace
8382 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8383 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8384 return std::make_pair(pair, SDValue());
8388 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8389 const X86Subtarget *Subtarget) {
8390 MVT VT = Op->getValueType(0).getSimpleVT();
8391 SDValue In = Op->getOperand(0);
8392 MVT InVT = In.getValueType().getSimpleVT();
8395 // Optimize vectors in AVX mode:
8398 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8399 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8400 // Concat upper and lower parts.
8403 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8404 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8405 // Concat upper and lower parts.
8408 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8409 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8412 if (Subtarget->hasInt256())
8413 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8415 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8416 SDValue Undef = DAG.getUNDEF(InVT);
8417 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8418 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8419 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8421 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8422 VT.getVectorNumElements()/2);
8424 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8425 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8427 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8430 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8431 SelectionDAG &DAG) const {
8432 if (Subtarget->hasFp256()) {
8433 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8440 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8441 SelectionDAG &DAG) const {
8443 MVT VT = Op.getValueType().getSimpleVT();
8444 SDValue In = Op.getOperand(0);
8445 MVT SVT = In.getValueType().getSimpleVT();
8447 if (Subtarget->hasFp256()) {
8448 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8453 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8454 VT.getVectorNumElements() != SVT.getVectorNumElements())
8457 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8459 // AVX2 has better support of integer extending.
8460 if (Subtarget->hasInt256())
8461 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8463 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8464 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8465 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8466 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8467 DAG.getUNDEF(MVT::v8i16),
8470 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8473 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8475 MVT VT = Op.getValueType().getSimpleVT();
8476 SDValue In = Op.getOperand(0);
8477 MVT SVT = In.getValueType().getSimpleVT();
8479 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8480 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8481 if (Subtarget->hasInt256()) {
8482 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8483 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8484 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8486 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8487 DAG.getIntPtrConstant(0));
8490 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8491 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8492 DAG.getIntPtrConstant(0));
8493 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8494 DAG.getIntPtrConstant(2));
8496 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8497 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8500 static const int ShufMask1[] = {0, 2, 0, 0};
8501 SDValue Undef = DAG.getUNDEF(VT);
8502 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8503 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8505 // The MOVLHPS mask:
8506 static const int ShufMask2[] = {0, 1, 4, 5};
8507 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8510 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8511 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8512 if (Subtarget->hasInt256()) {
8513 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8515 SmallVector<SDValue,32> pshufbMask;
8516 for (unsigned i = 0; i < 2; ++i) {
8517 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8518 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8519 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8520 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8521 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8522 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8523 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8524 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8525 for (unsigned j = 0; j < 8; ++j)
8526 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8528 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8529 &pshufbMask[0], 32);
8530 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8531 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8533 static const int ShufMask[] = {0, 2, -1, -1};
8534 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8536 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8537 DAG.getIntPtrConstant(0));
8538 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8541 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8542 DAG.getIntPtrConstant(0));
8544 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8545 DAG.getIntPtrConstant(4));
8547 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8548 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8551 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8552 -1, -1, -1, -1, -1, -1, -1, -1};
8554 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8555 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8556 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8558 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8559 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8561 // The MOVLHPS Mask:
8562 static const int ShufMask2[] = {0, 1, 4, 5};
8563 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8564 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8567 // Handle truncation of V256 to V128 using shuffles.
8568 if (!VT.is128BitVector() || !SVT.is256BitVector())
8571 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8573 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8575 unsigned NumElems = VT.getVectorNumElements();
8576 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8579 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8580 // Prepare truncation shuffle mask
8581 for (unsigned i = 0; i != NumElems; ++i)
8583 SDValue V = DAG.getVectorShuffle(NVT, DL,
8584 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8585 DAG.getUNDEF(NVT), &MaskVec[0]);
8586 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8587 DAG.getIntPtrConstant(0));
8590 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8591 SelectionDAG &DAG) const {
8592 MVT VT = Op.getValueType().getSimpleVT();
8593 if (VT.isVector()) {
8594 if (VT == MVT::v8i16)
8595 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8596 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8597 MVT::v8i32, Op.getOperand(0)));
8601 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8602 /*IsSigned=*/ true, /*IsReplace=*/ false);
8603 SDValue FIST = Vals.first, StackSlot = Vals.second;
8604 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8605 if (FIST.getNode() == 0) return Op;
8607 if (StackSlot.getNode())
8609 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8610 FIST, StackSlot, MachinePointerInfo(),
8611 false, false, false, 0);
8613 // The node is the result.
8617 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8618 SelectionDAG &DAG) const {
8619 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8620 /*IsSigned=*/ false, /*IsReplace=*/ false);
8621 SDValue FIST = Vals.first, StackSlot = Vals.second;
8622 assert(FIST.getNode() && "Unexpected failure");
8624 if (StackSlot.getNode())
8626 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8627 FIST, StackSlot, MachinePointerInfo(),
8628 false, false, false, 0);
8630 // The node is the result.
8634 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8636 MVT VT = Op.getValueType().getSimpleVT();
8637 SDValue In = Op.getOperand(0);
8638 MVT SVT = In.getValueType().getSimpleVT();
8640 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8642 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8643 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8644 In, DAG.getUNDEF(SVT)));
8647 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8648 LLVMContext *Context = DAG.getContext();
8650 MVT VT = Op.getValueType().getSimpleVT();
8652 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8653 if (VT.isVector()) {
8654 EltVT = VT.getVectorElementType();
8655 NumElts = VT.getVectorNumElements();
8658 if (EltVT == MVT::f64)
8659 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8660 APInt(64, ~(1ULL << 63))));
8662 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8663 APInt(32, ~(1U << 31))));
8664 C = ConstantVector::getSplat(NumElts, C);
8665 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8666 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8667 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8668 MachinePointerInfo::getConstantPool(),
8669 false, false, false, Alignment);
8670 if (VT.isVector()) {
8671 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8672 return DAG.getNode(ISD::BITCAST, dl, VT,
8673 DAG.getNode(ISD::AND, dl, ANDVT,
8674 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8676 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8678 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8681 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8682 LLVMContext *Context = DAG.getContext();
8684 MVT VT = Op.getValueType().getSimpleVT();
8686 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8687 if (VT.isVector()) {
8688 EltVT = VT.getVectorElementType();
8689 NumElts = VT.getVectorNumElements();
8692 if (EltVT == MVT::f64)
8693 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8694 APInt(64, 1ULL << 63)));
8696 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8697 APInt(32, 1U << 31)));
8698 C = ConstantVector::getSplat(NumElts, C);
8699 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8700 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8701 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8702 MachinePointerInfo::getConstantPool(),
8703 false, false, false, Alignment);
8704 if (VT.isVector()) {
8705 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8706 return DAG.getNode(ISD::BITCAST, dl, VT,
8707 DAG.getNode(ISD::XOR, dl, XORVT,
8708 DAG.getNode(ISD::BITCAST, dl, XORVT,
8710 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8713 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8716 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8717 LLVMContext *Context = DAG.getContext();
8718 SDValue Op0 = Op.getOperand(0);
8719 SDValue Op1 = Op.getOperand(1);
8721 MVT VT = Op.getValueType().getSimpleVT();
8722 MVT SrcVT = Op1.getValueType().getSimpleVT();
8724 // If second operand is smaller, extend it first.
8725 if (SrcVT.bitsLT(VT)) {
8726 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8729 // And if it is bigger, shrink it first.
8730 if (SrcVT.bitsGT(VT)) {
8731 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8735 // At this point the operands and the result should have the same
8736 // type, and that won't be f80 since that is not custom lowered.
8738 // First get the sign bit of second operand.
8739 SmallVector<Constant*,4> CV;
8740 if (SrcVT == MVT::f64) {
8741 const fltSemantics &Sem = APFloat::IEEEdouble;
8742 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8743 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8745 const fltSemantics &Sem = APFloat::IEEEsingle;
8746 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8747 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8748 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8749 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8751 Constant *C = ConstantVector::get(CV);
8752 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8753 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8754 MachinePointerInfo::getConstantPool(),
8755 false, false, false, 16);
8756 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8758 // Shift sign bit right or left if the two operands have different types.
8759 if (SrcVT.bitsGT(VT)) {
8760 // Op0 is MVT::f32, Op1 is MVT::f64.
8761 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8762 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8763 DAG.getConstant(32, MVT::i32));
8764 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8765 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8766 DAG.getIntPtrConstant(0));
8769 // Clear first operand sign bit.
8771 if (VT == MVT::f64) {
8772 const fltSemantics &Sem = APFloat::IEEEdouble;
8773 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8774 APInt(64, ~(1ULL << 63)))));
8775 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8777 const fltSemantics &Sem = APFloat::IEEEsingle;
8778 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8779 APInt(32, ~(1U << 31)))));
8780 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8781 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8782 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8784 C = ConstantVector::get(CV);
8785 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8786 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8787 MachinePointerInfo::getConstantPool(),
8788 false, false, false, 16);
8789 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8791 // Or the value with the sign bit.
8792 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8795 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8796 SDValue N0 = Op.getOperand(0);
8798 MVT VT = Op.getValueType().getSimpleVT();
8800 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8801 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8802 DAG.getConstant(1, VT));
8803 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8806 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8808 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8809 SelectionDAG &DAG) const {
8810 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8812 if (!Subtarget->hasSSE41())
8815 if (!Op->hasOneUse())
8818 SDNode *N = Op.getNode();
8821 SmallVector<SDValue, 8> Opnds;
8822 DenseMap<SDValue, unsigned> VecInMap;
8823 EVT VT = MVT::Other;
8825 // Recognize a special case where a vector is casted into wide integer to
8827 Opnds.push_back(N->getOperand(0));
8828 Opnds.push_back(N->getOperand(1));
8830 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8831 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8832 // BFS traverse all OR'd operands.
8833 if (I->getOpcode() == ISD::OR) {
8834 Opnds.push_back(I->getOperand(0));
8835 Opnds.push_back(I->getOperand(1));
8836 // Re-evaluate the number of nodes to be traversed.
8837 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8841 // Quit if a non-EXTRACT_VECTOR_ELT
8842 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8845 // Quit if without a constant index.
8846 SDValue Idx = I->getOperand(1);
8847 if (!isa<ConstantSDNode>(Idx))
8850 SDValue ExtractedFromVec = I->getOperand(0);
8851 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8852 if (M == VecInMap.end()) {
8853 VT = ExtractedFromVec.getValueType();
8854 // Quit if not 128/256-bit vector.
8855 if (!VT.is128BitVector() && !VT.is256BitVector())
8857 // Quit if not the same type.
8858 if (VecInMap.begin() != VecInMap.end() &&
8859 VT != VecInMap.begin()->first.getValueType())
8861 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8863 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8866 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8867 "Not extracted from 128-/256-bit vector.");
8869 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8870 SmallVector<SDValue, 8> VecIns;
8872 for (DenseMap<SDValue, unsigned>::const_iterator
8873 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8874 // Quit if not all elements are used.
8875 if (I->second != FullMask)
8877 VecIns.push_back(I->first);
8880 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8882 // Cast all vectors into TestVT for PTEST.
8883 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8884 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8886 // If more than one full vectors are evaluated, OR them first before PTEST.
8887 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8888 // Each iteration will OR 2 nodes and append the result until there is only
8889 // 1 node left, i.e. the final OR'd value of all vectors.
8890 SDValue LHS = VecIns[Slot];
8891 SDValue RHS = VecIns[Slot + 1];
8892 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8895 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8896 VecIns.back(), VecIns.back());
8899 /// Emit nodes that will be selected as "test Op0,Op0", or something
8901 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8902 SelectionDAG &DAG) const {
8905 // CF and OF aren't always set the way we want. Determine which
8906 // of these we need.
8907 bool NeedCF = false;
8908 bool NeedOF = false;
8911 case X86::COND_A: case X86::COND_AE:
8912 case X86::COND_B: case X86::COND_BE:
8915 case X86::COND_G: case X86::COND_GE:
8916 case X86::COND_L: case X86::COND_LE:
8917 case X86::COND_O: case X86::COND_NO:
8922 // See if we can use the EFLAGS value from the operand instead of
8923 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8924 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8925 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8926 // Emit a CMP with 0, which is the TEST pattern.
8927 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8928 DAG.getConstant(0, Op.getValueType()));
8930 unsigned Opcode = 0;
8931 unsigned NumOperands = 0;
8933 // Truncate operations may prevent the merge of the SETCC instruction
8934 // and the arithmetic intruction before it. Attempt to truncate the operands
8935 // of the arithmetic instruction and use a reduced bit-width instruction.
8936 bool NeedTruncation = false;
8937 SDValue ArithOp = Op;
8938 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8939 SDValue Arith = Op->getOperand(0);
8940 // Both the trunc and the arithmetic op need to have one user each.
8941 if (Arith->hasOneUse())
8942 switch (Arith.getOpcode()) {
8949 NeedTruncation = true;
8955 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8956 // which may be the result of a CAST. We use the variable 'Op', which is the
8957 // non-casted variable when we check for possible users.
8958 switch (ArithOp.getOpcode()) {
8960 // Due to an isel shortcoming, be conservative if this add is likely to be
8961 // selected as part of a load-modify-store instruction. When the root node
8962 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8963 // uses of other nodes in the match, such as the ADD in this case. This
8964 // leads to the ADD being left around and reselected, with the result being
8965 // two adds in the output. Alas, even if none our users are stores, that
8966 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8967 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8968 // climbing the DAG back to the root, and it doesn't seem to be worth the
8970 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8971 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8972 if (UI->getOpcode() != ISD::CopyToReg &&
8973 UI->getOpcode() != ISD::SETCC &&
8974 UI->getOpcode() != ISD::STORE)
8977 if (ConstantSDNode *C =
8978 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8979 // An add of one will be selected as an INC.
8980 if (C->getAPIntValue() == 1) {
8981 Opcode = X86ISD::INC;
8986 // An add of negative one (subtract of one) will be selected as a DEC.
8987 if (C->getAPIntValue().isAllOnesValue()) {
8988 Opcode = X86ISD::DEC;
8994 // Otherwise use a regular EFLAGS-setting add.
8995 Opcode = X86ISD::ADD;
8999 // If the primary and result isn't used, don't bother using X86ISD::AND,
9000 // because a TEST instruction will be better.
9001 bool NonFlagUse = false;
9002 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9003 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9005 unsigned UOpNo = UI.getOperandNo();
9006 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9007 // Look pass truncate.
9008 UOpNo = User->use_begin().getOperandNo();
9009 User = *User->use_begin();
9012 if (User->getOpcode() != ISD::BRCOND &&
9013 User->getOpcode() != ISD::SETCC &&
9014 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9027 // Due to the ISEL shortcoming noted above, be conservative if this op is
9028 // likely to be selected as part of a load-modify-store instruction.
9029 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9030 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9031 if (UI->getOpcode() == ISD::STORE)
9034 // Otherwise use a regular EFLAGS-setting instruction.
9035 switch (ArithOp.getOpcode()) {
9036 default: llvm_unreachable("unexpected operator!");
9037 case ISD::SUB: Opcode = X86ISD::SUB; break;
9038 case ISD::XOR: Opcode = X86ISD::XOR; break;
9039 case ISD::AND: Opcode = X86ISD::AND; break;
9041 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9042 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9043 if (EFLAGS.getNode())
9046 Opcode = X86ISD::OR;
9060 return SDValue(Op.getNode(), 1);
9066 // If we found that truncation is beneficial, perform the truncation and
9068 if (NeedTruncation) {
9069 EVT VT = Op.getValueType();
9070 SDValue WideVal = Op->getOperand(0);
9071 EVT WideVT = WideVal.getValueType();
9072 unsigned ConvertedOp = 0;
9073 // Use a target machine opcode to prevent further DAGCombine
9074 // optimizations that may separate the arithmetic operations
9075 // from the setcc node.
9076 switch (WideVal.getOpcode()) {
9078 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9079 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9080 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9081 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9082 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9087 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9088 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9089 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9090 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9096 // Emit a CMP with 0, which is the TEST pattern.
9097 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9098 DAG.getConstant(0, Op.getValueType()));
9100 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9101 SmallVector<SDValue, 4> Ops;
9102 for (unsigned i = 0; i != NumOperands; ++i)
9103 Ops.push_back(Op.getOperand(i));
9105 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9106 DAG.ReplaceAllUsesWith(Op, New);
9107 return SDValue(New.getNode(), 1);
9110 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9112 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9113 SelectionDAG &DAG) const {
9114 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9115 if (C->getAPIntValue() == 0)
9116 return EmitTest(Op0, X86CC, DAG);
9119 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9120 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9121 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9122 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9123 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9125 return SDValue(Sub.getNode(), 1);
9127 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9130 /// Convert a comparison if required by the subtarget.
9131 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9132 SelectionDAG &DAG) const {
9133 // If the subtarget does not support the FUCOMI instruction, floating-point
9134 // comparisons have to be converted.
9135 if (Subtarget->hasCMov() ||
9136 Cmp.getOpcode() != X86ISD::CMP ||
9137 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9138 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9141 // The instruction selector will select an FUCOM instruction instead of
9142 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9143 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9144 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9146 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9147 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9148 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9149 DAG.getConstant(8, MVT::i8));
9150 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9151 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9154 static bool isAllOnes(SDValue V) {
9155 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9156 return C && C->isAllOnesValue();
9159 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9160 /// if it's possible.
9161 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9162 SDLoc dl, SelectionDAG &DAG) const {
9163 SDValue Op0 = And.getOperand(0);
9164 SDValue Op1 = And.getOperand(1);
9165 if (Op0.getOpcode() == ISD::TRUNCATE)
9166 Op0 = Op0.getOperand(0);
9167 if (Op1.getOpcode() == ISD::TRUNCATE)
9168 Op1 = Op1.getOperand(0);
9171 if (Op1.getOpcode() == ISD::SHL)
9172 std::swap(Op0, Op1);
9173 if (Op0.getOpcode() == ISD::SHL) {
9174 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9175 if (And00C->getZExtValue() == 1) {
9176 // If we looked past a truncate, check that it's only truncating away
9178 unsigned BitWidth = Op0.getValueSizeInBits();
9179 unsigned AndBitWidth = And.getValueSizeInBits();
9180 if (BitWidth > AndBitWidth) {
9182 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9183 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9187 RHS = Op0.getOperand(1);
9189 } else if (Op1.getOpcode() == ISD::Constant) {
9190 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9191 uint64_t AndRHSVal = AndRHS->getZExtValue();
9192 SDValue AndLHS = Op0;
9194 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9195 LHS = AndLHS.getOperand(0);
9196 RHS = AndLHS.getOperand(1);
9199 // Use BT if the immediate can't be encoded in a TEST instruction.
9200 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9202 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9206 if (LHS.getNode()) {
9207 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9208 // instruction. Since the shift amount is in-range-or-undefined, we know
9209 // that doing a bittest on the i32 value is ok. We extend to i32 because
9210 // the encoding for the i16 version is larger than the i32 version.
9211 // Also promote i16 to i32 for performance / code size reason.
9212 if (LHS.getValueType() == MVT::i8 ||
9213 LHS.getValueType() == MVT::i16)
9214 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9216 // If the operand types disagree, extend the shift amount to match. Since
9217 // BT ignores high bits (like shifts) we can use anyextend.
9218 if (LHS.getValueType() != RHS.getValueType())
9219 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9221 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9222 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9223 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9224 DAG.getConstant(Cond, MVT::i8), BT);
9230 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9231 // ones, and then concatenate the result back.
9232 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9233 MVT VT = Op.getValueType().getSimpleVT();
9235 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9236 "Unsupported value type for operation");
9238 unsigned NumElems = VT.getVectorNumElements();
9240 SDValue CC = Op.getOperand(2);
9242 // Extract the LHS vectors
9243 SDValue LHS = Op.getOperand(0);
9244 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9245 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9247 // Extract the RHS vectors
9248 SDValue RHS = Op.getOperand(1);
9249 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9250 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9252 // Issue the operation on the smaller types and concatenate the result back
9253 MVT EltVT = VT.getVectorElementType();
9254 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9255 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9256 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9257 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9260 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9261 SelectionDAG &DAG) {
9263 SDValue Op0 = Op.getOperand(0);
9264 SDValue Op1 = Op.getOperand(1);
9265 SDValue CC = Op.getOperand(2);
9266 MVT VT = Op.getValueType().getSimpleVT();
9267 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9268 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9273 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9274 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9280 // SSE Condition code mapping:
9289 switch (SetCCOpcode) {
9290 default: llvm_unreachable("Unexpected SETCC condition");
9292 case ISD::SETEQ: SSECC = 0; break;
9294 case ISD::SETGT: Swap = true; // Fallthrough
9296 case ISD::SETOLT: SSECC = 1; break;
9298 case ISD::SETGE: Swap = true; // Fallthrough
9300 case ISD::SETOLE: SSECC = 2; break;
9301 case ISD::SETUO: SSECC = 3; break;
9303 case ISD::SETNE: SSECC = 4; break;
9304 case ISD::SETULE: Swap = true; // Fallthrough
9305 case ISD::SETUGE: SSECC = 5; break;
9306 case ISD::SETULT: Swap = true; // Fallthrough
9307 case ISD::SETUGT: SSECC = 6; break;
9308 case ISD::SETO: SSECC = 7; break;
9310 case ISD::SETONE: SSECC = 8; break;
9313 std::swap(Op0, Op1);
9315 // In the two special cases we can't handle, emit two comparisons.
9318 unsigned CombineOpc;
9319 if (SetCCOpcode == ISD::SETUEQ) {
9320 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9322 assert(SetCCOpcode == ISD::SETONE);
9323 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9326 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9327 DAG.getConstant(CC0, MVT::i8));
9328 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9329 DAG.getConstant(CC1, MVT::i8));
9330 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9332 // Handle all other FP comparisons here.
9333 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9334 DAG.getConstant(SSECC, MVT::i8));
9337 // Break 256-bit integer vector compare into smaller ones.
9338 if (VT.is256BitVector() && !Subtarget->hasInt256())
9339 return Lower256IntVSETCC(Op, DAG);
9341 // We are handling one of the integer comparisons here. Since SSE only has
9342 // GT and EQ comparisons for integer, swapping operands and multiple
9343 // operations may be required for some comparisons.
9345 bool Swap = false, Invert = false, FlipSigns = false;
9347 switch (SetCCOpcode) {
9348 default: llvm_unreachable("Unexpected SETCC condition");
9349 case ISD::SETNE: Invert = true;
9350 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9351 case ISD::SETLT: Swap = true;
9352 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9353 case ISD::SETGE: Swap = true;
9354 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9355 case ISD::SETULT: Swap = true;
9356 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9357 case ISD::SETUGE: Swap = true;
9358 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9361 std::swap(Op0, Op1);
9363 // Check that the operation in question is available (most are plain SSE2,
9364 // but PCMPGTQ and PCMPEQQ have different requirements).
9365 if (VT == MVT::v2i64) {
9366 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9367 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9369 // First cast everything to the right type.
9370 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9371 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9373 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9374 // bits of the inputs before performing those operations. The lower
9375 // compare is always unsigned.
9378 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9380 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9381 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9382 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9383 Sign, Zero, Sign, Zero);
9385 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9386 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9388 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9389 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9390 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9392 // Create masks for only the low parts/high parts of the 64 bit integers.
9393 const int MaskHi[] = { 1, 1, 3, 3 };
9394 const int MaskLo[] = { 0, 0, 2, 2 };
9395 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9396 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9397 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9399 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9400 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9403 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9405 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9408 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9409 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9410 // pcmpeqd + pshufd + pand.
9411 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9413 // First cast everything to the right type.
9414 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9415 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9418 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9420 // Make sure the lower and upper halves are both all-ones.
9421 const int Mask[] = { 1, 0, 3, 2 };
9422 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9423 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9426 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9428 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9432 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9433 // bits of the inputs before performing those operations.
9435 EVT EltVT = VT.getVectorElementType();
9436 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9437 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9438 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9441 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9443 // If the logical-not of the result is required, perform that now.
9445 Result = DAG.getNOT(dl, Result, VT);
9450 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9452 MVT VT = Op.getValueType().getSimpleVT();
9454 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9456 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9457 SDValue Op0 = Op.getOperand(0);
9458 SDValue Op1 = Op.getOperand(1);
9460 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9462 // Optimize to BT if possible.
9463 // Lower (X & (1 << N)) == 0 to BT(X, N).
9464 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9465 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9466 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9467 Op1.getOpcode() == ISD::Constant &&
9468 cast<ConstantSDNode>(Op1)->isNullValue() &&
9469 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9470 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9471 if (NewSetCC.getNode())
9475 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9477 if (Op1.getOpcode() == ISD::Constant &&
9478 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9479 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9480 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9482 // If the input is a setcc, then reuse the input setcc or use a new one with
9483 // the inverted condition.
9484 if (Op0.getOpcode() == X86ISD::SETCC) {
9485 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9486 bool Invert = (CC == ISD::SETNE) ^
9487 cast<ConstantSDNode>(Op1)->isNullValue();
9488 if (!Invert) return Op0;
9490 CCode = X86::GetOppositeBranchCondition(CCode);
9491 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9492 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9496 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9497 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9498 if (X86CC == X86::COND_INVALID)
9501 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9502 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9503 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9504 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9507 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9508 static bool isX86LogicalCmp(SDValue Op) {
9509 unsigned Opc = Op.getNode()->getOpcode();
9510 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9511 Opc == X86ISD::SAHF)
9513 if (Op.getResNo() == 1 &&
9514 (Opc == X86ISD::ADD ||
9515 Opc == X86ISD::SUB ||
9516 Opc == X86ISD::ADC ||
9517 Opc == X86ISD::SBB ||
9518 Opc == X86ISD::SMUL ||
9519 Opc == X86ISD::UMUL ||
9520 Opc == X86ISD::INC ||
9521 Opc == X86ISD::DEC ||
9522 Opc == X86ISD::OR ||
9523 Opc == X86ISD::XOR ||
9524 Opc == X86ISD::AND))
9527 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9533 static bool isZero(SDValue V) {
9534 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9535 return C && C->isNullValue();
9538 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9539 if (V.getOpcode() != ISD::TRUNCATE)
9542 SDValue VOp0 = V.getOperand(0);
9543 unsigned InBits = VOp0.getValueSizeInBits();
9544 unsigned Bits = V.getValueSizeInBits();
9545 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9548 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9549 bool addTest = true;
9550 SDValue Cond = Op.getOperand(0);
9551 SDValue Op1 = Op.getOperand(1);
9552 SDValue Op2 = Op.getOperand(2);
9556 if (Cond.getOpcode() == ISD::SETCC) {
9557 SDValue NewCond = LowerSETCC(Cond, DAG);
9558 if (NewCond.getNode())
9562 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9563 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9564 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9565 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9566 if (Cond.getOpcode() == X86ISD::SETCC &&
9567 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9568 isZero(Cond.getOperand(1).getOperand(1))) {
9569 SDValue Cmp = Cond.getOperand(1);
9571 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9573 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9574 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9575 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9577 SDValue CmpOp0 = Cmp.getOperand(0);
9578 // Apply further optimizations for special cases
9579 // (select (x != 0), -1, 0) -> neg & sbb
9580 // (select (x == 0), 0, -1) -> neg & sbb
9581 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9582 if (YC->isNullValue() &&
9583 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9584 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9585 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9586 DAG.getConstant(0, CmpOp0.getValueType()),
9588 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9589 DAG.getConstant(X86::COND_B, MVT::i8),
9590 SDValue(Neg.getNode(), 1));
9594 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9595 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9596 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9598 SDValue Res = // Res = 0 or -1.
9599 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9600 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9602 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9603 Res = DAG.getNOT(DL, Res, Res.getValueType());
9605 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9606 if (N2C == 0 || !N2C->isNullValue())
9607 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9612 // Look past (and (setcc_carry (cmp ...)), 1).
9613 if (Cond.getOpcode() == ISD::AND &&
9614 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9615 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9616 if (C && C->getAPIntValue() == 1)
9617 Cond = Cond.getOperand(0);
9620 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9621 // setting operand in place of the X86ISD::SETCC.
9622 unsigned CondOpcode = Cond.getOpcode();
9623 if (CondOpcode == X86ISD::SETCC ||
9624 CondOpcode == X86ISD::SETCC_CARRY) {
9625 CC = Cond.getOperand(0);
9627 SDValue Cmp = Cond.getOperand(1);
9628 unsigned Opc = Cmp.getOpcode();
9629 MVT VT = Op.getValueType().getSimpleVT();
9631 bool IllegalFPCMov = false;
9632 if (VT.isFloatingPoint() && !VT.isVector() &&
9633 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9634 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9636 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9637 Opc == X86ISD::BT) { // FIXME
9641 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9642 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9643 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9644 Cond.getOperand(0).getValueType() != MVT::i8)) {
9645 SDValue LHS = Cond.getOperand(0);
9646 SDValue RHS = Cond.getOperand(1);
9650 switch (CondOpcode) {
9651 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9652 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9653 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9654 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9655 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9656 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9657 default: llvm_unreachable("unexpected overflowing operator");
9659 if (CondOpcode == ISD::UMULO)
9660 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9663 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9665 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9667 if (CondOpcode == ISD::UMULO)
9668 Cond = X86Op.getValue(2);
9670 Cond = X86Op.getValue(1);
9672 CC = DAG.getConstant(X86Cond, MVT::i8);
9677 // Look pass the truncate if the high bits are known zero.
9678 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9679 Cond = Cond.getOperand(0);
9681 // We know the result of AND is compared against zero. Try to match
9683 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9684 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9685 if (NewSetCC.getNode()) {
9686 CC = NewSetCC.getOperand(0);
9687 Cond = NewSetCC.getOperand(1);
9694 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9695 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9698 // a < b ? -1 : 0 -> RES = ~setcc_carry
9699 // a < b ? 0 : -1 -> RES = setcc_carry
9700 // a >= b ? -1 : 0 -> RES = setcc_carry
9701 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9702 if (Cond.getOpcode() == X86ISD::SUB) {
9703 Cond = ConvertCmpIfNecessary(Cond, DAG);
9704 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9706 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9707 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9708 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9709 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9710 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9711 return DAG.getNOT(DL, Res, Res.getValueType());
9716 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9717 // widen the cmov and push the truncate through. This avoids introducing a new
9718 // branch during isel and doesn't add any extensions.
9719 if (Op.getValueType() == MVT::i8 &&
9720 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9721 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9722 if (T1.getValueType() == T2.getValueType() &&
9723 // Blacklist CopyFromReg to avoid partial register stalls.
9724 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9725 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9726 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9727 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9731 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9732 // condition is true.
9733 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9734 SDValue Ops[] = { Op2, Op1, CC, Cond };
9735 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9738 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9739 SelectionDAG &DAG) const {
9740 MVT VT = Op->getValueType(0).getSimpleVT();
9741 SDValue In = Op->getOperand(0);
9742 MVT InVT = In.getValueType().getSimpleVT();
9745 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9746 (VT != MVT::v8i32 || InVT != MVT::v8i16))
9749 if (Subtarget->hasInt256())
9750 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9752 // Optimize vectors in AVX mode
9753 // Sign extend v8i16 to v8i32 and
9756 // Divide input vector into two parts
9757 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9758 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9759 // concat the vectors to original VT
9761 unsigned NumElems = InVT.getVectorNumElements();
9762 SDValue Undef = DAG.getUNDEF(InVT);
9764 SmallVector<int,8> ShufMask1(NumElems, -1);
9765 for (unsigned i = 0; i != NumElems/2; ++i)
9768 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9770 SmallVector<int,8> ShufMask2(NumElems, -1);
9771 for (unsigned i = 0; i != NumElems/2; ++i)
9772 ShufMask2[i] = i + NumElems/2;
9774 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9776 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9777 VT.getVectorNumElements()/2);
9779 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9780 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9782 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9785 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9786 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9787 // from the AND / OR.
9788 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9789 Opc = Op.getOpcode();
9790 if (Opc != ISD::OR && Opc != ISD::AND)
9792 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9793 Op.getOperand(0).hasOneUse() &&
9794 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9795 Op.getOperand(1).hasOneUse());
9798 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9799 // 1 and that the SETCC node has a single use.
9800 static bool isXor1OfSetCC(SDValue Op) {
9801 if (Op.getOpcode() != ISD::XOR)
9803 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9804 if (N1C && N1C->getAPIntValue() == 1) {
9805 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9806 Op.getOperand(0).hasOneUse();
9811 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9812 bool addTest = true;
9813 SDValue Chain = Op.getOperand(0);
9814 SDValue Cond = Op.getOperand(1);
9815 SDValue Dest = Op.getOperand(2);
9818 bool Inverted = false;
9820 if (Cond.getOpcode() == ISD::SETCC) {
9821 // Check for setcc([su]{add,sub,mul}o == 0).
9822 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9823 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9824 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9825 Cond.getOperand(0).getResNo() == 1 &&
9826 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9827 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9828 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9829 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9830 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9831 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9833 Cond = Cond.getOperand(0);
9835 SDValue NewCond = LowerSETCC(Cond, DAG);
9836 if (NewCond.getNode())
9841 // FIXME: LowerXALUO doesn't handle these!!
9842 else if (Cond.getOpcode() == X86ISD::ADD ||
9843 Cond.getOpcode() == X86ISD::SUB ||
9844 Cond.getOpcode() == X86ISD::SMUL ||
9845 Cond.getOpcode() == X86ISD::UMUL)
9846 Cond = LowerXALUO(Cond, DAG);
9849 // Look pass (and (setcc_carry (cmp ...)), 1).
9850 if (Cond.getOpcode() == ISD::AND &&
9851 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9852 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9853 if (C && C->getAPIntValue() == 1)
9854 Cond = Cond.getOperand(0);
9857 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9858 // setting operand in place of the X86ISD::SETCC.
9859 unsigned CondOpcode = Cond.getOpcode();
9860 if (CondOpcode == X86ISD::SETCC ||
9861 CondOpcode == X86ISD::SETCC_CARRY) {
9862 CC = Cond.getOperand(0);
9864 SDValue Cmp = Cond.getOperand(1);
9865 unsigned Opc = Cmp.getOpcode();
9866 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9867 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9871 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9875 // These can only come from an arithmetic instruction with overflow,
9876 // e.g. SADDO, UADDO.
9877 Cond = Cond.getNode()->getOperand(1);
9883 CondOpcode = Cond.getOpcode();
9884 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9885 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9886 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9887 Cond.getOperand(0).getValueType() != MVT::i8)) {
9888 SDValue LHS = Cond.getOperand(0);
9889 SDValue RHS = Cond.getOperand(1);
9893 switch (CondOpcode) {
9894 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9895 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9896 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9897 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9898 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9899 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9900 default: llvm_unreachable("unexpected overflowing operator");
9903 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9904 if (CondOpcode == ISD::UMULO)
9905 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9908 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9910 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9912 if (CondOpcode == ISD::UMULO)
9913 Cond = X86Op.getValue(2);
9915 Cond = X86Op.getValue(1);
9917 CC = DAG.getConstant(X86Cond, MVT::i8);
9921 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9922 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9923 if (CondOpc == ISD::OR) {
9924 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9925 // two branches instead of an explicit OR instruction with a
9927 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9928 isX86LogicalCmp(Cmp)) {
9929 CC = Cond.getOperand(0).getOperand(0);
9930 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9931 Chain, Dest, CC, Cmp);
9932 CC = Cond.getOperand(1).getOperand(0);
9936 } else { // ISD::AND
9937 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9938 // two branches instead of an explicit AND instruction with a
9939 // separate test. However, we only do this if this block doesn't
9940 // have a fall-through edge, because this requires an explicit
9941 // jmp when the condition is false.
9942 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9943 isX86LogicalCmp(Cmp) &&
9944 Op.getNode()->hasOneUse()) {
9945 X86::CondCode CCode =
9946 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9947 CCode = X86::GetOppositeBranchCondition(CCode);
9948 CC = DAG.getConstant(CCode, MVT::i8);
9949 SDNode *User = *Op.getNode()->use_begin();
9950 // Look for an unconditional branch following this conditional branch.
9951 // We need this because we need to reverse the successors in order
9952 // to implement FCMP_OEQ.
9953 if (User->getOpcode() == ISD::BR) {
9954 SDValue FalseBB = User->getOperand(1);
9956 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9957 assert(NewBR == User);
9961 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9962 Chain, Dest, CC, Cmp);
9963 X86::CondCode CCode =
9964 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9965 CCode = X86::GetOppositeBranchCondition(CCode);
9966 CC = DAG.getConstant(CCode, MVT::i8);
9972 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9973 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9974 // It should be transformed during dag combiner except when the condition
9975 // is set by a arithmetics with overflow node.
9976 X86::CondCode CCode =
9977 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9978 CCode = X86::GetOppositeBranchCondition(CCode);
9979 CC = DAG.getConstant(CCode, MVT::i8);
9980 Cond = Cond.getOperand(0).getOperand(1);
9982 } else if (Cond.getOpcode() == ISD::SETCC &&
9983 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9984 // For FCMP_OEQ, we can emit
9985 // two branches instead of an explicit AND instruction with a
9986 // separate test. However, we only do this if this block doesn't
9987 // have a fall-through edge, because this requires an explicit
9988 // jmp when the condition is false.
9989 if (Op.getNode()->hasOneUse()) {
9990 SDNode *User = *Op.getNode()->use_begin();
9991 // Look for an unconditional branch following this conditional branch.
9992 // We need this because we need to reverse the successors in order
9993 // to implement FCMP_OEQ.
9994 if (User->getOpcode() == ISD::BR) {
9995 SDValue FalseBB = User->getOperand(1);
9997 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9998 assert(NewBR == User);
10002 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10003 Cond.getOperand(0), Cond.getOperand(1));
10004 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10005 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10006 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10007 Chain, Dest, CC, Cmp);
10008 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10013 } else if (Cond.getOpcode() == ISD::SETCC &&
10014 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10015 // For FCMP_UNE, we can emit
10016 // two branches instead of an explicit AND instruction with a
10017 // separate test. However, we only do this if this block doesn't
10018 // have a fall-through edge, because this requires an explicit
10019 // jmp when the condition is false.
10020 if (Op.getNode()->hasOneUse()) {
10021 SDNode *User = *Op.getNode()->use_begin();
10022 // Look for an unconditional branch following this conditional branch.
10023 // We need this because we need to reverse the successors in order
10024 // to implement FCMP_UNE.
10025 if (User->getOpcode() == ISD::BR) {
10026 SDValue FalseBB = User->getOperand(1);
10028 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10029 assert(NewBR == User);
10032 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10033 Cond.getOperand(0), Cond.getOperand(1));
10034 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10035 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10036 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10037 Chain, Dest, CC, Cmp);
10038 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10048 // Look pass the truncate if the high bits are known zero.
10049 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10050 Cond = Cond.getOperand(0);
10052 // We know the result of AND is compared against zero. Try to match
10054 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10055 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10056 if (NewSetCC.getNode()) {
10057 CC = NewSetCC.getOperand(0);
10058 Cond = NewSetCC.getOperand(1);
10065 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10066 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10068 Cond = ConvertCmpIfNecessary(Cond, DAG);
10069 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10070 Chain, Dest, CC, Cond);
10073 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10074 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10075 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10076 // that the guard pages used by the OS virtual memory manager are allocated in
10077 // correct sequence.
10079 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10080 SelectionDAG &DAG) const {
10081 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10082 getTargetMachine().Options.EnableSegmentedStacks) &&
10083 "This should be used only on Windows targets or when segmented stacks "
10085 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10089 SDValue Chain = Op.getOperand(0);
10090 SDValue Size = Op.getOperand(1);
10091 // FIXME: Ensure alignment here
10093 bool Is64Bit = Subtarget->is64Bit();
10094 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10096 if (getTargetMachine().Options.EnableSegmentedStacks) {
10097 MachineFunction &MF = DAG.getMachineFunction();
10098 MachineRegisterInfo &MRI = MF.getRegInfo();
10101 // The 64 bit implementation of segmented stacks needs to clobber both r10
10102 // r11. This makes it impossible to use it along with nested parameters.
10103 const Function *F = MF.getFunction();
10105 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10107 if (I->hasNestAttr())
10108 report_fatal_error("Cannot use segmented stacks with functions that "
10109 "have nested arguments.");
10112 const TargetRegisterClass *AddrRegClass =
10113 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10114 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10115 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10116 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10117 DAG.getRegister(Vreg, SPTy));
10118 SDValue Ops1[2] = { Value, Chain };
10119 return DAG.getMergeValues(Ops1, 2, dl);
10122 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10124 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10125 Flag = Chain.getValue(1);
10126 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10128 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10129 Flag = Chain.getValue(1);
10131 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10134 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10135 return DAG.getMergeValues(Ops1, 2, dl);
10139 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10140 MachineFunction &MF = DAG.getMachineFunction();
10141 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10143 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10146 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10147 // vastart just stores the address of the VarArgsFrameIndex slot into the
10148 // memory location argument.
10149 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10151 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10152 MachinePointerInfo(SV), false, false, 0);
10156 // gp_offset (0 - 6 * 8)
10157 // fp_offset (48 - 48 + 8 * 16)
10158 // overflow_arg_area (point to parameters coming in memory).
10160 SmallVector<SDValue, 8> MemOps;
10161 SDValue FIN = Op.getOperand(1);
10163 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10164 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10166 FIN, MachinePointerInfo(SV), false, false, 0);
10167 MemOps.push_back(Store);
10170 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10171 FIN, DAG.getIntPtrConstant(4));
10172 Store = DAG.getStore(Op.getOperand(0), DL,
10173 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10175 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10176 MemOps.push_back(Store);
10178 // Store ptr to overflow_arg_area
10179 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10180 FIN, DAG.getIntPtrConstant(4));
10181 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10183 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10184 MachinePointerInfo(SV, 8),
10186 MemOps.push_back(Store);
10188 // Store ptr to reg_save_area.
10189 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10190 FIN, DAG.getIntPtrConstant(8));
10191 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10193 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10194 MachinePointerInfo(SV, 16), false, false, 0);
10195 MemOps.push_back(Store);
10196 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10197 &MemOps[0], MemOps.size());
10200 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10201 assert(Subtarget->is64Bit() &&
10202 "LowerVAARG only handles 64-bit va_arg!");
10203 assert((Subtarget->isTargetLinux() ||
10204 Subtarget->isTargetDarwin()) &&
10205 "Unhandled target in LowerVAARG");
10206 assert(Op.getNode()->getNumOperands() == 4);
10207 SDValue Chain = Op.getOperand(0);
10208 SDValue SrcPtr = Op.getOperand(1);
10209 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10210 unsigned Align = Op.getConstantOperandVal(3);
10213 EVT ArgVT = Op.getNode()->getValueType(0);
10214 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10215 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10218 // Decide which area this value should be read from.
10219 // TODO: Implement the AMD64 ABI in its entirety. This simple
10220 // selection mechanism works only for the basic types.
10221 if (ArgVT == MVT::f80) {
10222 llvm_unreachable("va_arg for f80 not yet implemented");
10223 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10224 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10225 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10226 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10228 llvm_unreachable("Unhandled argument type in LowerVAARG");
10231 if (ArgMode == 2) {
10232 // Sanity Check: Make sure using fp_offset makes sense.
10233 assert(!getTargetMachine().Options.UseSoftFloat &&
10234 !(DAG.getMachineFunction()
10235 .getFunction()->getAttributes()
10236 .hasAttribute(AttributeSet::FunctionIndex,
10237 Attribute::NoImplicitFloat)) &&
10238 Subtarget->hasSSE1());
10241 // Insert VAARG_64 node into the DAG
10242 // VAARG_64 returns two values: Variable Argument Address, Chain
10243 SmallVector<SDValue, 11> InstOps;
10244 InstOps.push_back(Chain);
10245 InstOps.push_back(SrcPtr);
10246 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10247 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10248 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10249 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10250 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10251 VTs, &InstOps[0], InstOps.size(),
10253 MachinePointerInfo(SV),
10255 /*Volatile=*/false,
10257 /*WriteMem=*/true);
10258 Chain = VAARG.getValue(1);
10260 // Load the next argument and return it
10261 return DAG.getLoad(ArgVT, dl,
10264 MachinePointerInfo(),
10265 false, false, false, 0);
10268 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10269 SelectionDAG &DAG) {
10270 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10271 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10272 SDValue Chain = Op.getOperand(0);
10273 SDValue DstPtr = Op.getOperand(1);
10274 SDValue SrcPtr = Op.getOperand(2);
10275 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10276 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10279 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10280 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10282 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10285 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10286 // may or may not be a constant. Takes immediate version of shift as input.
10287 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10288 SDValue SrcOp, SDValue ShAmt,
10289 SelectionDAG &DAG) {
10290 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10292 if (isa<ConstantSDNode>(ShAmt)) {
10293 // Constant may be a TargetConstant. Use a regular constant.
10294 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10296 default: llvm_unreachable("Unknown target vector shift node");
10297 case X86ISD::VSHLI:
10298 case X86ISD::VSRLI:
10299 case X86ISD::VSRAI:
10300 return DAG.getNode(Opc, dl, VT, SrcOp,
10301 DAG.getConstant(ShiftAmt, MVT::i32));
10305 // Change opcode to non-immediate version
10307 default: llvm_unreachable("Unknown target vector shift node");
10308 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10309 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10310 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10313 // Need to build a vector containing shift amount
10314 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10317 ShOps[1] = DAG.getConstant(0, MVT::i32);
10318 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10319 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10321 // The return type has to be a 128-bit type with the same element
10322 // type as the input type.
10323 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10324 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10326 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10327 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10330 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10332 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10334 default: return SDValue(); // Don't custom lower most intrinsics.
10335 // Comparison intrinsics.
10336 case Intrinsic::x86_sse_comieq_ss:
10337 case Intrinsic::x86_sse_comilt_ss:
10338 case Intrinsic::x86_sse_comile_ss:
10339 case Intrinsic::x86_sse_comigt_ss:
10340 case Intrinsic::x86_sse_comige_ss:
10341 case Intrinsic::x86_sse_comineq_ss:
10342 case Intrinsic::x86_sse_ucomieq_ss:
10343 case Intrinsic::x86_sse_ucomilt_ss:
10344 case Intrinsic::x86_sse_ucomile_ss:
10345 case Intrinsic::x86_sse_ucomigt_ss:
10346 case Intrinsic::x86_sse_ucomige_ss:
10347 case Intrinsic::x86_sse_ucomineq_ss:
10348 case Intrinsic::x86_sse2_comieq_sd:
10349 case Intrinsic::x86_sse2_comilt_sd:
10350 case Intrinsic::x86_sse2_comile_sd:
10351 case Intrinsic::x86_sse2_comigt_sd:
10352 case Intrinsic::x86_sse2_comige_sd:
10353 case Intrinsic::x86_sse2_comineq_sd:
10354 case Intrinsic::x86_sse2_ucomieq_sd:
10355 case Intrinsic::x86_sse2_ucomilt_sd:
10356 case Intrinsic::x86_sse2_ucomile_sd:
10357 case Intrinsic::x86_sse2_ucomigt_sd:
10358 case Intrinsic::x86_sse2_ucomige_sd:
10359 case Intrinsic::x86_sse2_ucomineq_sd: {
10363 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10364 case Intrinsic::x86_sse_comieq_ss:
10365 case Intrinsic::x86_sse2_comieq_sd:
10366 Opc = X86ISD::COMI;
10369 case Intrinsic::x86_sse_comilt_ss:
10370 case Intrinsic::x86_sse2_comilt_sd:
10371 Opc = X86ISD::COMI;
10374 case Intrinsic::x86_sse_comile_ss:
10375 case Intrinsic::x86_sse2_comile_sd:
10376 Opc = X86ISD::COMI;
10379 case Intrinsic::x86_sse_comigt_ss:
10380 case Intrinsic::x86_sse2_comigt_sd:
10381 Opc = X86ISD::COMI;
10384 case Intrinsic::x86_sse_comige_ss:
10385 case Intrinsic::x86_sse2_comige_sd:
10386 Opc = X86ISD::COMI;
10389 case Intrinsic::x86_sse_comineq_ss:
10390 case Intrinsic::x86_sse2_comineq_sd:
10391 Opc = X86ISD::COMI;
10394 case Intrinsic::x86_sse_ucomieq_ss:
10395 case Intrinsic::x86_sse2_ucomieq_sd:
10396 Opc = X86ISD::UCOMI;
10399 case Intrinsic::x86_sse_ucomilt_ss:
10400 case Intrinsic::x86_sse2_ucomilt_sd:
10401 Opc = X86ISD::UCOMI;
10404 case Intrinsic::x86_sse_ucomile_ss:
10405 case Intrinsic::x86_sse2_ucomile_sd:
10406 Opc = X86ISD::UCOMI;
10409 case Intrinsic::x86_sse_ucomigt_ss:
10410 case Intrinsic::x86_sse2_ucomigt_sd:
10411 Opc = X86ISD::UCOMI;
10414 case Intrinsic::x86_sse_ucomige_ss:
10415 case Intrinsic::x86_sse2_ucomige_sd:
10416 Opc = X86ISD::UCOMI;
10419 case Intrinsic::x86_sse_ucomineq_ss:
10420 case Intrinsic::x86_sse2_ucomineq_sd:
10421 Opc = X86ISD::UCOMI;
10426 SDValue LHS = Op.getOperand(1);
10427 SDValue RHS = Op.getOperand(2);
10428 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10429 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10430 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10431 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10432 DAG.getConstant(X86CC, MVT::i8), Cond);
10433 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10436 // Arithmetic intrinsics.
10437 case Intrinsic::x86_sse2_pmulu_dq:
10438 case Intrinsic::x86_avx2_pmulu_dq:
10439 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10440 Op.getOperand(1), Op.getOperand(2));
10442 // SSE2/AVX2 sub with unsigned saturation intrinsics
10443 case Intrinsic::x86_sse2_psubus_b:
10444 case Intrinsic::x86_sse2_psubus_w:
10445 case Intrinsic::x86_avx2_psubus_b:
10446 case Intrinsic::x86_avx2_psubus_w:
10447 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10448 Op.getOperand(1), Op.getOperand(2));
10450 // SSE3/AVX horizontal add/sub intrinsics
10451 case Intrinsic::x86_sse3_hadd_ps:
10452 case Intrinsic::x86_sse3_hadd_pd:
10453 case Intrinsic::x86_avx_hadd_ps_256:
10454 case Intrinsic::x86_avx_hadd_pd_256:
10455 case Intrinsic::x86_sse3_hsub_ps:
10456 case Intrinsic::x86_sse3_hsub_pd:
10457 case Intrinsic::x86_avx_hsub_ps_256:
10458 case Intrinsic::x86_avx_hsub_pd_256:
10459 case Intrinsic::x86_ssse3_phadd_w_128:
10460 case Intrinsic::x86_ssse3_phadd_d_128:
10461 case Intrinsic::x86_avx2_phadd_w:
10462 case Intrinsic::x86_avx2_phadd_d:
10463 case Intrinsic::x86_ssse3_phsub_w_128:
10464 case Intrinsic::x86_ssse3_phsub_d_128:
10465 case Intrinsic::x86_avx2_phsub_w:
10466 case Intrinsic::x86_avx2_phsub_d: {
10469 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10470 case Intrinsic::x86_sse3_hadd_ps:
10471 case Intrinsic::x86_sse3_hadd_pd:
10472 case Intrinsic::x86_avx_hadd_ps_256:
10473 case Intrinsic::x86_avx_hadd_pd_256:
10474 Opcode = X86ISD::FHADD;
10476 case Intrinsic::x86_sse3_hsub_ps:
10477 case Intrinsic::x86_sse3_hsub_pd:
10478 case Intrinsic::x86_avx_hsub_ps_256:
10479 case Intrinsic::x86_avx_hsub_pd_256:
10480 Opcode = X86ISD::FHSUB;
10482 case Intrinsic::x86_ssse3_phadd_w_128:
10483 case Intrinsic::x86_ssse3_phadd_d_128:
10484 case Intrinsic::x86_avx2_phadd_w:
10485 case Intrinsic::x86_avx2_phadd_d:
10486 Opcode = X86ISD::HADD;
10488 case Intrinsic::x86_ssse3_phsub_w_128:
10489 case Intrinsic::x86_ssse3_phsub_d_128:
10490 case Intrinsic::x86_avx2_phsub_w:
10491 case Intrinsic::x86_avx2_phsub_d:
10492 Opcode = X86ISD::HSUB;
10495 return DAG.getNode(Opcode, dl, Op.getValueType(),
10496 Op.getOperand(1), Op.getOperand(2));
10499 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10500 case Intrinsic::x86_sse2_pmaxu_b:
10501 case Intrinsic::x86_sse41_pmaxuw:
10502 case Intrinsic::x86_sse41_pmaxud:
10503 case Intrinsic::x86_avx2_pmaxu_b:
10504 case Intrinsic::x86_avx2_pmaxu_w:
10505 case Intrinsic::x86_avx2_pmaxu_d:
10506 case Intrinsic::x86_sse2_pminu_b:
10507 case Intrinsic::x86_sse41_pminuw:
10508 case Intrinsic::x86_sse41_pminud:
10509 case Intrinsic::x86_avx2_pminu_b:
10510 case Intrinsic::x86_avx2_pminu_w:
10511 case Intrinsic::x86_avx2_pminu_d:
10512 case Intrinsic::x86_sse41_pmaxsb:
10513 case Intrinsic::x86_sse2_pmaxs_w:
10514 case Intrinsic::x86_sse41_pmaxsd:
10515 case Intrinsic::x86_avx2_pmaxs_b:
10516 case Intrinsic::x86_avx2_pmaxs_w:
10517 case Intrinsic::x86_avx2_pmaxs_d:
10518 case Intrinsic::x86_sse41_pminsb:
10519 case Intrinsic::x86_sse2_pmins_w:
10520 case Intrinsic::x86_sse41_pminsd:
10521 case Intrinsic::x86_avx2_pmins_b:
10522 case Intrinsic::x86_avx2_pmins_w:
10523 case Intrinsic::x86_avx2_pmins_d: {
10526 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10527 case Intrinsic::x86_sse2_pmaxu_b:
10528 case Intrinsic::x86_sse41_pmaxuw:
10529 case Intrinsic::x86_sse41_pmaxud:
10530 case Intrinsic::x86_avx2_pmaxu_b:
10531 case Intrinsic::x86_avx2_pmaxu_w:
10532 case Intrinsic::x86_avx2_pmaxu_d:
10533 Opcode = X86ISD::UMAX;
10535 case Intrinsic::x86_sse2_pminu_b:
10536 case Intrinsic::x86_sse41_pminuw:
10537 case Intrinsic::x86_sse41_pminud:
10538 case Intrinsic::x86_avx2_pminu_b:
10539 case Intrinsic::x86_avx2_pminu_w:
10540 case Intrinsic::x86_avx2_pminu_d:
10541 Opcode = X86ISD::UMIN;
10543 case Intrinsic::x86_sse41_pmaxsb:
10544 case Intrinsic::x86_sse2_pmaxs_w:
10545 case Intrinsic::x86_sse41_pmaxsd:
10546 case Intrinsic::x86_avx2_pmaxs_b:
10547 case Intrinsic::x86_avx2_pmaxs_w:
10548 case Intrinsic::x86_avx2_pmaxs_d:
10549 Opcode = X86ISD::SMAX;
10551 case Intrinsic::x86_sse41_pminsb:
10552 case Intrinsic::x86_sse2_pmins_w:
10553 case Intrinsic::x86_sse41_pminsd:
10554 case Intrinsic::x86_avx2_pmins_b:
10555 case Intrinsic::x86_avx2_pmins_w:
10556 case Intrinsic::x86_avx2_pmins_d:
10557 Opcode = X86ISD::SMIN;
10560 return DAG.getNode(Opcode, dl, Op.getValueType(),
10561 Op.getOperand(1), Op.getOperand(2));
10564 // SSE/SSE2/AVX floating point max/min intrinsics.
10565 case Intrinsic::x86_sse_max_ps:
10566 case Intrinsic::x86_sse2_max_pd:
10567 case Intrinsic::x86_avx_max_ps_256:
10568 case Intrinsic::x86_avx_max_pd_256:
10569 case Intrinsic::x86_sse_min_ps:
10570 case Intrinsic::x86_sse2_min_pd:
10571 case Intrinsic::x86_avx_min_ps_256:
10572 case Intrinsic::x86_avx_min_pd_256: {
10575 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10576 case Intrinsic::x86_sse_max_ps:
10577 case Intrinsic::x86_sse2_max_pd:
10578 case Intrinsic::x86_avx_max_ps_256:
10579 case Intrinsic::x86_avx_max_pd_256:
10580 Opcode = X86ISD::FMAX;
10582 case Intrinsic::x86_sse_min_ps:
10583 case Intrinsic::x86_sse2_min_pd:
10584 case Intrinsic::x86_avx_min_ps_256:
10585 case Intrinsic::x86_avx_min_pd_256:
10586 Opcode = X86ISD::FMIN;
10589 return DAG.getNode(Opcode, dl, Op.getValueType(),
10590 Op.getOperand(1), Op.getOperand(2));
10593 // AVX2 variable shift intrinsics
10594 case Intrinsic::x86_avx2_psllv_d:
10595 case Intrinsic::x86_avx2_psllv_q:
10596 case Intrinsic::x86_avx2_psllv_d_256:
10597 case Intrinsic::x86_avx2_psllv_q_256:
10598 case Intrinsic::x86_avx2_psrlv_d:
10599 case Intrinsic::x86_avx2_psrlv_q:
10600 case Intrinsic::x86_avx2_psrlv_d_256:
10601 case Intrinsic::x86_avx2_psrlv_q_256:
10602 case Intrinsic::x86_avx2_psrav_d:
10603 case Intrinsic::x86_avx2_psrav_d_256: {
10606 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10607 case Intrinsic::x86_avx2_psllv_d:
10608 case Intrinsic::x86_avx2_psllv_q:
10609 case Intrinsic::x86_avx2_psllv_d_256:
10610 case Intrinsic::x86_avx2_psllv_q_256:
10613 case Intrinsic::x86_avx2_psrlv_d:
10614 case Intrinsic::x86_avx2_psrlv_q:
10615 case Intrinsic::x86_avx2_psrlv_d_256:
10616 case Intrinsic::x86_avx2_psrlv_q_256:
10619 case Intrinsic::x86_avx2_psrav_d:
10620 case Intrinsic::x86_avx2_psrav_d_256:
10624 return DAG.getNode(Opcode, dl, Op.getValueType(),
10625 Op.getOperand(1), Op.getOperand(2));
10628 case Intrinsic::x86_ssse3_pshuf_b_128:
10629 case Intrinsic::x86_avx2_pshuf_b:
10630 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10631 Op.getOperand(1), Op.getOperand(2));
10633 case Intrinsic::x86_ssse3_psign_b_128:
10634 case Intrinsic::x86_ssse3_psign_w_128:
10635 case Intrinsic::x86_ssse3_psign_d_128:
10636 case Intrinsic::x86_avx2_psign_b:
10637 case Intrinsic::x86_avx2_psign_w:
10638 case Intrinsic::x86_avx2_psign_d:
10639 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10640 Op.getOperand(1), Op.getOperand(2));
10642 case Intrinsic::x86_sse41_insertps:
10643 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10644 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10646 case Intrinsic::x86_avx_vperm2f128_ps_256:
10647 case Intrinsic::x86_avx_vperm2f128_pd_256:
10648 case Intrinsic::x86_avx_vperm2f128_si_256:
10649 case Intrinsic::x86_avx2_vperm2i128:
10650 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10651 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10653 case Intrinsic::x86_avx2_permd:
10654 case Intrinsic::x86_avx2_permps:
10655 // Operands intentionally swapped. Mask is last operand to intrinsic,
10656 // but second operand for node/intruction.
10657 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10658 Op.getOperand(2), Op.getOperand(1));
10660 case Intrinsic::x86_sse_sqrt_ps:
10661 case Intrinsic::x86_sse2_sqrt_pd:
10662 case Intrinsic::x86_avx_sqrt_ps_256:
10663 case Intrinsic::x86_avx_sqrt_pd_256:
10664 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10666 // ptest and testp intrinsics. The intrinsic these come from are designed to
10667 // return an integer value, not just an instruction so lower it to the ptest
10668 // or testp pattern and a setcc for the result.
10669 case Intrinsic::x86_sse41_ptestz:
10670 case Intrinsic::x86_sse41_ptestc:
10671 case Intrinsic::x86_sse41_ptestnzc:
10672 case Intrinsic::x86_avx_ptestz_256:
10673 case Intrinsic::x86_avx_ptestc_256:
10674 case Intrinsic::x86_avx_ptestnzc_256:
10675 case Intrinsic::x86_avx_vtestz_ps:
10676 case Intrinsic::x86_avx_vtestc_ps:
10677 case Intrinsic::x86_avx_vtestnzc_ps:
10678 case Intrinsic::x86_avx_vtestz_pd:
10679 case Intrinsic::x86_avx_vtestc_pd:
10680 case Intrinsic::x86_avx_vtestnzc_pd:
10681 case Intrinsic::x86_avx_vtestz_ps_256:
10682 case Intrinsic::x86_avx_vtestc_ps_256:
10683 case Intrinsic::x86_avx_vtestnzc_ps_256:
10684 case Intrinsic::x86_avx_vtestz_pd_256:
10685 case Intrinsic::x86_avx_vtestc_pd_256:
10686 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10687 bool IsTestPacked = false;
10690 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10691 case Intrinsic::x86_avx_vtestz_ps:
10692 case Intrinsic::x86_avx_vtestz_pd:
10693 case Intrinsic::x86_avx_vtestz_ps_256:
10694 case Intrinsic::x86_avx_vtestz_pd_256:
10695 IsTestPacked = true; // Fallthrough
10696 case Intrinsic::x86_sse41_ptestz:
10697 case Intrinsic::x86_avx_ptestz_256:
10699 X86CC = X86::COND_E;
10701 case Intrinsic::x86_avx_vtestc_ps:
10702 case Intrinsic::x86_avx_vtestc_pd:
10703 case Intrinsic::x86_avx_vtestc_ps_256:
10704 case Intrinsic::x86_avx_vtestc_pd_256:
10705 IsTestPacked = true; // Fallthrough
10706 case Intrinsic::x86_sse41_ptestc:
10707 case Intrinsic::x86_avx_ptestc_256:
10709 X86CC = X86::COND_B;
10711 case Intrinsic::x86_avx_vtestnzc_ps:
10712 case Intrinsic::x86_avx_vtestnzc_pd:
10713 case Intrinsic::x86_avx_vtestnzc_ps_256:
10714 case Intrinsic::x86_avx_vtestnzc_pd_256:
10715 IsTestPacked = true; // Fallthrough
10716 case Intrinsic::x86_sse41_ptestnzc:
10717 case Intrinsic::x86_avx_ptestnzc_256:
10719 X86CC = X86::COND_A;
10723 SDValue LHS = Op.getOperand(1);
10724 SDValue RHS = Op.getOperand(2);
10725 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10726 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10727 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10728 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10729 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10732 // SSE/AVX shift intrinsics
10733 case Intrinsic::x86_sse2_psll_w:
10734 case Intrinsic::x86_sse2_psll_d:
10735 case Intrinsic::x86_sse2_psll_q:
10736 case Intrinsic::x86_avx2_psll_w:
10737 case Intrinsic::x86_avx2_psll_d:
10738 case Intrinsic::x86_avx2_psll_q:
10739 case Intrinsic::x86_sse2_psrl_w:
10740 case Intrinsic::x86_sse2_psrl_d:
10741 case Intrinsic::x86_sse2_psrl_q:
10742 case Intrinsic::x86_avx2_psrl_w:
10743 case Intrinsic::x86_avx2_psrl_d:
10744 case Intrinsic::x86_avx2_psrl_q:
10745 case Intrinsic::x86_sse2_psra_w:
10746 case Intrinsic::x86_sse2_psra_d:
10747 case Intrinsic::x86_avx2_psra_w:
10748 case Intrinsic::x86_avx2_psra_d: {
10751 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10752 case Intrinsic::x86_sse2_psll_w:
10753 case Intrinsic::x86_sse2_psll_d:
10754 case Intrinsic::x86_sse2_psll_q:
10755 case Intrinsic::x86_avx2_psll_w:
10756 case Intrinsic::x86_avx2_psll_d:
10757 case Intrinsic::x86_avx2_psll_q:
10758 Opcode = X86ISD::VSHL;
10760 case Intrinsic::x86_sse2_psrl_w:
10761 case Intrinsic::x86_sse2_psrl_d:
10762 case Intrinsic::x86_sse2_psrl_q:
10763 case Intrinsic::x86_avx2_psrl_w:
10764 case Intrinsic::x86_avx2_psrl_d:
10765 case Intrinsic::x86_avx2_psrl_q:
10766 Opcode = X86ISD::VSRL;
10768 case Intrinsic::x86_sse2_psra_w:
10769 case Intrinsic::x86_sse2_psra_d:
10770 case Intrinsic::x86_avx2_psra_w:
10771 case Intrinsic::x86_avx2_psra_d:
10772 Opcode = X86ISD::VSRA;
10775 return DAG.getNode(Opcode, dl, Op.getValueType(),
10776 Op.getOperand(1), Op.getOperand(2));
10779 // SSE/AVX immediate shift intrinsics
10780 case Intrinsic::x86_sse2_pslli_w:
10781 case Intrinsic::x86_sse2_pslli_d:
10782 case Intrinsic::x86_sse2_pslli_q:
10783 case Intrinsic::x86_avx2_pslli_w:
10784 case Intrinsic::x86_avx2_pslli_d:
10785 case Intrinsic::x86_avx2_pslli_q:
10786 case Intrinsic::x86_sse2_psrli_w:
10787 case Intrinsic::x86_sse2_psrli_d:
10788 case Intrinsic::x86_sse2_psrli_q:
10789 case Intrinsic::x86_avx2_psrli_w:
10790 case Intrinsic::x86_avx2_psrli_d:
10791 case Intrinsic::x86_avx2_psrli_q:
10792 case Intrinsic::x86_sse2_psrai_w:
10793 case Intrinsic::x86_sse2_psrai_d:
10794 case Intrinsic::x86_avx2_psrai_w:
10795 case Intrinsic::x86_avx2_psrai_d: {
10798 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10799 case Intrinsic::x86_sse2_pslli_w:
10800 case Intrinsic::x86_sse2_pslli_d:
10801 case Intrinsic::x86_sse2_pslli_q:
10802 case Intrinsic::x86_avx2_pslli_w:
10803 case Intrinsic::x86_avx2_pslli_d:
10804 case Intrinsic::x86_avx2_pslli_q:
10805 Opcode = X86ISD::VSHLI;
10807 case Intrinsic::x86_sse2_psrli_w:
10808 case Intrinsic::x86_sse2_psrli_d:
10809 case Intrinsic::x86_sse2_psrli_q:
10810 case Intrinsic::x86_avx2_psrli_w:
10811 case Intrinsic::x86_avx2_psrli_d:
10812 case Intrinsic::x86_avx2_psrli_q:
10813 Opcode = X86ISD::VSRLI;
10815 case Intrinsic::x86_sse2_psrai_w:
10816 case Intrinsic::x86_sse2_psrai_d:
10817 case Intrinsic::x86_avx2_psrai_w:
10818 case Intrinsic::x86_avx2_psrai_d:
10819 Opcode = X86ISD::VSRAI;
10822 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10823 Op.getOperand(1), Op.getOperand(2), DAG);
10826 case Intrinsic::x86_sse42_pcmpistria128:
10827 case Intrinsic::x86_sse42_pcmpestria128:
10828 case Intrinsic::x86_sse42_pcmpistric128:
10829 case Intrinsic::x86_sse42_pcmpestric128:
10830 case Intrinsic::x86_sse42_pcmpistrio128:
10831 case Intrinsic::x86_sse42_pcmpestrio128:
10832 case Intrinsic::x86_sse42_pcmpistris128:
10833 case Intrinsic::x86_sse42_pcmpestris128:
10834 case Intrinsic::x86_sse42_pcmpistriz128:
10835 case Intrinsic::x86_sse42_pcmpestriz128: {
10839 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10840 case Intrinsic::x86_sse42_pcmpistria128:
10841 Opcode = X86ISD::PCMPISTRI;
10842 X86CC = X86::COND_A;
10844 case Intrinsic::x86_sse42_pcmpestria128:
10845 Opcode = X86ISD::PCMPESTRI;
10846 X86CC = X86::COND_A;
10848 case Intrinsic::x86_sse42_pcmpistric128:
10849 Opcode = X86ISD::PCMPISTRI;
10850 X86CC = X86::COND_B;
10852 case Intrinsic::x86_sse42_pcmpestric128:
10853 Opcode = X86ISD::PCMPESTRI;
10854 X86CC = X86::COND_B;
10856 case Intrinsic::x86_sse42_pcmpistrio128:
10857 Opcode = X86ISD::PCMPISTRI;
10858 X86CC = X86::COND_O;
10860 case Intrinsic::x86_sse42_pcmpestrio128:
10861 Opcode = X86ISD::PCMPESTRI;
10862 X86CC = X86::COND_O;
10864 case Intrinsic::x86_sse42_pcmpistris128:
10865 Opcode = X86ISD::PCMPISTRI;
10866 X86CC = X86::COND_S;
10868 case Intrinsic::x86_sse42_pcmpestris128:
10869 Opcode = X86ISD::PCMPESTRI;
10870 X86CC = X86::COND_S;
10872 case Intrinsic::x86_sse42_pcmpistriz128:
10873 Opcode = X86ISD::PCMPISTRI;
10874 X86CC = X86::COND_E;
10876 case Intrinsic::x86_sse42_pcmpestriz128:
10877 Opcode = X86ISD::PCMPESTRI;
10878 X86CC = X86::COND_E;
10881 SmallVector<SDValue, 5> NewOps;
10882 NewOps.append(Op->op_begin()+1, Op->op_end());
10883 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10884 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10885 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10886 DAG.getConstant(X86CC, MVT::i8),
10887 SDValue(PCMP.getNode(), 1));
10888 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10891 case Intrinsic::x86_sse42_pcmpistri128:
10892 case Intrinsic::x86_sse42_pcmpestri128: {
10894 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10895 Opcode = X86ISD::PCMPISTRI;
10897 Opcode = X86ISD::PCMPESTRI;
10899 SmallVector<SDValue, 5> NewOps;
10900 NewOps.append(Op->op_begin()+1, Op->op_end());
10901 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10902 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10904 case Intrinsic::x86_fma_vfmadd_ps:
10905 case Intrinsic::x86_fma_vfmadd_pd:
10906 case Intrinsic::x86_fma_vfmsub_ps:
10907 case Intrinsic::x86_fma_vfmsub_pd:
10908 case Intrinsic::x86_fma_vfnmadd_ps:
10909 case Intrinsic::x86_fma_vfnmadd_pd:
10910 case Intrinsic::x86_fma_vfnmsub_ps:
10911 case Intrinsic::x86_fma_vfnmsub_pd:
10912 case Intrinsic::x86_fma_vfmaddsub_ps:
10913 case Intrinsic::x86_fma_vfmaddsub_pd:
10914 case Intrinsic::x86_fma_vfmsubadd_ps:
10915 case Intrinsic::x86_fma_vfmsubadd_pd:
10916 case Intrinsic::x86_fma_vfmadd_ps_256:
10917 case Intrinsic::x86_fma_vfmadd_pd_256:
10918 case Intrinsic::x86_fma_vfmsub_ps_256:
10919 case Intrinsic::x86_fma_vfmsub_pd_256:
10920 case Intrinsic::x86_fma_vfnmadd_ps_256:
10921 case Intrinsic::x86_fma_vfnmadd_pd_256:
10922 case Intrinsic::x86_fma_vfnmsub_ps_256:
10923 case Intrinsic::x86_fma_vfnmsub_pd_256:
10924 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10925 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10926 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10927 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10930 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10931 case Intrinsic::x86_fma_vfmadd_ps:
10932 case Intrinsic::x86_fma_vfmadd_pd:
10933 case Intrinsic::x86_fma_vfmadd_ps_256:
10934 case Intrinsic::x86_fma_vfmadd_pd_256:
10935 Opc = X86ISD::FMADD;
10937 case Intrinsic::x86_fma_vfmsub_ps:
10938 case Intrinsic::x86_fma_vfmsub_pd:
10939 case Intrinsic::x86_fma_vfmsub_ps_256:
10940 case Intrinsic::x86_fma_vfmsub_pd_256:
10941 Opc = X86ISD::FMSUB;
10943 case Intrinsic::x86_fma_vfnmadd_ps:
10944 case Intrinsic::x86_fma_vfnmadd_pd:
10945 case Intrinsic::x86_fma_vfnmadd_ps_256:
10946 case Intrinsic::x86_fma_vfnmadd_pd_256:
10947 Opc = X86ISD::FNMADD;
10949 case Intrinsic::x86_fma_vfnmsub_ps:
10950 case Intrinsic::x86_fma_vfnmsub_pd:
10951 case Intrinsic::x86_fma_vfnmsub_ps_256:
10952 case Intrinsic::x86_fma_vfnmsub_pd_256:
10953 Opc = X86ISD::FNMSUB;
10955 case Intrinsic::x86_fma_vfmaddsub_ps:
10956 case Intrinsic::x86_fma_vfmaddsub_pd:
10957 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10958 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10959 Opc = X86ISD::FMADDSUB;
10961 case Intrinsic::x86_fma_vfmsubadd_ps:
10962 case Intrinsic::x86_fma_vfmsubadd_pd:
10963 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10964 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10965 Opc = X86ISD::FMSUBADD;
10969 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10970 Op.getOperand(2), Op.getOperand(3));
10975 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10977 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10979 default: return SDValue(); // Don't custom lower most intrinsics.
10981 // RDRAND/RDSEED intrinsics.
10982 case Intrinsic::x86_rdrand_16:
10983 case Intrinsic::x86_rdrand_32:
10984 case Intrinsic::x86_rdrand_64:
10985 case Intrinsic::x86_rdseed_16:
10986 case Intrinsic::x86_rdseed_32:
10987 case Intrinsic::x86_rdseed_64: {
10988 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10989 IntNo == Intrinsic::x86_rdseed_32 ||
10990 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10992 // Emit the node with the right value type.
10993 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10994 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10996 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10997 // Otherwise return the value from Rand, which is always 0, casted to i32.
10998 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10999 DAG.getConstant(1, Op->getValueType(1)),
11000 DAG.getConstant(X86::COND_B, MVT::i32),
11001 SDValue(Result.getNode(), 1) };
11002 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11003 DAG.getVTList(Op->getValueType(1), MVT::Glue),
11004 Ops, array_lengthof(Ops));
11006 // Return { result, isValid, chain }.
11007 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11008 SDValue(Result.getNode(), 2));
11011 // XTEST intrinsics.
11012 case Intrinsic::x86_xtest: {
11013 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11014 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11015 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11016 DAG.getConstant(X86::COND_NE, MVT::i8),
11018 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11019 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11020 Ret, SDValue(InTrans.getNode(), 1));
11025 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11026 SelectionDAG &DAG) const {
11027 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11028 MFI->setReturnAddressIsTaken(true);
11030 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11032 EVT PtrVT = getPointerTy();
11035 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11037 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11038 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11039 DAG.getNode(ISD::ADD, dl, PtrVT,
11040 FrameAddr, Offset),
11041 MachinePointerInfo(), false, false, false, 0);
11044 // Just load the return address.
11045 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11046 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11047 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11050 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11051 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11052 MFI->setFrameAddressIsTaken(true);
11054 EVT VT = Op.getValueType();
11055 SDLoc dl(Op); // FIXME probably not meaningful
11056 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11057 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11058 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11059 (FrameReg == X86::EBP && VT == MVT::i32)) &&
11060 "Invalid Frame Register!");
11061 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11063 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11064 MachinePointerInfo(),
11065 false, false, false, 0);
11069 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11070 SelectionDAG &DAG) const {
11071 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11074 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11075 SDValue Chain = Op.getOperand(0);
11076 SDValue Offset = Op.getOperand(1);
11077 SDValue Handler = Op.getOperand(2);
11080 EVT PtrVT = getPointerTy();
11081 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11082 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11083 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11084 "Invalid Frame Register!");
11085 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11086 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11088 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11089 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11090 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11091 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11093 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11095 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11096 DAG.getRegister(StoreAddrReg, PtrVT));
11099 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11100 SelectionDAG &DAG) const {
11102 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11103 DAG.getVTList(MVT::i32, MVT::Other),
11104 Op.getOperand(0), Op.getOperand(1));
11107 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11108 SelectionDAG &DAG) const {
11110 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11111 Op.getOperand(0), Op.getOperand(1));
11114 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11115 return Op.getOperand(0);
11118 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11119 SelectionDAG &DAG) const {
11120 SDValue Root = Op.getOperand(0);
11121 SDValue Trmp = Op.getOperand(1); // trampoline
11122 SDValue FPtr = Op.getOperand(2); // nested function
11123 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11126 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11127 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11129 if (Subtarget->is64Bit()) {
11130 SDValue OutChains[6];
11132 // Large code-model.
11133 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
11134 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11136 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11137 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11139 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11141 // Load the pointer to the nested function into R11.
11142 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11143 SDValue Addr = Trmp;
11144 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11145 Addr, MachinePointerInfo(TrmpAddr),
11148 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11149 DAG.getConstant(2, MVT::i64));
11150 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11151 MachinePointerInfo(TrmpAddr, 2),
11154 // Load the 'nest' parameter value into R10.
11155 // R10 is specified in X86CallingConv.td
11156 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11157 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11158 DAG.getConstant(10, MVT::i64));
11159 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11160 Addr, MachinePointerInfo(TrmpAddr, 10),
11163 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11164 DAG.getConstant(12, MVT::i64));
11165 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11166 MachinePointerInfo(TrmpAddr, 12),
11169 // Jump to the nested function.
11170 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11171 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11172 DAG.getConstant(20, MVT::i64));
11173 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11174 Addr, MachinePointerInfo(TrmpAddr, 20),
11177 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11178 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11179 DAG.getConstant(22, MVT::i64));
11180 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11181 MachinePointerInfo(TrmpAddr, 22),
11184 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11186 const Function *Func =
11187 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11188 CallingConv::ID CC = Func->getCallingConv();
11193 llvm_unreachable("Unsupported calling convention");
11194 case CallingConv::C:
11195 case CallingConv::X86_StdCall: {
11196 // Pass 'nest' parameter in ECX.
11197 // Must be kept in sync with X86CallingConv.td
11198 NestReg = X86::ECX;
11200 // Check that ECX wasn't needed by an 'inreg' parameter.
11201 FunctionType *FTy = Func->getFunctionType();
11202 const AttributeSet &Attrs = Func->getAttributes();
11204 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11205 unsigned InRegCount = 0;
11208 for (FunctionType::param_iterator I = FTy->param_begin(),
11209 E = FTy->param_end(); I != E; ++I, ++Idx)
11210 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11211 // FIXME: should only count parameters that are lowered to integers.
11212 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11214 if (InRegCount > 2) {
11215 report_fatal_error("Nest register in use - reduce number of inreg"
11221 case CallingConv::X86_FastCall:
11222 case CallingConv::X86_ThisCall:
11223 case CallingConv::Fast:
11224 // Pass 'nest' parameter in EAX.
11225 // Must be kept in sync with X86CallingConv.td
11226 NestReg = X86::EAX;
11230 SDValue OutChains[4];
11231 SDValue Addr, Disp;
11233 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11234 DAG.getConstant(10, MVT::i32));
11235 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11237 // This is storing the opcode for MOV32ri.
11238 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11239 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11240 OutChains[0] = DAG.getStore(Root, dl,
11241 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11242 Trmp, MachinePointerInfo(TrmpAddr),
11245 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11246 DAG.getConstant(1, MVT::i32));
11247 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11248 MachinePointerInfo(TrmpAddr, 1),
11251 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11252 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11253 DAG.getConstant(5, MVT::i32));
11254 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11255 MachinePointerInfo(TrmpAddr, 5),
11258 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11259 DAG.getConstant(6, MVT::i32));
11260 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11261 MachinePointerInfo(TrmpAddr, 6),
11264 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11268 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11269 SelectionDAG &DAG) const {
11271 The rounding mode is in bits 11:10 of FPSR, and has the following
11273 00 Round to nearest
11278 FLT_ROUNDS, on the other hand, expects the following:
11285 To perform the conversion, we do:
11286 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11289 MachineFunction &MF = DAG.getMachineFunction();
11290 const TargetMachine &TM = MF.getTarget();
11291 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11292 unsigned StackAlignment = TFI.getStackAlignment();
11293 EVT VT = Op.getValueType();
11296 // Save FP Control Word to stack slot
11297 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11298 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11300 MachineMemOperand *MMO =
11301 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11302 MachineMemOperand::MOStore, 2, 2);
11304 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11305 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11306 DAG.getVTList(MVT::Other),
11307 Ops, array_lengthof(Ops), MVT::i16,
11310 // Load FP Control Word from stack slot
11311 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11312 MachinePointerInfo(), false, false, false, 0);
11314 // Transform as necessary
11316 DAG.getNode(ISD::SRL, DL, MVT::i16,
11317 DAG.getNode(ISD::AND, DL, MVT::i16,
11318 CWD, DAG.getConstant(0x800, MVT::i16)),
11319 DAG.getConstant(11, MVT::i8));
11321 DAG.getNode(ISD::SRL, DL, MVT::i16,
11322 DAG.getNode(ISD::AND, DL, MVT::i16,
11323 CWD, DAG.getConstant(0x400, MVT::i16)),
11324 DAG.getConstant(9, MVT::i8));
11327 DAG.getNode(ISD::AND, DL, MVT::i16,
11328 DAG.getNode(ISD::ADD, DL, MVT::i16,
11329 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11330 DAG.getConstant(1, MVT::i16)),
11331 DAG.getConstant(3, MVT::i16));
11333 return DAG.getNode((VT.getSizeInBits() < 16 ?
11334 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11337 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11338 EVT VT = Op.getValueType();
11340 unsigned NumBits = VT.getSizeInBits();
11343 Op = Op.getOperand(0);
11344 if (VT == MVT::i8) {
11345 // Zero extend to i32 since there is not an i8 bsr.
11347 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11350 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11351 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11352 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11354 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11357 DAG.getConstant(NumBits+NumBits-1, OpVT),
11358 DAG.getConstant(X86::COND_E, MVT::i8),
11361 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11363 // Finally xor with NumBits-1.
11364 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11367 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11371 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11372 EVT VT = Op.getValueType();
11374 unsigned NumBits = VT.getSizeInBits();
11377 Op = Op.getOperand(0);
11378 if (VT == MVT::i8) {
11379 // Zero extend to i32 since there is not an i8 bsr.
11381 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11384 // Issue a bsr (scan bits in reverse).
11385 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11386 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11388 // And xor with NumBits-1.
11389 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11392 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11396 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11397 EVT VT = Op.getValueType();
11398 unsigned NumBits = VT.getSizeInBits();
11400 Op = Op.getOperand(0);
11402 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11403 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11404 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11406 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11409 DAG.getConstant(NumBits, VT),
11410 DAG.getConstant(X86::COND_E, MVT::i8),
11413 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11416 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11417 // ones, and then concatenate the result back.
11418 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11419 EVT VT = Op.getValueType();
11421 assert(VT.is256BitVector() && VT.isInteger() &&
11422 "Unsupported value type for operation");
11424 unsigned NumElems = VT.getVectorNumElements();
11427 // Extract the LHS vectors
11428 SDValue LHS = Op.getOperand(0);
11429 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11430 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11432 // Extract the RHS vectors
11433 SDValue RHS = Op.getOperand(1);
11434 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11435 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11437 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11438 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11440 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11441 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11442 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11445 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11446 assert(Op.getValueType().is256BitVector() &&
11447 Op.getValueType().isInteger() &&
11448 "Only handle AVX 256-bit vector integer operation");
11449 return Lower256IntArith(Op, DAG);
11452 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11453 assert(Op.getValueType().is256BitVector() &&
11454 Op.getValueType().isInteger() &&
11455 "Only handle AVX 256-bit vector integer operation");
11456 return Lower256IntArith(Op, DAG);
11459 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11460 SelectionDAG &DAG) {
11462 EVT VT = Op.getValueType();
11464 // Decompose 256-bit ops into smaller 128-bit ops.
11465 if (VT.is256BitVector() && !Subtarget->hasInt256())
11466 return Lower256IntArith(Op, DAG);
11468 SDValue A = Op.getOperand(0);
11469 SDValue B = Op.getOperand(1);
11471 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11472 if (VT == MVT::v4i32) {
11473 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11474 "Should not custom lower when pmuldq is available!");
11476 // Extract the odd parts.
11477 const int UnpackMask[] = { 1, -1, 3, -1 };
11478 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11479 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11481 // Multiply the even parts.
11482 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11483 // Now multiply odd parts.
11484 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11486 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11487 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11489 // Merge the two vectors back together with a shuffle. This expands into 2
11491 const int ShufMask[] = { 0, 4, 2, 6 };
11492 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11495 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11496 "Only know how to lower V2I64/V4I64 multiply");
11498 // Ahi = psrlqi(a, 32);
11499 // Bhi = psrlqi(b, 32);
11501 // AloBlo = pmuludq(a, b);
11502 // AloBhi = pmuludq(a, Bhi);
11503 // AhiBlo = pmuludq(Ahi, b);
11505 // AloBhi = psllqi(AloBhi, 32);
11506 // AhiBlo = psllqi(AhiBlo, 32);
11507 // return AloBlo + AloBhi + AhiBlo;
11509 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11511 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11512 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11514 // Bit cast to 32-bit vectors for MULUDQ
11515 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11516 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11517 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11518 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11519 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11521 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11522 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11523 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11525 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11526 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11528 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11529 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11532 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11533 EVT VT = Op.getValueType();
11534 EVT EltTy = VT.getVectorElementType();
11535 unsigned NumElts = VT.getVectorNumElements();
11536 SDValue N0 = Op.getOperand(0);
11539 // Lower sdiv X, pow2-const.
11540 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11544 APInt SplatValue, SplatUndef;
11545 unsigned MinSplatBits;
11547 if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11550 if ((SplatValue != 0) &&
11551 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11552 unsigned lg2 = SplatValue.countTrailingZeros();
11553 // Splat the sign bit.
11554 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11555 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11556 // Add (N0 < 0) ? abs2 - 1 : 0;
11557 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11558 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11559 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11560 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11561 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11563 // If we're dividing by a positive value, we're done. Otherwise, we must
11564 // negate the result.
11565 if (SplatValue.isNonNegative())
11568 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11569 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11570 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11575 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11576 const X86Subtarget *Subtarget) {
11577 EVT VT = Op.getValueType();
11579 SDValue R = Op.getOperand(0);
11580 SDValue Amt = Op.getOperand(1);
11582 // Optimize shl/srl/sra with constant shift amount.
11583 if (isSplatVector(Amt.getNode())) {
11584 SDValue SclrAmt = Amt->getOperand(0);
11585 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11586 uint64_t ShiftAmt = C->getZExtValue();
11588 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11589 (Subtarget->hasInt256() &&
11590 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11591 if (Op.getOpcode() == ISD::SHL)
11592 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11593 DAG.getConstant(ShiftAmt, MVT::i32));
11594 if (Op.getOpcode() == ISD::SRL)
11595 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11596 DAG.getConstant(ShiftAmt, MVT::i32));
11597 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11598 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11599 DAG.getConstant(ShiftAmt, MVT::i32));
11602 if (VT == MVT::v16i8) {
11603 if (Op.getOpcode() == ISD::SHL) {
11604 // Make a large shift.
11605 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11606 DAG.getConstant(ShiftAmt, MVT::i32));
11607 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11608 // Zero out the rightmost bits.
11609 SmallVector<SDValue, 16> V(16,
11610 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11612 return DAG.getNode(ISD::AND, dl, VT, SHL,
11613 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11615 if (Op.getOpcode() == ISD::SRL) {
11616 // Make a large shift.
11617 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11618 DAG.getConstant(ShiftAmt, MVT::i32));
11619 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11620 // Zero out the leftmost bits.
11621 SmallVector<SDValue, 16> V(16,
11622 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11624 return DAG.getNode(ISD::AND, dl, VT, SRL,
11625 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11627 if (Op.getOpcode() == ISD::SRA) {
11628 if (ShiftAmt == 7) {
11629 // R s>> 7 === R s< 0
11630 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11631 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11634 // R s>> a === ((R u>> a) ^ m) - m
11635 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11636 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11638 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11639 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11640 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11643 llvm_unreachable("Unknown shift opcode.");
11646 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11647 if (Op.getOpcode() == ISD::SHL) {
11648 // Make a large shift.
11649 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11650 DAG.getConstant(ShiftAmt, MVT::i32));
11651 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11652 // Zero out the rightmost bits.
11653 SmallVector<SDValue, 32> V(32,
11654 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11656 return DAG.getNode(ISD::AND, dl, VT, SHL,
11657 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11659 if (Op.getOpcode() == ISD::SRL) {
11660 // Make a large shift.
11661 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11662 DAG.getConstant(ShiftAmt, MVT::i32));
11663 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11664 // Zero out the leftmost bits.
11665 SmallVector<SDValue, 32> V(32,
11666 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11668 return DAG.getNode(ISD::AND, dl, VT, SRL,
11669 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11671 if (Op.getOpcode() == ISD::SRA) {
11672 if (ShiftAmt == 7) {
11673 // R s>> 7 === R s< 0
11674 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11675 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11678 // R s>> a === ((R u>> a) ^ m) - m
11679 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11680 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11682 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11683 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11684 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11687 llvm_unreachable("Unknown shift opcode.");
11692 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11693 if (!Subtarget->is64Bit() &&
11694 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11695 Amt.getOpcode() == ISD::BITCAST &&
11696 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11697 Amt = Amt.getOperand(0);
11698 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11699 VT.getVectorNumElements();
11700 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11701 uint64_t ShiftAmt = 0;
11702 for (unsigned i = 0; i != Ratio; ++i) {
11703 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11707 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11709 // Check remaining shift amounts.
11710 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11711 uint64_t ShAmt = 0;
11712 for (unsigned j = 0; j != Ratio; ++j) {
11713 ConstantSDNode *C =
11714 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11718 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11720 if (ShAmt != ShiftAmt)
11723 switch (Op.getOpcode()) {
11725 llvm_unreachable("Unknown shift opcode!");
11727 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11728 DAG.getConstant(ShiftAmt, MVT::i32));
11730 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11731 DAG.getConstant(ShiftAmt, MVT::i32));
11733 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11734 DAG.getConstant(ShiftAmt, MVT::i32));
11741 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11742 const X86Subtarget* Subtarget) {
11743 EVT VT = Op.getValueType();
11745 SDValue R = Op.getOperand(0);
11746 SDValue Amt = Op.getOperand(1);
11748 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11749 VT == MVT::v4i32 || VT == MVT::v8i16 ||
11750 (Subtarget->hasInt256() &&
11751 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11752 VT == MVT::v8i32 || VT == MVT::v16i16))) {
11754 EVT EltVT = VT.getVectorElementType();
11756 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11757 unsigned NumElts = VT.getVectorNumElements();
11759 for (i = 0; i != NumElts; ++i) {
11760 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11764 for (j = i; j != NumElts; ++j) {
11765 SDValue Arg = Amt.getOperand(j);
11766 if (Arg.getOpcode() == ISD::UNDEF) continue;
11767 if (Arg != Amt.getOperand(i))
11770 if (i != NumElts && j == NumElts)
11771 BaseShAmt = Amt.getOperand(i);
11773 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11774 Amt = Amt.getOperand(0);
11775 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11776 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11777 SDValue InVec = Amt.getOperand(0);
11778 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11779 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11781 for (; i != NumElts; ++i) {
11782 SDValue Arg = InVec.getOperand(i);
11783 if (Arg.getOpcode() == ISD::UNDEF) continue;
11787 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11788 if (ConstantSDNode *C =
11789 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11790 unsigned SplatIdx =
11791 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11792 if (C->getZExtValue() == SplatIdx)
11793 BaseShAmt = InVec.getOperand(1);
11796 if (BaseShAmt.getNode() == 0)
11797 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11798 DAG.getIntPtrConstant(0));
11802 if (BaseShAmt.getNode()) {
11803 if (EltVT.bitsGT(MVT::i32))
11804 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11805 else if (EltVT.bitsLT(MVT::i32))
11806 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11808 switch (Op.getOpcode()) {
11810 llvm_unreachable("Unknown shift opcode!");
11812 switch (VT.getSimpleVT().SimpleTy) {
11813 default: return SDValue();
11820 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11823 switch (VT.getSimpleVT().SimpleTy) {
11824 default: return SDValue();
11829 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11832 switch (VT.getSimpleVT().SimpleTy) {
11833 default: return SDValue();
11840 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11846 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11847 if (!Subtarget->is64Bit() &&
11848 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11849 Amt.getOpcode() == ISD::BITCAST &&
11850 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11851 Amt = Amt.getOperand(0);
11852 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11853 VT.getVectorNumElements();
11854 std::vector<SDValue> Vals(Ratio);
11855 for (unsigned i = 0; i != Ratio; ++i)
11856 Vals[i] = Amt.getOperand(i);
11857 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11858 for (unsigned j = 0; j != Ratio; ++j)
11859 if (Vals[j] != Amt.getOperand(i + j))
11862 switch (Op.getOpcode()) {
11864 llvm_unreachable("Unknown shift opcode!");
11866 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11868 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11870 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11877 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11879 EVT VT = Op.getValueType();
11881 SDValue R = Op.getOperand(0);
11882 SDValue Amt = Op.getOperand(1);
11885 if (!Subtarget->hasSSE2())
11888 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11892 V = LowerScalarVariableShift(Op, DAG, Subtarget);
11896 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11897 if (Subtarget->hasInt256()) {
11898 if (Op.getOpcode() == ISD::SRL &&
11899 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11900 VT == MVT::v4i64 || VT == MVT::v8i32))
11902 if (Op.getOpcode() == ISD::SHL &&
11903 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11904 VT == MVT::v4i64 || VT == MVT::v8i32))
11906 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11910 // Lower SHL with variable shift amount.
11911 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11912 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11914 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11915 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11916 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11917 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11919 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11920 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11923 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11924 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11926 // Turn 'a' into a mask suitable for VSELECT
11927 SDValue VSelM = DAG.getConstant(0x80, VT);
11928 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11929 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11931 SDValue CM1 = DAG.getConstant(0x0f, VT);
11932 SDValue CM2 = DAG.getConstant(0x3f, VT);
11934 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11935 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11936 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11937 DAG.getConstant(4, MVT::i32), DAG);
11938 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11939 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11942 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11943 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11944 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11946 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11947 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11948 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11949 DAG.getConstant(2, MVT::i32), DAG);
11950 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11951 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11954 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11955 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11956 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11958 // return VSELECT(r, r+r, a);
11959 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11960 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11964 // Decompose 256-bit shifts into smaller 128-bit shifts.
11965 if (VT.is256BitVector()) {
11966 unsigned NumElems = VT.getVectorNumElements();
11967 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11968 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11970 // Extract the two vectors
11971 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11972 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11974 // Recreate the shift amount vectors
11975 SDValue Amt1, Amt2;
11976 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11977 // Constant shift amount
11978 SmallVector<SDValue, 4> Amt1Csts;
11979 SmallVector<SDValue, 4> Amt2Csts;
11980 for (unsigned i = 0; i != NumElems/2; ++i)
11981 Amt1Csts.push_back(Amt->getOperand(i));
11982 for (unsigned i = NumElems/2; i != NumElems; ++i)
11983 Amt2Csts.push_back(Amt->getOperand(i));
11985 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11986 &Amt1Csts[0], NumElems/2);
11987 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11988 &Amt2Csts[0], NumElems/2);
11990 // Variable shift amount
11991 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11992 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11995 // Issue new vector shifts for the smaller types
11996 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11997 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11999 // Concatenate the result back
12000 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12006 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12007 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12008 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12009 // looks for this combo and may remove the "setcc" instruction if the "setcc"
12010 // has only one use.
12011 SDNode *N = Op.getNode();
12012 SDValue LHS = N->getOperand(0);
12013 SDValue RHS = N->getOperand(1);
12014 unsigned BaseOp = 0;
12017 switch (Op.getOpcode()) {
12018 default: llvm_unreachable("Unknown ovf instruction!");
12020 // A subtract of one will be selected as a INC. Note that INC doesn't
12021 // set CF, so we can't do this for UADDO.
12022 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12024 BaseOp = X86ISD::INC;
12025 Cond = X86::COND_O;
12028 BaseOp = X86ISD::ADD;
12029 Cond = X86::COND_O;
12032 BaseOp = X86ISD::ADD;
12033 Cond = X86::COND_B;
12036 // A subtract of one will be selected as a DEC. Note that DEC doesn't
12037 // set CF, so we can't do this for USUBO.
12038 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12040 BaseOp = X86ISD::DEC;
12041 Cond = X86::COND_O;
12044 BaseOp = X86ISD::SUB;
12045 Cond = X86::COND_O;
12048 BaseOp = X86ISD::SUB;
12049 Cond = X86::COND_B;
12052 BaseOp = X86ISD::SMUL;
12053 Cond = X86::COND_O;
12055 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12056 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12058 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12061 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12062 DAG.getConstant(X86::COND_O, MVT::i32),
12063 SDValue(Sum.getNode(), 2));
12065 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12069 // Also sets EFLAGS.
12070 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12071 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12074 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12075 DAG.getConstant(Cond, MVT::i32),
12076 SDValue(Sum.getNode(), 1));
12078 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12081 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12082 SelectionDAG &DAG) const {
12084 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12085 EVT VT = Op.getValueType();
12087 if (!Subtarget->hasSSE2() || !VT.isVector())
12090 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12091 ExtraVT.getScalarType().getSizeInBits();
12092 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12094 switch (VT.getSimpleVT().SimpleTy) {
12095 default: return SDValue();
12098 if (!Subtarget->hasFp256())
12100 if (!Subtarget->hasInt256()) {
12101 // needs to be split
12102 unsigned NumElems = VT.getVectorNumElements();
12104 // Extract the LHS vectors
12105 SDValue LHS = Op.getOperand(0);
12106 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12107 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12109 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12110 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12112 EVT ExtraEltVT = ExtraVT.getVectorElementType();
12113 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12114 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12116 SDValue Extra = DAG.getValueType(ExtraVT);
12118 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12119 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12121 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12126 // (sext (vzext x)) -> (vsext x)
12127 SDValue Op0 = Op.getOperand(0);
12128 SDValue Op00 = Op0.getOperand(0);
12130 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12131 if (Op0.getOpcode() == ISD::BITCAST &&
12132 Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12133 Tmp1 = LowerVectorIntExtend(Op00, DAG);
12134 if (Tmp1.getNode()) {
12135 SDValue Tmp1Op0 = Tmp1.getOperand(0);
12136 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12137 "This optimization is invalid without a VZEXT.");
12138 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12141 // If the above didn't work, then just use Shift-Left + Shift-Right.
12142 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12143 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12148 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12149 SelectionDAG &DAG) {
12151 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12152 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12153 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12154 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12156 // The only fence that needs an instruction is a sequentially-consistent
12157 // cross-thread fence.
12158 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12159 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12160 // no-sse2). There isn't any reason to disable it if the target processor
12162 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12163 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12165 SDValue Chain = Op.getOperand(0);
12166 SDValue Zero = DAG.getConstant(0, MVT::i32);
12168 DAG.getRegister(X86::ESP, MVT::i32), // Base
12169 DAG.getTargetConstant(1, MVT::i8), // Scale
12170 DAG.getRegister(0, MVT::i32), // Index
12171 DAG.getTargetConstant(0, MVT::i32), // Disp
12172 DAG.getRegister(0, MVT::i32), // Segment.
12176 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12177 return SDValue(Res, 0);
12180 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12181 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12184 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12185 SelectionDAG &DAG) {
12186 EVT T = Op.getValueType();
12190 switch(T.getSimpleVT().SimpleTy) {
12191 default: llvm_unreachable("Invalid value type!");
12192 case MVT::i8: Reg = X86::AL; size = 1; break;
12193 case MVT::i16: Reg = X86::AX; size = 2; break;
12194 case MVT::i32: Reg = X86::EAX; size = 4; break;
12196 assert(Subtarget->is64Bit() && "Node not type legal!");
12197 Reg = X86::RAX; size = 8;
12200 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12201 Op.getOperand(2), SDValue());
12202 SDValue Ops[] = { cpIn.getValue(0),
12205 DAG.getTargetConstant(size, MVT::i8),
12206 cpIn.getValue(1) };
12207 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12208 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12209 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12210 Ops, array_lengthof(Ops), T, MMO);
12212 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12216 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12217 SelectionDAG &DAG) {
12218 assert(Subtarget->is64Bit() && "Result not type legalized?");
12219 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12220 SDValue TheChain = Op.getOperand(0);
12222 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12223 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12224 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12226 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12227 DAG.getConstant(32, MVT::i8));
12229 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12232 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12235 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12236 EVT SrcVT = Op.getOperand(0).getValueType();
12237 EVT DstVT = Op.getValueType();
12238 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12239 Subtarget->hasMMX() && "Unexpected custom BITCAST");
12240 assert((DstVT == MVT::i64 ||
12241 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12242 "Unexpected custom BITCAST");
12243 // i64 <=> MMX conversions are Legal.
12244 if (SrcVT==MVT::i64 && DstVT.isVector())
12246 if (DstVT==MVT::i64 && SrcVT.isVector())
12248 // MMX <=> MMX conversions are Legal.
12249 if (SrcVT.isVector() && DstVT.isVector())
12251 // All other conversions need to be expanded.
12255 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12256 SDNode *Node = Op.getNode();
12258 EVT T = Node->getValueType(0);
12259 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12260 DAG.getConstant(0, T), Node->getOperand(2));
12261 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12262 cast<AtomicSDNode>(Node)->getMemoryVT(),
12263 Node->getOperand(0),
12264 Node->getOperand(1), negOp,
12265 cast<AtomicSDNode>(Node)->getSrcValue(),
12266 cast<AtomicSDNode>(Node)->getAlignment(),
12267 cast<AtomicSDNode>(Node)->getOrdering(),
12268 cast<AtomicSDNode>(Node)->getSynchScope());
12271 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12272 SDNode *Node = Op.getNode();
12274 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12276 // Convert seq_cst store -> xchg
12277 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12278 // FIXME: On 32-bit, store -> fist or movq would be more efficient
12279 // (The only way to get a 16-byte store is cmpxchg16b)
12280 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12281 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12282 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12283 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12284 cast<AtomicSDNode>(Node)->getMemoryVT(),
12285 Node->getOperand(0),
12286 Node->getOperand(1), Node->getOperand(2),
12287 cast<AtomicSDNode>(Node)->getMemOperand(),
12288 cast<AtomicSDNode>(Node)->getOrdering(),
12289 cast<AtomicSDNode>(Node)->getSynchScope());
12290 return Swap.getValue(1);
12292 // Other atomic stores have a simple pattern.
12296 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12297 EVT VT = Op.getNode()->getValueType(0);
12299 // Let legalize expand this if it isn't a legal type yet.
12300 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12303 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12306 bool ExtraOp = false;
12307 switch (Op.getOpcode()) {
12308 default: llvm_unreachable("Invalid code");
12309 case ISD::ADDC: Opc = X86ISD::ADD; break;
12310 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12311 case ISD::SUBC: Opc = X86ISD::SUB; break;
12312 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12316 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12318 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12319 Op.getOperand(1), Op.getOperand(2));
12322 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12323 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12325 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12326 // which returns the values as { float, float } (in XMM0) or
12327 // { double, double } (which is returned in XMM0, XMM1).
12329 SDValue Arg = Op.getOperand(0);
12330 EVT ArgVT = Arg.getValueType();
12331 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12334 ArgListEntry Entry;
12338 Entry.isSExt = false;
12339 Entry.isZExt = false;
12340 Args.push_back(Entry);
12342 bool isF64 = ArgVT == MVT::f64;
12343 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12344 // the small struct {f32, f32} is returned in (eax, edx). For f64,
12345 // the results are returned via SRet in memory.
12346 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
12347 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12349 Type *RetTy = isF64
12350 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12351 : (Type*)VectorType::get(ArgTy, 4);
12353 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12354 false, false, false, false, 0,
12355 CallingConv::C, /*isTaillCall=*/false,
12356 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12357 Callee, Args, DAG, dl);
12358 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12361 // Returned in xmm0 and xmm1.
12362 return CallResult.first;
12364 // Returned in bits 0:31 and 32:64 xmm0.
12365 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12366 CallResult.first, DAG.getIntPtrConstant(0));
12367 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12368 CallResult.first, DAG.getIntPtrConstant(1));
12369 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12370 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12373 /// LowerOperation - Provide custom lowering hooks for some operations.
12375 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12376 switch (Op.getOpcode()) {
12377 default: llvm_unreachable("Should not custom lower this!");
12378 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12379 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12380 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12381 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12382 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12383 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12384 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12385 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12386 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12387 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12388 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12389 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12390 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12391 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12392 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12393 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12394 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12395 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12396 case ISD::SHL_PARTS:
12397 case ISD::SRA_PARTS:
12398 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12399 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12400 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12401 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12402 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12403 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12404 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12405 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12406 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12407 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12408 case ISD::FABS: return LowerFABS(Op, DAG);
12409 case ISD::FNEG: return LowerFNEG(Op, DAG);
12410 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12411 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12412 case ISD::SETCC: return LowerSETCC(Op, DAG);
12413 case ISD::SELECT: return LowerSELECT(Op, DAG);
12414 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12415 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12416 case ISD::VASTART: return LowerVASTART(Op, DAG);
12417 case ISD::VAARG: return LowerVAARG(Op, DAG);
12418 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12419 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12420 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12421 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12422 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12423 case ISD::FRAME_TO_ARGS_OFFSET:
12424 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12425 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12426 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12427 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12428 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12429 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12430 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12431 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12432 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12433 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12434 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12435 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12438 case ISD::SHL: return LowerShift(Op, DAG);
12444 case ISD::UMULO: return LowerXALUO(Op, DAG);
12445 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12446 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12450 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12451 case ISD::ADD: return LowerADD(Op, DAG);
12452 case ISD::SUB: return LowerSUB(Op, DAG);
12453 case ISD::SDIV: return LowerSDIV(Op, DAG);
12454 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
12458 static void ReplaceATOMIC_LOAD(SDNode *Node,
12459 SmallVectorImpl<SDValue> &Results,
12460 SelectionDAG &DAG) {
12462 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12464 // Convert wide load -> cmpxchg8b/cmpxchg16b
12465 // FIXME: On 32-bit, load -> fild or movq would be more efficient
12466 // (The only way to get a 16-byte load is cmpxchg16b)
12467 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12468 SDValue Zero = DAG.getConstant(0, VT);
12469 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12470 Node->getOperand(0),
12471 Node->getOperand(1), Zero, Zero,
12472 cast<AtomicSDNode>(Node)->getMemOperand(),
12473 cast<AtomicSDNode>(Node)->getOrdering(),
12474 cast<AtomicSDNode>(Node)->getSynchScope());
12475 Results.push_back(Swap.getValue(0));
12476 Results.push_back(Swap.getValue(1));
12480 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12481 SelectionDAG &DAG, unsigned NewOp) {
12483 assert (Node->getValueType(0) == MVT::i64 &&
12484 "Only know how to expand i64 atomics");
12486 SDValue Chain = Node->getOperand(0);
12487 SDValue In1 = Node->getOperand(1);
12488 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12489 Node->getOperand(2), DAG.getIntPtrConstant(0));
12490 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12491 Node->getOperand(2), DAG.getIntPtrConstant(1));
12492 SDValue Ops[] = { Chain, In1, In2L, In2H };
12493 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12495 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12496 cast<MemSDNode>(Node)->getMemOperand());
12497 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12498 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12499 Results.push_back(Result.getValue(2));
12502 /// ReplaceNodeResults - Replace a node with an illegal result type
12503 /// with a new node built out of custom code.
12504 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12505 SmallVectorImpl<SDValue>&Results,
12506 SelectionDAG &DAG) const {
12508 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12509 switch (N->getOpcode()) {
12511 llvm_unreachable("Do not know how to custom type legalize this operation!");
12512 case ISD::SIGN_EXTEND_INREG:
12517 // We don't want to expand or promote these.
12519 case ISD::FP_TO_SINT:
12520 case ISD::FP_TO_UINT: {
12521 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12523 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12526 std::pair<SDValue,SDValue> Vals =
12527 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12528 SDValue FIST = Vals.first, StackSlot = Vals.second;
12529 if (FIST.getNode() != 0) {
12530 EVT VT = N->getValueType(0);
12531 // Return a load from the stack slot.
12532 if (StackSlot.getNode() != 0)
12533 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12534 MachinePointerInfo(),
12535 false, false, false, 0));
12537 Results.push_back(FIST);
12541 case ISD::UINT_TO_FP: {
12542 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12543 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12544 N->getValueType(0) != MVT::v2f32)
12546 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12548 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12550 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12551 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12552 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12553 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12554 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12555 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12558 case ISD::FP_ROUND: {
12559 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12561 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12562 Results.push_back(V);
12565 case ISD::READCYCLECOUNTER: {
12566 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12567 SDValue TheChain = N->getOperand(0);
12568 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12569 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12571 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12573 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12574 SDValue Ops[] = { eax, edx };
12575 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12576 array_lengthof(Ops)));
12577 Results.push_back(edx.getValue(1));
12580 case ISD::ATOMIC_CMP_SWAP: {
12581 EVT T = N->getValueType(0);
12582 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12583 bool Regs64bit = T == MVT::i128;
12584 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12585 SDValue cpInL, cpInH;
12586 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12587 DAG.getConstant(0, HalfT));
12588 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12589 DAG.getConstant(1, HalfT));
12590 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12591 Regs64bit ? X86::RAX : X86::EAX,
12593 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12594 Regs64bit ? X86::RDX : X86::EDX,
12595 cpInH, cpInL.getValue(1));
12596 SDValue swapInL, swapInH;
12597 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12598 DAG.getConstant(0, HalfT));
12599 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12600 DAG.getConstant(1, HalfT));
12601 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12602 Regs64bit ? X86::RBX : X86::EBX,
12603 swapInL, cpInH.getValue(1));
12604 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12605 Regs64bit ? X86::RCX : X86::ECX,
12606 swapInH, swapInL.getValue(1));
12607 SDValue Ops[] = { swapInH.getValue(0),
12609 swapInH.getValue(1) };
12610 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12611 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12612 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12613 X86ISD::LCMPXCHG8_DAG;
12614 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12615 Ops, array_lengthof(Ops), T, MMO);
12616 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12617 Regs64bit ? X86::RAX : X86::EAX,
12618 HalfT, Result.getValue(1));
12619 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12620 Regs64bit ? X86::RDX : X86::EDX,
12621 HalfT, cpOutL.getValue(2));
12622 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12623 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12624 Results.push_back(cpOutH.getValue(1));
12627 case ISD::ATOMIC_LOAD_ADD:
12628 case ISD::ATOMIC_LOAD_AND:
12629 case ISD::ATOMIC_LOAD_NAND:
12630 case ISD::ATOMIC_LOAD_OR:
12631 case ISD::ATOMIC_LOAD_SUB:
12632 case ISD::ATOMIC_LOAD_XOR:
12633 case ISD::ATOMIC_LOAD_MAX:
12634 case ISD::ATOMIC_LOAD_MIN:
12635 case ISD::ATOMIC_LOAD_UMAX:
12636 case ISD::ATOMIC_LOAD_UMIN:
12637 case ISD::ATOMIC_SWAP: {
12639 switch (N->getOpcode()) {
12640 default: llvm_unreachable("Unexpected opcode");
12641 case ISD::ATOMIC_LOAD_ADD:
12642 Opc = X86ISD::ATOMADD64_DAG;
12644 case ISD::ATOMIC_LOAD_AND:
12645 Opc = X86ISD::ATOMAND64_DAG;
12647 case ISD::ATOMIC_LOAD_NAND:
12648 Opc = X86ISD::ATOMNAND64_DAG;
12650 case ISD::ATOMIC_LOAD_OR:
12651 Opc = X86ISD::ATOMOR64_DAG;
12653 case ISD::ATOMIC_LOAD_SUB:
12654 Opc = X86ISD::ATOMSUB64_DAG;
12656 case ISD::ATOMIC_LOAD_XOR:
12657 Opc = X86ISD::ATOMXOR64_DAG;
12659 case ISD::ATOMIC_LOAD_MAX:
12660 Opc = X86ISD::ATOMMAX64_DAG;
12662 case ISD::ATOMIC_LOAD_MIN:
12663 Opc = X86ISD::ATOMMIN64_DAG;
12665 case ISD::ATOMIC_LOAD_UMAX:
12666 Opc = X86ISD::ATOMUMAX64_DAG;
12668 case ISD::ATOMIC_LOAD_UMIN:
12669 Opc = X86ISD::ATOMUMIN64_DAG;
12671 case ISD::ATOMIC_SWAP:
12672 Opc = X86ISD::ATOMSWAP64_DAG;
12675 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12678 case ISD::ATOMIC_LOAD:
12679 ReplaceATOMIC_LOAD(N, Results, DAG);
12683 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12685 default: return NULL;
12686 case X86ISD::BSF: return "X86ISD::BSF";
12687 case X86ISD::BSR: return "X86ISD::BSR";
12688 case X86ISD::SHLD: return "X86ISD::SHLD";
12689 case X86ISD::SHRD: return "X86ISD::SHRD";
12690 case X86ISD::FAND: return "X86ISD::FAND";
12691 case X86ISD::FOR: return "X86ISD::FOR";
12692 case X86ISD::FXOR: return "X86ISD::FXOR";
12693 case X86ISD::FSRL: return "X86ISD::FSRL";
12694 case X86ISD::FILD: return "X86ISD::FILD";
12695 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12696 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12697 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12698 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12699 case X86ISD::FLD: return "X86ISD::FLD";
12700 case X86ISD::FST: return "X86ISD::FST";
12701 case X86ISD::CALL: return "X86ISD::CALL";
12702 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12703 case X86ISD::BT: return "X86ISD::BT";
12704 case X86ISD::CMP: return "X86ISD::CMP";
12705 case X86ISD::COMI: return "X86ISD::COMI";
12706 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12707 case X86ISD::SETCC: return "X86ISD::SETCC";
12708 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12709 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12710 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12711 case X86ISD::CMOV: return "X86ISD::CMOV";
12712 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12713 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12714 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12715 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12716 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12717 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12718 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12719 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12720 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12721 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12722 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12723 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12724 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12725 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12726 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12727 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12728 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12729 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12730 case X86ISD::HADD: return "X86ISD::HADD";
12731 case X86ISD::HSUB: return "X86ISD::HSUB";
12732 case X86ISD::FHADD: return "X86ISD::FHADD";
12733 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12734 case X86ISD::UMAX: return "X86ISD::UMAX";
12735 case X86ISD::UMIN: return "X86ISD::UMIN";
12736 case X86ISD::SMAX: return "X86ISD::SMAX";
12737 case X86ISD::SMIN: return "X86ISD::SMIN";
12738 case X86ISD::FMAX: return "X86ISD::FMAX";
12739 case X86ISD::FMIN: return "X86ISD::FMIN";
12740 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12741 case X86ISD::FMINC: return "X86ISD::FMINC";
12742 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12743 case X86ISD::FRCP: return "X86ISD::FRCP";
12744 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12745 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12746 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12747 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12748 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12749 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12750 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12751 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12752 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12753 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12754 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12755 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12756 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12757 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12758 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12759 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12760 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12761 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12762 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12763 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12764 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12765 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12766 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12767 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12768 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12769 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12770 case X86ISD::VSHL: return "X86ISD::VSHL";
12771 case X86ISD::VSRL: return "X86ISD::VSRL";
12772 case X86ISD::VSRA: return "X86ISD::VSRA";
12773 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12774 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12775 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12776 case X86ISD::CMPP: return "X86ISD::CMPP";
12777 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12778 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12779 case X86ISD::ADD: return "X86ISD::ADD";
12780 case X86ISD::SUB: return "X86ISD::SUB";
12781 case X86ISD::ADC: return "X86ISD::ADC";
12782 case X86ISD::SBB: return "X86ISD::SBB";
12783 case X86ISD::SMUL: return "X86ISD::SMUL";
12784 case X86ISD::UMUL: return "X86ISD::UMUL";
12785 case X86ISD::INC: return "X86ISD::INC";
12786 case X86ISD::DEC: return "X86ISD::DEC";
12787 case X86ISD::OR: return "X86ISD::OR";
12788 case X86ISD::XOR: return "X86ISD::XOR";
12789 case X86ISD::AND: return "X86ISD::AND";
12790 case X86ISD::BLSI: return "X86ISD::BLSI";
12791 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12792 case X86ISD::BLSR: return "X86ISD::BLSR";
12793 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12794 case X86ISD::PTEST: return "X86ISD::PTEST";
12795 case X86ISD::TESTP: return "X86ISD::TESTP";
12796 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
12797 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12798 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12799 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12800 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12801 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12802 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12803 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12804 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12805 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12806 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12807 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12808 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12809 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12810 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12811 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12812 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12813 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12814 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12815 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12816 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12817 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12818 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12819 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12820 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12821 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12822 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12823 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12824 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12825 case X86ISD::SAHF: return "X86ISD::SAHF";
12826 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12827 case X86ISD::RDSEED: return "X86ISD::RDSEED";
12828 case X86ISD::FMADD: return "X86ISD::FMADD";
12829 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12830 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12831 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12832 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12833 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12834 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12835 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12836 case X86ISD::XTEST: return "X86ISD::XTEST";
12840 // isLegalAddressingMode - Return true if the addressing mode represented
12841 // by AM is legal for this target, for a load/store of the specified type.
12842 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12844 // X86 supports extremely general addressing modes.
12845 CodeModel::Model M = getTargetMachine().getCodeModel();
12846 Reloc::Model R = getTargetMachine().getRelocationModel();
12848 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12849 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12854 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12856 // If a reference to this global requires an extra load, we can't fold it.
12857 if (isGlobalStubReference(GVFlags))
12860 // If BaseGV requires a register for the PIC base, we cannot also have a
12861 // BaseReg specified.
12862 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12865 // If lower 4G is not available, then we must use rip-relative addressing.
12866 if ((M != CodeModel::Small || R != Reloc::Static) &&
12867 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12871 switch (AM.Scale) {
12877 // These scales always work.
12882 // These scales are formed with basereg+scalereg. Only accept if there is
12887 default: // Other stuff never works.
12894 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12895 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12897 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12898 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12899 return NumBits1 > NumBits2;
12902 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12903 return isInt<32>(Imm);
12906 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12907 // Can also use sub to handle negated immediates.
12908 return isInt<32>(Imm);
12911 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12912 if (!VT1.isInteger() || !VT2.isInteger())
12914 unsigned NumBits1 = VT1.getSizeInBits();
12915 unsigned NumBits2 = VT2.getSizeInBits();
12916 return NumBits1 > NumBits2;
12919 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12920 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12921 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12924 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12925 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12926 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12929 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12930 EVT VT1 = Val.getValueType();
12931 if (isZExtFree(VT1, VT2))
12934 if (Val.getOpcode() != ISD::LOAD)
12937 if (!VT1.isSimple() || !VT1.isInteger() ||
12938 !VT2.isSimple() || !VT2.isInteger())
12941 switch (VT1.getSimpleVT().SimpleTy) {
12946 // X86 has 8, 16, and 32-bit zero-extending loads.
12953 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12954 // i16 instructions are longer (0x66 prefix) and potentially slower.
12955 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12958 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12959 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12960 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12961 /// are assumed to be legal.
12963 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12965 // Very little shuffling can be done for 64-bit vectors right now.
12966 if (VT.getSizeInBits() == 64)
12969 // FIXME: pshufb, blends, shifts.
12970 return (VT.getVectorNumElements() == 2 ||
12971 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12972 isMOVLMask(M, VT) ||
12973 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12974 isPSHUFDMask(M, VT) ||
12975 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12976 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12977 isPALIGNRMask(M, VT, Subtarget) ||
12978 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12979 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12980 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12981 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12985 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12987 unsigned NumElts = VT.getVectorNumElements();
12988 // FIXME: This collection of masks seems suspect.
12991 if (NumElts == 4 && VT.is128BitVector()) {
12992 return (isMOVLMask(Mask, VT) ||
12993 isCommutedMOVLMask(Mask, VT, true) ||
12994 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12995 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13000 //===----------------------------------------------------------------------===//
13001 // X86 Scheduler Hooks
13002 //===----------------------------------------------------------------------===//
13004 /// Utility function to emit xbegin specifying the start of an RTM region.
13005 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13006 const TargetInstrInfo *TII) {
13007 DebugLoc DL = MI->getDebugLoc();
13009 const BasicBlock *BB = MBB->getBasicBlock();
13010 MachineFunction::iterator I = MBB;
13013 // For the v = xbegin(), we generate
13024 MachineBasicBlock *thisMBB = MBB;
13025 MachineFunction *MF = MBB->getParent();
13026 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13027 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13028 MF->insert(I, mainMBB);
13029 MF->insert(I, sinkMBB);
13031 // Transfer the remainder of BB and its successor edges to sinkMBB.
13032 sinkMBB->splice(sinkMBB->begin(), MBB,
13033 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13034 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13038 // # fallthrough to mainMBB
13039 // # abortion to sinkMBB
13040 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13041 thisMBB->addSuccessor(mainMBB);
13042 thisMBB->addSuccessor(sinkMBB);
13046 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13047 mainMBB->addSuccessor(sinkMBB);
13050 // EAX is live into the sinkMBB
13051 sinkMBB->addLiveIn(X86::EAX);
13052 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13053 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13056 MI->eraseFromParent();
13060 // Get CMPXCHG opcode for the specified data type.
13061 static unsigned getCmpXChgOpcode(EVT VT) {
13062 switch (VT.getSimpleVT().SimpleTy) {
13063 case MVT::i8: return X86::LCMPXCHG8;
13064 case MVT::i16: return X86::LCMPXCHG16;
13065 case MVT::i32: return X86::LCMPXCHG32;
13066 case MVT::i64: return X86::LCMPXCHG64;
13070 llvm_unreachable("Invalid operand size!");
13073 // Get LOAD opcode for the specified data type.
13074 static unsigned getLoadOpcode(EVT VT) {
13075 switch (VT.getSimpleVT().SimpleTy) {
13076 case MVT::i8: return X86::MOV8rm;
13077 case MVT::i16: return X86::MOV16rm;
13078 case MVT::i32: return X86::MOV32rm;
13079 case MVT::i64: return X86::MOV64rm;
13083 llvm_unreachable("Invalid operand size!");
13086 // Get opcode of the non-atomic one from the specified atomic instruction.
13087 static unsigned getNonAtomicOpcode(unsigned Opc) {
13089 case X86::ATOMAND8: return X86::AND8rr;
13090 case X86::ATOMAND16: return X86::AND16rr;
13091 case X86::ATOMAND32: return X86::AND32rr;
13092 case X86::ATOMAND64: return X86::AND64rr;
13093 case X86::ATOMOR8: return X86::OR8rr;
13094 case X86::ATOMOR16: return X86::OR16rr;
13095 case X86::ATOMOR32: return X86::OR32rr;
13096 case X86::ATOMOR64: return X86::OR64rr;
13097 case X86::ATOMXOR8: return X86::XOR8rr;
13098 case X86::ATOMXOR16: return X86::XOR16rr;
13099 case X86::ATOMXOR32: return X86::XOR32rr;
13100 case X86::ATOMXOR64: return X86::XOR64rr;
13102 llvm_unreachable("Unhandled atomic-load-op opcode!");
13105 // Get opcode of the non-atomic one from the specified atomic instruction with
13107 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13108 unsigned &ExtraOpc) {
13110 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
13111 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
13112 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
13113 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
13114 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
13115 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13116 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13117 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13118 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
13119 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13120 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13121 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13122 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
13123 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13124 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13125 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13126 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
13127 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13128 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13129 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13131 llvm_unreachable("Unhandled atomic-load-op opcode!");
13134 // Get opcode of the non-atomic one from the specified atomic instruction for
13135 // 64-bit data type on 32-bit target.
13136 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13138 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
13139 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
13140 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
13141 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
13142 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
13143 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13144 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
13145 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
13146 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
13147 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
13149 llvm_unreachable("Unhandled atomic-load-op opcode!");
13152 // Get opcode of the non-atomic one from the specified atomic instruction for
13153 // 64-bit data type on 32-bit target with extra opcode.
13154 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13156 unsigned &ExtraOpc) {
13158 case X86::ATOMNAND6432:
13159 ExtraOpc = X86::NOT32r;
13160 HiOpc = X86::AND32rr;
13161 return X86::AND32rr;
13163 llvm_unreachable("Unhandled atomic-load-op opcode!");
13166 // Get pseudo CMOV opcode from the specified data type.
13167 static unsigned getPseudoCMOVOpc(EVT VT) {
13168 switch (VT.getSimpleVT().SimpleTy) {
13169 case MVT::i8: return X86::CMOV_GR8;
13170 case MVT::i16: return X86::CMOV_GR16;
13171 case MVT::i32: return X86::CMOV_GR32;
13175 llvm_unreachable("Unknown CMOV opcode!");
13178 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13179 // They will be translated into a spin-loop or compare-exchange loop from
13182 // dst = atomic-fetch-op MI.addr, MI.val
13188 // t1 = LOAD MI.addr
13190 // t4 = phi(t1, t3 / loop)
13191 // t2 = OP MI.val, t4
13193 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13199 MachineBasicBlock *
13200 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13201 MachineBasicBlock *MBB) const {
13202 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13203 DebugLoc DL = MI->getDebugLoc();
13205 MachineFunction *MF = MBB->getParent();
13206 MachineRegisterInfo &MRI = MF->getRegInfo();
13208 const BasicBlock *BB = MBB->getBasicBlock();
13209 MachineFunction::iterator I = MBB;
13212 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13213 "Unexpected number of operands");
13215 assert(MI->hasOneMemOperand() &&
13216 "Expected atomic-load-op to have one memoperand");
13218 // Memory Reference
13219 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13220 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13222 unsigned DstReg, SrcReg;
13223 unsigned MemOpndSlot;
13225 unsigned CurOp = 0;
13227 DstReg = MI->getOperand(CurOp++).getReg();
13228 MemOpndSlot = CurOp;
13229 CurOp += X86::AddrNumOperands;
13230 SrcReg = MI->getOperand(CurOp++).getReg();
13232 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13233 MVT::SimpleValueType VT = *RC->vt_begin();
13234 unsigned t1 = MRI.createVirtualRegister(RC);
13235 unsigned t2 = MRI.createVirtualRegister(RC);
13236 unsigned t3 = MRI.createVirtualRegister(RC);
13237 unsigned t4 = MRI.createVirtualRegister(RC);
13238 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13240 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13241 unsigned LOADOpc = getLoadOpcode(VT);
13243 // For the atomic load-arith operator, we generate
13246 // t1 = LOAD [MI.addr]
13248 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
13249 // t1 = OP MI.val, EAX
13251 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13257 MachineBasicBlock *thisMBB = MBB;
13258 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13259 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13260 MF->insert(I, mainMBB);
13261 MF->insert(I, sinkMBB);
13263 MachineInstrBuilder MIB;
13265 // Transfer the remainder of BB and its successor edges to sinkMBB.
13266 sinkMBB->splice(sinkMBB->begin(), MBB,
13267 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13268 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13271 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13272 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13273 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13275 NewMO.setIsKill(false);
13276 MIB.addOperand(NewMO);
13278 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13279 unsigned flags = (*MMOI)->getFlags();
13280 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13281 MachineMemOperand *MMO =
13282 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13283 (*MMOI)->getSize(),
13284 (*MMOI)->getBaseAlignment(),
13285 (*MMOI)->getTBAAInfo(),
13286 (*MMOI)->getRanges());
13287 MIB.addMemOperand(MMO);
13290 thisMBB->addSuccessor(mainMBB);
13293 MachineBasicBlock *origMainMBB = mainMBB;
13296 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13297 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13299 unsigned Opc = MI->getOpcode();
13302 llvm_unreachable("Unhandled atomic-load-op opcode!");
13303 case X86::ATOMAND8:
13304 case X86::ATOMAND16:
13305 case X86::ATOMAND32:
13306 case X86::ATOMAND64:
13308 case X86::ATOMOR16:
13309 case X86::ATOMOR32:
13310 case X86::ATOMOR64:
13311 case X86::ATOMXOR8:
13312 case X86::ATOMXOR16:
13313 case X86::ATOMXOR32:
13314 case X86::ATOMXOR64: {
13315 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13316 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13320 case X86::ATOMNAND8:
13321 case X86::ATOMNAND16:
13322 case X86::ATOMNAND32:
13323 case X86::ATOMNAND64: {
13324 unsigned Tmp = MRI.createVirtualRegister(RC);
13326 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13327 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13329 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13332 case X86::ATOMMAX8:
13333 case X86::ATOMMAX16:
13334 case X86::ATOMMAX32:
13335 case X86::ATOMMAX64:
13336 case X86::ATOMMIN8:
13337 case X86::ATOMMIN16:
13338 case X86::ATOMMIN32:
13339 case X86::ATOMMIN64:
13340 case X86::ATOMUMAX8:
13341 case X86::ATOMUMAX16:
13342 case X86::ATOMUMAX32:
13343 case X86::ATOMUMAX64:
13344 case X86::ATOMUMIN8:
13345 case X86::ATOMUMIN16:
13346 case X86::ATOMUMIN32:
13347 case X86::ATOMUMIN64: {
13349 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13351 BuildMI(mainMBB, DL, TII->get(CMPOpc))
13355 if (Subtarget->hasCMov()) {
13356 if (VT != MVT::i8) {
13358 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13362 // Promote i8 to i32 to use CMOV32
13363 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13364 const TargetRegisterClass *RC32 =
13365 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13366 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13367 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13368 unsigned Tmp = MRI.createVirtualRegister(RC32);
13370 unsigned Undef = MRI.createVirtualRegister(RC32);
13371 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13373 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13376 .addImm(X86::sub_8bit);
13377 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13380 .addImm(X86::sub_8bit);
13382 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13386 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13387 .addReg(Tmp, 0, X86::sub_8bit);
13390 // Use pseudo select and lower them.
13391 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13392 "Invalid atomic-load-op transformation!");
13393 unsigned SelOpc = getPseudoCMOVOpc(VT);
13394 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13395 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13396 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13397 .addReg(SrcReg).addReg(t4)
13399 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13400 // Replace the original PHI node as mainMBB is changed after CMOV
13402 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13403 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13404 Phi->eraseFromParent();
13410 // Copy PhyReg back from virtual register.
13411 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13414 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13415 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13416 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13418 NewMO.setIsKill(false);
13419 MIB.addOperand(NewMO);
13422 MIB.setMemRefs(MMOBegin, MMOEnd);
13424 // Copy PhyReg back to virtual register.
13425 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13428 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13430 mainMBB->addSuccessor(origMainMBB);
13431 mainMBB->addSuccessor(sinkMBB);
13434 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13435 TII->get(TargetOpcode::COPY), DstReg)
13438 MI->eraseFromParent();
13442 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13443 // instructions. They will be translated into a spin-loop or compare-exchange
13447 // dst = atomic-fetch-op MI.addr, MI.val
13453 // t1L = LOAD [MI.addr + 0]
13454 // t1H = LOAD [MI.addr + 4]
13456 // t4L = phi(t1L, t3L / loop)
13457 // t4H = phi(t1H, t3H / loop)
13458 // t2L = OP MI.val.lo, t4L
13459 // t2H = OP MI.val.hi, t4H
13464 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13472 MachineBasicBlock *
13473 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13474 MachineBasicBlock *MBB) const {
13475 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13476 DebugLoc DL = MI->getDebugLoc();
13478 MachineFunction *MF = MBB->getParent();
13479 MachineRegisterInfo &MRI = MF->getRegInfo();
13481 const BasicBlock *BB = MBB->getBasicBlock();
13482 MachineFunction::iterator I = MBB;
13485 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13486 "Unexpected number of operands");
13488 assert(MI->hasOneMemOperand() &&
13489 "Expected atomic-load-op32 to have one memoperand");
13491 // Memory Reference
13492 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13493 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13495 unsigned DstLoReg, DstHiReg;
13496 unsigned SrcLoReg, SrcHiReg;
13497 unsigned MemOpndSlot;
13499 unsigned CurOp = 0;
13501 DstLoReg = MI->getOperand(CurOp++).getReg();
13502 DstHiReg = MI->getOperand(CurOp++).getReg();
13503 MemOpndSlot = CurOp;
13504 CurOp += X86::AddrNumOperands;
13505 SrcLoReg = MI->getOperand(CurOp++).getReg();
13506 SrcHiReg = MI->getOperand(CurOp++).getReg();
13508 const TargetRegisterClass *RC = &X86::GR32RegClass;
13509 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13511 unsigned t1L = MRI.createVirtualRegister(RC);
13512 unsigned t1H = MRI.createVirtualRegister(RC);
13513 unsigned t2L = MRI.createVirtualRegister(RC);
13514 unsigned t2H = MRI.createVirtualRegister(RC);
13515 unsigned t3L = MRI.createVirtualRegister(RC);
13516 unsigned t3H = MRI.createVirtualRegister(RC);
13517 unsigned t4L = MRI.createVirtualRegister(RC);
13518 unsigned t4H = MRI.createVirtualRegister(RC);
13520 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13521 unsigned LOADOpc = X86::MOV32rm;
13523 // For the atomic load-arith operator, we generate
13526 // t1L = LOAD [MI.addr + 0]
13527 // t1H = LOAD [MI.addr + 4]
13529 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
13530 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
13531 // t2L = OP MI.val.lo, t4L
13532 // t2H = OP MI.val.hi, t4H
13535 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13543 MachineBasicBlock *thisMBB = MBB;
13544 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13545 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13546 MF->insert(I, mainMBB);
13547 MF->insert(I, sinkMBB);
13549 MachineInstrBuilder MIB;
13551 // Transfer the remainder of BB and its successor edges to sinkMBB.
13552 sinkMBB->splice(sinkMBB->begin(), MBB,
13553 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13554 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13558 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13559 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13560 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13562 NewMO.setIsKill(false);
13563 MIB.addOperand(NewMO);
13565 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13566 unsigned flags = (*MMOI)->getFlags();
13567 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13568 MachineMemOperand *MMO =
13569 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13570 (*MMOI)->getSize(),
13571 (*MMOI)->getBaseAlignment(),
13572 (*MMOI)->getTBAAInfo(),
13573 (*MMOI)->getRanges());
13574 MIB.addMemOperand(MMO);
13576 MachineInstr *LowMI = MIB;
13579 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13580 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13581 if (i == X86::AddrDisp) {
13582 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13584 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13586 NewMO.setIsKill(false);
13587 MIB.addOperand(NewMO);
13590 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13592 thisMBB->addSuccessor(mainMBB);
13595 MachineBasicBlock *origMainMBB = mainMBB;
13598 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13599 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13600 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13601 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13603 unsigned Opc = MI->getOpcode();
13606 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13607 case X86::ATOMAND6432:
13608 case X86::ATOMOR6432:
13609 case X86::ATOMXOR6432:
13610 case X86::ATOMADD6432:
13611 case X86::ATOMSUB6432: {
13613 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13614 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13616 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13620 case X86::ATOMNAND6432: {
13621 unsigned HiOpc, NOTOpc;
13622 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13623 unsigned TmpL = MRI.createVirtualRegister(RC);
13624 unsigned TmpH = MRI.createVirtualRegister(RC);
13625 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13627 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13629 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13630 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13633 case X86::ATOMMAX6432:
13634 case X86::ATOMMIN6432:
13635 case X86::ATOMUMAX6432:
13636 case X86::ATOMUMIN6432: {
13638 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13639 unsigned cL = MRI.createVirtualRegister(RC8);
13640 unsigned cH = MRI.createVirtualRegister(RC8);
13641 unsigned cL32 = MRI.createVirtualRegister(RC);
13642 unsigned cH32 = MRI.createVirtualRegister(RC);
13643 unsigned cc = MRI.createVirtualRegister(RC);
13644 // cl := cmp src_lo, lo
13645 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13646 .addReg(SrcLoReg).addReg(t4L);
13647 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13648 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13649 // ch := cmp src_hi, hi
13650 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13651 .addReg(SrcHiReg).addReg(t4H);
13652 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13653 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13654 // cc := if (src_hi == hi) ? cl : ch;
13655 if (Subtarget->hasCMov()) {
13656 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13657 .addReg(cH32).addReg(cL32);
13659 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13660 .addReg(cH32).addReg(cL32)
13661 .addImm(X86::COND_E);
13662 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13664 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13665 if (Subtarget->hasCMov()) {
13666 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13667 .addReg(SrcLoReg).addReg(t4L);
13668 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13669 .addReg(SrcHiReg).addReg(t4H);
13671 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13672 .addReg(SrcLoReg).addReg(t4L)
13673 .addImm(X86::COND_NE);
13674 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13675 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13676 // 2nd CMOV lowering.
13677 mainMBB->addLiveIn(X86::EFLAGS);
13678 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13679 .addReg(SrcHiReg).addReg(t4H)
13680 .addImm(X86::COND_NE);
13681 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13682 // Replace the original PHI node as mainMBB is changed after CMOV
13684 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13685 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13686 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13687 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13688 PhiL->eraseFromParent();
13689 PhiH->eraseFromParent();
13693 case X86::ATOMSWAP6432: {
13695 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13696 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13697 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13702 // Copy EDX:EAX back from HiReg:LoReg
13703 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13704 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13705 // Copy ECX:EBX from t1H:t1L
13706 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13707 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13709 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13710 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13711 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13713 NewMO.setIsKill(false);
13714 MIB.addOperand(NewMO);
13716 MIB.setMemRefs(MMOBegin, MMOEnd);
13718 // Copy EDX:EAX back to t3H:t3L
13719 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13720 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13722 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13724 mainMBB->addSuccessor(origMainMBB);
13725 mainMBB->addSuccessor(sinkMBB);
13728 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13729 TII->get(TargetOpcode::COPY), DstLoReg)
13731 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13732 TII->get(TargetOpcode::COPY), DstHiReg)
13735 MI->eraseFromParent();
13739 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13740 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13741 // in the .td file.
13742 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13743 const TargetInstrInfo *TII) {
13745 switch (MI->getOpcode()) {
13746 default: llvm_unreachable("illegal opcode!");
13747 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
13748 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13749 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
13750 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13751 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
13752 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13753 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
13754 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13757 DebugLoc dl = MI->getDebugLoc();
13758 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13760 unsigned NumArgs = MI->getNumOperands();
13761 for (unsigned i = 1; i < NumArgs; ++i) {
13762 MachineOperand &Op = MI->getOperand(i);
13763 if (!(Op.isReg() && Op.isImplicit()))
13764 MIB.addOperand(Op);
13766 if (MI->hasOneMemOperand())
13767 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13769 BuildMI(*BB, MI, dl,
13770 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13771 .addReg(X86::XMM0);
13773 MI->eraseFromParent();
13777 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13778 // defs in an instruction pattern
13779 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13780 const TargetInstrInfo *TII) {
13782 switch (MI->getOpcode()) {
13783 default: llvm_unreachable("illegal opcode!");
13784 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
13785 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13786 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
13787 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13788 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13789 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13790 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13791 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13794 DebugLoc dl = MI->getDebugLoc();
13795 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13797 unsigned NumArgs = MI->getNumOperands(); // remove the results
13798 for (unsigned i = 1; i < NumArgs; ++i) {
13799 MachineOperand &Op = MI->getOperand(i);
13800 if (!(Op.isReg() && Op.isImplicit()))
13801 MIB.addOperand(Op);
13803 if (MI->hasOneMemOperand())
13804 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13806 BuildMI(*BB, MI, dl,
13807 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13810 MI->eraseFromParent();
13814 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13815 const TargetInstrInfo *TII,
13816 const X86Subtarget* Subtarget) {
13817 DebugLoc dl = MI->getDebugLoc();
13819 // Address into RAX/EAX, other two args into ECX, EDX.
13820 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13821 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13822 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13823 for (int i = 0; i < X86::AddrNumOperands; ++i)
13824 MIB.addOperand(MI->getOperand(i));
13826 unsigned ValOps = X86::AddrNumOperands;
13827 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13828 .addReg(MI->getOperand(ValOps).getReg());
13829 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13830 .addReg(MI->getOperand(ValOps+1).getReg());
13832 // The instruction doesn't actually take any operands though.
13833 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13835 MI->eraseFromParent(); // The pseudo is gone now.
13839 MachineBasicBlock *
13840 X86TargetLowering::EmitVAARG64WithCustomInserter(
13842 MachineBasicBlock *MBB) const {
13843 // Emit va_arg instruction on X86-64.
13845 // Operands to this pseudo-instruction:
13846 // 0 ) Output : destination address (reg)
13847 // 1-5) Input : va_list address (addr, i64mem)
13848 // 6 ) ArgSize : Size (in bytes) of vararg type
13849 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13850 // 8 ) Align : Alignment of type
13851 // 9 ) EFLAGS (implicit-def)
13853 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13854 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13856 unsigned DestReg = MI->getOperand(0).getReg();
13857 MachineOperand &Base = MI->getOperand(1);
13858 MachineOperand &Scale = MI->getOperand(2);
13859 MachineOperand &Index = MI->getOperand(3);
13860 MachineOperand &Disp = MI->getOperand(4);
13861 MachineOperand &Segment = MI->getOperand(5);
13862 unsigned ArgSize = MI->getOperand(6).getImm();
13863 unsigned ArgMode = MI->getOperand(7).getImm();
13864 unsigned Align = MI->getOperand(8).getImm();
13866 // Memory Reference
13867 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13868 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13869 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13871 // Machine Information
13872 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13873 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13874 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13875 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13876 DebugLoc DL = MI->getDebugLoc();
13878 // struct va_list {
13881 // i64 overflow_area (address)
13882 // i64 reg_save_area (address)
13884 // sizeof(va_list) = 24
13885 // alignment(va_list) = 8
13887 unsigned TotalNumIntRegs = 6;
13888 unsigned TotalNumXMMRegs = 8;
13889 bool UseGPOffset = (ArgMode == 1);
13890 bool UseFPOffset = (ArgMode == 2);
13891 unsigned MaxOffset = TotalNumIntRegs * 8 +
13892 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13894 /* Align ArgSize to a multiple of 8 */
13895 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13896 bool NeedsAlign = (Align > 8);
13898 MachineBasicBlock *thisMBB = MBB;
13899 MachineBasicBlock *overflowMBB;
13900 MachineBasicBlock *offsetMBB;
13901 MachineBasicBlock *endMBB;
13903 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13904 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13905 unsigned OffsetReg = 0;
13907 if (!UseGPOffset && !UseFPOffset) {
13908 // If we only pull from the overflow region, we don't create a branch.
13909 // We don't need to alter control flow.
13910 OffsetDestReg = 0; // unused
13911 OverflowDestReg = DestReg;
13914 overflowMBB = thisMBB;
13917 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13918 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13919 // If not, pull from overflow_area. (branch to overflowMBB)
13924 // offsetMBB overflowMBB
13929 // Registers for the PHI in endMBB
13930 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13931 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13933 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13934 MachineFunction *MF = MBB->getParent();
13935 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13936 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13937 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13939 MachineFunction::iterator MBBIter = MBB;
13942 // Insert the new basic blocks
13943 MF->insert(MBBIter, offsetMBB);
13944 MF->insert(MBBIter, overflowMBB);
13945 MF->insert(MBBIter, endMBB);
13947 // Transfer the remainder of MBB and its successor edges to endMBB.
13948 endMBB->splice(endMBB->begin(), thisMBB,
13949 llvm::next(MachineBasicBlock::iterator(MI)),
13951 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13953 // Make offsetMBB and overflowMBB successors of thisMBB
13954 thisMBB->addSuccessor(offsetMBB);
13955 thisMBB->addSuccessor(overflowMBB);
13957 // endMBB is a successor of both offsetMBB and overflowMBB
13958 offsetMBB->addSuccessor(endMBB);
13959 overflowMBB->addSuccessor(endMBB);
13961 // Load the offset value into a register
13962 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13963 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13967 .addDisp(Disp, UseFPOffset ? 4 : 0)
13968 .addOperand(Segment)
13969 .setMemRefs(MMOBegin, MMOEnd);
13971 // Check if there is enough room left to pull this argument.
13972 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13974 .addImm(MaxOffset + 8 - ArgSizeA8);
13976 // Branch to "overflowMBB" if offset >= max
13977 // Fall through to "offsetMBB" otherwise
13978 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13979 .addMBB(overflowMBB);
13982 // In offsetMBB, emit code to use the reg_save_area.
13984 assert(OffsetReg != 0);
13986 // Read the reg_save_area address.
13987 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13988 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13993 .addOperand(Segment)
13994 .setMemRefs(MMOBegin, MMOEnd);
13996 // Zero-extend the offset
13997 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13998 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14001 .addImm(X86::sub_32bit);
14003 // Add the offset to the reg_save_area to get the final address.
14004 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14005 .addReg(OffsetReg64)
14006 .addReg(RegSaveReg);
14008 // Compute the offset for the next argument
14009 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14010 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14012 .addImm(UseFPOffset ? 16 : 8);
14014 // Store it back into the va_list.
14015 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14019 .addDisp(Disp, UseFPOffset ? 4 : 0)
14020 .addOperand(Segment)
14021 .addReg(NextOffsetReg)
14022 .setMemRefs(MMOBegin, MMOEnd);
14025 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14030 // Emit code to use overflow area
14033 // Load the overflow_area address into a register.
14034 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14035 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14040 .addOperand(Segment)
14041 .setMemRefs(MMOBegin, MMOEnd);
14043 // If we need to align it, do so. Otherwise, just copy the address
14044 // to OverflowDestReg.
14046 // Align the overflow address
14047 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14048 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14050 // aligned_addr = (addr + (align-1)) & ~(align-1)
14051 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14052 .addReg(OverflowAddrReg)
14055 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14057 .addImm(~(uint64_t)(Align-1));
14059 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14060 .addReg(OverflowAddrReg);
14063 // Compute the next overflow address after this argument.
14064 // (the overflow address should be kept 8-byte aligned)
14065 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14066 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14067 .addReg(OverflowDestReg)
14068 .addImm(ArgSizeA8);
14070 // Store the new overflow address.
14071 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14076 .addOperand(Segment)
14077 .addReg(NextAddrReg)
14078 .setMemRefs(MMOBegin, MMOEnd);
14080 // If we branched, emit the PHI to the front of endMBB.
14082 BuildMI(*endMBB, endMBB->begin(), DL,
14083 TII->get(X86::PHI), DestReg)
14084 .addReg(OffsetDestReg).addMBB(offsetMBB)
14085 .addReg(OverflowDestReg).addMBB(overflowMBB);
14088 // Erase the pseudo instruction
14089 MI->eraseFromParent();
14094 MachineBasicBlock *
14095 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14097 MachineBasicBlock *MBB) const {
14098 // Emit code to save XMM registers to the stack. The ABI says that the
14099 // number of registers to save is given in %al, so it's theoretically
14100 // possible to do an indirect jump trick to avoid saving all of them,
14101 // however this code takes a simpler approach and just executes all
14102 // of the stores if %al is non-zero. It's less code, and it's probably
14103 // easier on the hardware branch predictor, and stores aren't all that
14104 // expensive anyway.
14106 // Create the new basic blocks. One block contains all the XMM stores,
14107 // and one block is the final destination regardless of whether any
14108 // stores were performed.
14109 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14110 MachineFunction *F = MBB->getParent();
14111 MachineFunction::iterator MBBIter = MBB;
14113 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14114 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14115 F->insert(MBBIter, XMMSaveMBB);
14116 F->insert(MBBIter, EndMBB);
14118 // Transfer the remainder of MBB and its successor edges to EndMBB.
14119 EndMBB->splice(EndMBB->begin(), MBB,
14120 llvm::next(MachineBasicBlock::iterator(MI)),
14122 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14124 // The original block will now fall through to the XMM save block.
14125 MBB->addSuccessor(XMMSaveMBB);
14126 // The XMMSaveMBB will fall through to the end block.
14127 XMMSaveMBB->addSuccessor(EndMBB);
14129 // Now add the instructions.
14130 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14131 DebugLoc DL = MI->getDebugLoc();
14133 unsigned CountReg = MI->getOperand(0).getReg();
14134 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14135 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14137 if (!Subtarget->isTargetWin64()) {
14138 // If %al is 0, branch around the XMM save block.
14139 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14140 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14141 MBB->addSuccessor(EndMBB);
14144 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14145 // In the XMM save block, save all the XMM argument registers.
14146 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14147 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14148 MachineMemOperand *MMO =
14149 F->getMachineMemOperand(
14150 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14151 MachineMemOperand::MOStore,
14152 /*Size=*/16, /*Align=*/16);
14153 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14154 .addFrameIndex(RegSaveFrameIndex)
14155 .addImm(/*Scale=*/1)
14156 .addReg(/*IndexReg=*/0)
14157 .addImm(/*Disp=*/Offset)
14158 .addReg(/*Segment=*/0)
14159 .addReg(MI->getOperand(i).getReg())
14160 .addMemOperand(MMO);
14163 MI->eraseFromParent(); // The pseudo instruction is gone now.
14168 // The EFLAGS operand of SelectItr might be missing a kill marker
14169 // because there were multiple uses of EFLAGS, and ISel didn't know
14170 // which to mark. Figure out whether SelectItr should have had a
14171 // kill marker, and set it if it should. Returns the correct kill
14173 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14174 MachineBasicBlock* BB,
14175 const TargetRegisterInfo* TRI) {
14176 // Scan forward through BB for a use/def of EFLAGS.
14177 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14178 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14179 const MachineInstr& mi = *miI;
14180 if (mi.readsRegister(X86::EFLAGS))
14182 if (mi.definesRegister(X86::EFLAGS))
14183 break; // Should have kill-flag - update below.
14186 // If we hit the end of the block, check whether EFLAGS is live into a
14188 if (miI == BB->end()) {
14189 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14190 sEnd = BB->succ_end();
14191 sItr != sEnd; ++sItr) {
14192 MachineBasicBlock* succ = *sItr;
14193 if (succ->isLiveIn(X86::EFLAGS))
14198 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14199 // out. SelectMI should have a kill flag on EFLAGS.
14200 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14204 MachineBasicBlock *
14205 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14206 MachineBasicBlock *BB) const {
14207 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14208 DebugLoc DL = MI->getDebugLoc();
14210 // To "insert" a SELECT_CC instruction, we actually have to insert the
14211 // diamond control-flow pattern. The incoming instruction knows the
14212 // destination vreg to set, the condition code register to branch on, the
14213 // true/false values to select between, and a branch opcode to use.
14214 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14215 MachineFunction::iterator It = BB;
14221 // cmpTY ccX, r1, r2
14223 // fallthrough --> copy0MBB
14224 MachineBasicBlock *thisMBB = BB;
14225 MachineFunction *F = BB->getParent();
14226 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14227 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14228 F->insert(It, copy0MBB);
14229 F->insert(It, sinkMBB);
14231 // If the EFLAGS register isn't dead in the terminator, then claim that it's
14232 // live into the sink and copy blocks.
14233 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14234 if (!MI->killsRegister(X86::EFLAGS) &&
14235 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14236 copy0MBB->addLiveIn(X86::EFLAGS);
14237 sinkMBB->addLiveIn(X86::EFLAGS);
14240 // Transfer the remainder of BB and its successor edges to sinkMBB.
14241 sinkMBB->splice(sinkMBB->begin(), BB,
14242 llvm::next(MachineBasicBlock::iterator(MI)),
14244 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14246 // Add the true and fallthrough blocks as its successors.
14247 BB->addSuccessor(copy0MBB);
14248 BB->addSuccessor(sinkMBB);
14250 // Create the conditional branch instruction.
14252 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14253 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14256 // %FalseValue = ...
14257 // # fallthrough to sinkMBB
14258 copy0MBB->addSuccessor(sinkMBB);
14261 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14263 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14264 TII->get(X86::PHI), MI->getOperand(0).getReg())
14265 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14266 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14268 MI->eraseFromParent(); // The pseudo instruction is gone now.
14272 MachineBasicBlock *
14273 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14274 bool Is64Bit) const {
14275 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14276 DebugLoc DL = MI->getDebugLoc();
14277 MachineFunction *MF = BB->getParent();
14278 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14280 assert(getTargetMachine().Options.EnableSegmentedStacks);
14282 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14283 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14286 // ... [Till the alloca]
14287 // If stacklet is not large enough, jump to mallocMBB
14290 // Allocate by subtracting from RSP
14291 // Jump to continueMBB
14294 // Allocate by call to runtime
14298 // [rest of original BB]
14301 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14302 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14303 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14305 MachineRegisterInfo &MRI = MF->getRegInfo();
14306 const TargetRegisterClass *AddrRegClass =
14307 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14309 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14310 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14311 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14312 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14313 sizeVReg = MI->getOperand(1).getReg(),
14314 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14316 MachineFunction::iterator MBBIter = BB;
14319 MF->insert(MBBIter, bumpMBB);
14320 MF->insert(MBBIter, mallocMBB);
14321 MF->insert(MBBIter, continueMBB);
14323 continueMBB->splice(continueMBB->begin(), BB, llvm::next
14324 (MachineBasicBlock::iterator(MI)), BB->end());
14325 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14327 // Add code to the main basic block to check if the stack limit has been hit,
14328 // and if so, jump to mallocMBB otherwise to bumpMBB.
14329 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14330 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14331 .addReg(tmpSPVReg).addReg(sizeVReg);
14332 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14333 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14334 .addReg(SPLimitVReg);
14335 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14337 // bumpMBB simply decreases the stack pointer, since we know the current
14338 // stacklet has enough space.
14339 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14340 .addReg(SPLimitVReg);
14341 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14342 .addReg(SPLimitVReg);
14343 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14345 // Calls into a routine in libgcc to allocate more space from the heap.
14346 const uint32_t *RegMask =
14347 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14349 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14351 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14352 .addExternalSymbol("__morestack_allocate_stack_space")
14353 .addRegMask(RegMask)
14354 .addReg(X86::RDI, RegState::Implicit)
14355 .addReg(X86::RAX, RegState::ImplicitDefine);
14357 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14359 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14360 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14361 .addExternalSymbol("__morestack_allocate_stack_space")
14362 .addRegMask(RegMask)
14363 .addReg(X86::EAX, RegState::ImplicitDefine);
14367 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14370 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14371 .addReg(Is64Bit ? X86::RAX : X86::EAX);
14372 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14374 // Set up the CFG correctly.
14375 BB->addSuccessor(bumpMBB);
14376 BB->addSuccessor(mallocMBB);
14377 mallocMBB->addSuccessor(continueMBB);
14378 bumpMBB->addSuccessor(continueMBB);
14380 // Take care of the PHI nodes.
14381 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14382 MI->getOperand(0).getReg())
14383 .addReg(mallocPtrVReg).addMBB(mallocMBB)
14384 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14386 // Delete the original pseudo instruction.
14387 MI->eraseFromParent();
14390 return continueMBB;
14393 MachineBasicBlock *
14394 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14395 MachineBasicBlock *BB) const {
14396 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14397 DebugLoc DL = MI->getDebugLoc();
14399 assert(!Subtarget->isTargetEnvMacho());
14401 // The lowering is pretty easy: we're just emitting the call to _alloca. The
14402 // non-trivial part is impdef of ESP.
14404 if (Subtarget->isTargetWin64()) {
14405 if (Subtarget->isTargetCygMing()) {
14406 // ___chkstk(Mingw64):
14407 // Clobbers R10, R11, RAX and EFLAGS.
14409 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14410 .addExternalSymbol("___chkstk")
14411 .addReg(X86::RAX, RegState::Implicit)
14412 .addReg(X86::RSP, RegState::Implicit)
14413 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14414 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14415 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14417 // __chkstk(MSVCRT): does not update stack pointer.
14418 // Clobbers R10, R11 and EFLAGS.
14419 // FIXME: RAX(allocated size) might be reused and not killed.
14420 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14421 .addExternalSymbol("__chkstk")
14422 .addReg(X86::RAX, RegState::Implicit)
14423 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14424 // RAX has the offset to subtracted from RSP.
14425 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14430 const char *StackProbeSymbol =
14431 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14433 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14434 .addExternalSymbol(StackProbeSymbol)
14435 .addReg(X86::EAX, RegState::Implicit)
14436 .addReg(X86::ESP, RegState::Implicit)
14437 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14438 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14439 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14442 MI->eraseFromParent(); // The pseudo instruction is gone now.
14446 MachineBasicBlock *
14447 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14448 MachineBasicBlock *BB) const {
14449 // This is pretty easy. We're taking the value that we received from
14450 // our load from the relocation, sticking it in either RDI (x86-64)
14451 // or EAX and doing an indirect call. The return value will then
14452 // be in the normal return register.
14453 const X86InstrInfo *TII
14454 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14455 DebugLoc DL = MI->getDebugLoc();
14456 MachineFunction *F = BB->getParent();
14458 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14459 assert(MI->getOperand(3).isGlobal() && "This should be a global");
14461 // Get a register mask for the lowered call.
14462 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14463 // proper register mask.
14464 const uint32_t *RegMask =
14465 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14466 if (Subtarget->is64Bit()) {
14467 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14468 TII->get(X86::MOV64rm), X86::RDI)
14470 .addImm(0).addReg(0)
14471 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14472 MI->getOperand(3).getTargetFlags())
14474 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14475 addDirectMem(MIB, X86::RDI);
14476 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14477 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14478 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14479 TII->get(X86::MOV32rm), X86::EAX)
14481 .addImm(0).addReg(0)
14482 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14483 MI->getOperand(3).getTargetFlags())
14485 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14486 addDirectMem(MIB, X86::EAX);
14487 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14489 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14490 TII->get(X86::MOV32rm), X86::EAX)
14491 .addReg(TII->getGlobalBaseReg(F))
14492 .addImm(0).addReg(0)
14493 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14494 MI->getOperand(3).getTargetFlags())
14496 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14497 addDirectMem(MIB, X86::EAX);
14498 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14501 MI->eraseFromParent(); // The pseudo instruction is gone now.
14505 MachineBasicBlock *
14506 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14507 MachineBasicBlock *MBB) const {
14508 DebugLoc DL = MI->getDebugLoc();
14509 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14511 MachineFunction *MF = MBB->getParent();
14512 MachineRegisterInfo &MRI = MF->getRegInfo();
14514 const BasicBlock *BB = MBB->getBasicBlock();
14515 MachineFunction::iterator I = MBB;
14518 // Memory Reference
14519 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14520 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14523 unsigned MemOpndSlot = 0;
14525 unsigned CurOp = 0;
14527 DstReg = MI->getOperand(CurOp++).getReg();
14528 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14529 assert(RC->hasType(MVT::i32) && "Invalid destination!");
14530 unsigned mainDstReg = MRI.createVirtualRegister(RC);
14531 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14533 MemOpndSlot = CurOp;
14535 MVT PVT = getPointerTy();
14536 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14537 "Invalid Pointer Size!");
14539 // For v = setjmp(buf), we generate
14542 // buf[LabelOffset] = restoreMBB
14543 // SjLjSetup restoreMBB
14549 // v = phi(main, restore)
14554 MachineBasicBlock *thisMBB = MBB;
14555 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14556 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14557 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14558 MF->insert(I, mainMBB);
14559 MF->insert(I, sinkMBB);
14560 MF->push_back(restoreMBB);
14562 MachineInstrBuilder MIB;
14564 // Transfer the remainder of BB and its successor edges to sinkMBB.
14565 sinkMBB->splice(sinkMBB->begin(), MBB,
14566 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14567 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14570 unsigned PtrStoreOpc = 0;
14571 unsigned LabelReg = 0;
14572 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14573 Reloc::Model RM = getTargetMachine().getRelocationModel();
14574 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14575 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14577 // Prepare IP either in reg or imm.
14578 if (!UseImmLabel) {
14579 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14580 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14581 LabelReg = MRI.createVirtualRegister(PtrRC);
14582 if (Subtarget->is64Bit()) {
14583 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14587 .addMBB(restoreMBB)
14590 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14591 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14592 .addReg(XII->getGlobalBaseReg(MF))
14595 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14599 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14601 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14602 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14603 if (i == X86::AddrDisp)
14604 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14606 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14609 MIB.addReg(LabelReg);
14611 MIB.addMBB(restoreMBB);
14612 MIB.setMemRefs(MMOBegin, MMOEnd);
14614 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14615 .addMBB(restoreMBB);
14616 MIB.addRegMask(RegInfo->getNoPreservedMask());
14617 thisMBB->addSuccessor(mainMBB);
14618 thisMBB->addSuccessor(restoreMBB);
14622 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14623 mainMBB->addSuccessor(sinkMBB);
14626 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14627 TII->get(X86::PHI), DstReg)
14628 .addReg(mainDstReg).addMBB(mainMBB)
14629 .addReg(restoreDstReg).addMBB(restoreMBB);
14632 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14633 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14634 restoreMBB->addSuccessor(sinkMBB);
14636 MI->eraseFromParent();
14640 MachineBasicBlock *
14641 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14642 MachineBasicBlock *MBB) const {
14643 DebugLoc DL = MI->getDebugLoc();
14644 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14646 MachineFunction *MF = MBB->getParent();
14647 MachineRegisterInfo &MRI = MF->getRegInfo();
14649 // Memory Reference
14650 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14651 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14653 MVT PVT = getPointerTy();
14654 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14655 "Invalid Pointer Size!");
14657 const TargetRegisterClass *RC =
14658 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14659 unsigned Tmp = MRI.createVirtualRegister(RC);
14660 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14661 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14662 unsigned SP = RegInfo->getStackRegister();
14664 MachineInstrBuilder MIB;
14666 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14667 const int64_t SPOffset = 2 * PVT.getStoreSize();
14669 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14670 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14673 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14674 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14675 MIB.addOperand(MI->getOperand(i));
14676 MIB.setMemRefs(MMOBegin, MMOEnd);
14678 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14679 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14680 if (i == X86::AddrDisp)
14681 MIB.addDisp(MI->getOperand(i), LabelOffset);
14683 MIB.addOperand(MI->getOperand(i));
14685 MIB.setMemRefs(MMOBegin, MMOEnd);
14687 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14688 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14689 if (i == X86::AddrDisp)
14690 MIB.addDisp(MI->getOperand(i), SPOffset);
14692 MIB.addOperand(MI->getOperand(i));
14694 MIB.setMemRefs(MMOBegin, MMOEnd);
14696 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14698 MI->eraseFromParent();
14702 MachineBasicBlock *
14703 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14704 MachineBasicBlock *BB) const {
14705 switch (MI->getOpcode()) {
14706 default: llvm_unreachable("Unexpected instr type to insert");
14707 case X86::TAILJMPd64:
14708 case X86::TAILJMPr64:
14709 case X86::TAILJMPm64:
14710 llvm_unreachable("TAILJMP64 would not be touched here.");
14711 case X86::TCRETURNdi64:
14712 case X86::TCRETURNri64:
14713 case X86::TCRETURNmi64:
14715 case X86::WIN_ALLOCA:
14716 return EmitLoweredWinAlloca(MI, BB);
14717 case X86::SEG_ALLOCA_32:
14718 return EmitLoweredSegAlloca(MI, BB, false);
14719 case X86::SEG_ALLOCA_64:
14720 return EmitLoweredSegAlloca(MI, BB, true);
14721 case X86::TLSCall_32:
14722 case X86::TLSCall_64:
14723 return EmitLoweredTLSCall(MI, BB);
14724 case X86::CMOV_GR8:
14725 case X86::CMOV_FR32:
14726 case X86::CMOV_FR64:
14727 case X86::CMOV_V4F32:
14728 case X86::CMOV_V2F64:
14729 case X86::CMOV_V2I64:
14730 case X86::CMOV_V8F32:
14731 case X86::CMOV_V4F64:
14732 case X86::CMOV_V4I64:
14733 case X86::CMOV_GR16:
14734 case X86::CMOV_GR32:
14735 case X86::CMOV_RFP32:
14736 case X86::CMOV_RFP64:
14737 case X86::CMOV_RFP80:
14738 return EmitLoweredSelect(MI, BB);
14740 case X86::FP32_TO_INT16_IN_MEM:
14741 case X86::FP32_TO_INT32_IN_MEM:
14742 case X86::FP32_TO_INT64_IN_MEM:
14743 case X86::FP64_TO_INT16_IN_MEM:
14744 case X86::FP64_TO_INT32_IN_MEM:
14745 case X86::FP64_TO_INT64_IN_MEM:
14746 case X86::FP80_TO_INT16_IN_MEM:
14747 case X86::FP80_TO_INT32_IN_MEM:
14748 case X86::FP80_TO_INT64_IN_MEM: {
14749 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14750 DebugLoc DL = MI->getDebugLoc();
14752 // Change the floating point control register to use "round towards zero"
14753 // mode when truncating to an integer value.
14754 MachineFunction *F = BB->getParent();
14755 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14756 addFrameReference(BuildMI(*BB, MI, DL,
14757 TII->get(X86::FNSTCW16m)), CWFrameIdx);
14759 // Load the old value of the high byte of the control word...
14761 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14762 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14765 // Set the high part to be round to zero...
14766 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14769 // Reload the modified control word now...
14770 addFrameReference(BuildMI(*BB, MI, DL,
14771 TII->get(X86::FLDCW16m)), CWFrameIdx);
14773 // Restore the memory image of control word to original value
14774 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14777 // Get the X86 opcode to use.
14779 switch (MI->getOpcode()) {
14780 default: llvm_unreachable("illegal opcode!");
14781 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14782 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14783 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14784 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14785 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14786 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14787 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14788 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14789 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14793 MachineOperand &Op = MI->getOperand(0);
14795 AM.BaseType = X86AddressMode::RegBase;
14796 AM.Base.Reg = Op.getReg();
14798 AM.BaseType = X86AddressMode::FrameIndexBase;
14799 AM.Base.FrameIndex = Op.getIndex();
14801 Op = MI->getOperand(1);
14803 AM.Scale = Op.getImm();
14804 Op = MI->getOperand(2);
14806 AM.IndexReg = Op.getImm();
14807 Op = MI->getOperand(3);
14808 if (Op.isGlobal()) {
14809 AM.GV = Op.getGlobal();
14811 AM.Disp = Op.getImm();
14813 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14814 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14816 // Reload the original control word now.
14817 addFrameReference(BuildMI(*BB, MI, DL,
14818 TII->get(X86::FLDCW16m)), CWFrameIdx);
14820 MI->eraseFromParent(); // The pseudo instruction is gone now.
14823 // String/text processing lowering.
14824 case X86::PCMPISTRM128REG:
14825 case X86::VPCMPISTRM128REG:
14826 case X86::PCMPISTRM128MEM:
14827 case X86::VPCMPISTRM128MEM:
14828 case X86::PCMPESTRM128REG:
14829 case X86::VPCMPESTRM128REG:
14830 case X86::PCMPESTRM128MEM:
14831 case X86::VPCMPESTRM128MEM:
14832 assert(Subtarget->hasSSE42() &&
14833 "Target must have SSE4.2 or AVX features enabled");
14834 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14836 // String/text processing lowering.
14837 case X86::PCMPISTRIREG:
14838 case X86::VPCMPISTRIREG:
14839 case X86::PCMPISTRIMEM:
14840 case X86::VPCMPISTRIMEM:
14841 case X86::PCMPESTRIREG:
14842 case X86::VPCMPESTRIREG:
14843 case X86::PCMPESTRIMEM:
14844 case X86::VPCMPESTRIMEM:
14845 assert(Subtarget->hasSSE42() &&
14846 "Target must have SSE4.2 or AVX features enabled");
14847 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14849 // Thread synchronization.
14851 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14855 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14857 // Atomic Lowering.
14858 case X86::ATOMAND8:
14859 case X86::ATOMAND16:
14860 case X86::ATOMAND32:
14861 case X86::ATOMAND64:
14864 case X86::ATOMOR16:
14865 case X86::ATOMOR32:
14866 case X86::ATOMOR64:
14868 case X86::ATOMXOR16:
14869 case X86::ATOMXOR8:
14870 case X86::ATOMXOR32:
14871 case X86::ATOMXOR64:
14873 case X86::ATOMNAND8:
14874 case X86::ATOMNAND16:
14875 case X86::ATOMNAND32:
14876 case X86::ATOMNAND64:
14878 case X86::ATOMMAX8:
14879 case X86::ATOMMAX16:
14880 case X86::ATOMMAX32:
14881 case X86::ATOMMAX64:
14883 case X86::ATOMMIN8:
14884 case X86::ATOMMIN16:
14885 case X86::ATOMMIN32:
14886 case X86::ATOMMIN64:
14888 case X86::ATOMUMAX8:
14889 case X86::ATOMUMAX16:
14890 case X86::ATOMUMAX32:
14891 case X86::ATOMUMAX64:
14893 case X86::ATOMUMIN8:
14894 case X86::ATOMUMIN16:
14895 case X86::ATOMUMIN32:
14896 case X86::ATOMUMIN64:
14897 return EmitAtomicLoadArith(MI, BB);
14899 // This group does 64-bit operations on a 32-bit host.
14900 case X86::ATOMAND6432:
14901 case X86::ATOMOR6432:
14902 case X86::ATOMXOR6432:
14903 case X86::ATOMNAND6432:
14904 case X86::ATOMADD6432:
14905 case X86::ATOMSUB6432:
14906 case X86::ATOMMAX6432:
14907 case X86::ATOMMIN6432:
14908 case X86::ATOMUMAX6432:
14909 case X86::ATOMUMIN6432:
14910 case X86::ATOMSWAP6432:
14911 return EmitAtomicLoadArith6432(MI, BB);
14913 case X86::VASTART_SAVE_XMM_REGS:
14914 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14916 case X86::VAARG_64:
14917 return EmitVAARG64WithCustomInserter(MI, BB);
14919 case X86::EH_SjLj_SetJmp32:
14920 case X86::EH_SjLj_SetJmp64:
14921 return emitEHSjLjSetJmp(MI, BB);
14923 case X86::EH_SjLj_LongJmp32:
14924 case X86::EH_SjLj_LongJmp64:
14925 return emitEHSjLjLongJmp(MI, BB);
14929 //===----------------------------------------------------------------------===//
14930 // X86 Optimization Hooks
14931 //===----------------------------------------------------------------------===//
14933 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14936 const SelectionDAG &DAG,
14937 unsigned Depth) const {
14938 unsigned BitWidth = KnownZero.getBitWidth();
14939 unsigned Opc = Op.getOpcode();
14940 assert((Opc >= ISD::BUILTIN_OP_END ||
14941 Opc == ISD::INTRINSIC_WO_CHAIN ||
14942 Opc == ISD::INTRINSIC_W_CHAIN ||
14943 Opc == ISD::INTRINSIC_VOID) &&
14944 "Should use MaskedValueIsZero if you don't know whether Op"
14945 " is a target node!");
14947 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14961 // These nodes' second result is a boolean.
14962 if (Op.getResNo() == 0)
14965 case X86ISD::SETCC:
14966 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14968 case ISD::INTRINSIC_WO_CHAIN: {
14969 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14970 unsigned NumLoBits = 0;
14973 case Intrinsic::x86_sse_movmsk_ps:
14974 case Intrinsic::x86_avx_movmsk_ps_256:
14975 case Intrinsic::x86_sse2_movmsk_pd:
14976 case Intrinsic::x86_avx_movmsk_pd_256:
14977 case Intrinsic::x86_mmx_pmovmskb:
14978 case Intrinsic::x86_sse2_pmovmskb_128:
14979 case Intrinsic::x86_avx2_pmovmskb: {
14980 // High bits of movmskp{s|d}, pmovmskb are known zero.
14982 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14983 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
14984 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
14985 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
14986 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
14987 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
14988 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
14989 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
14991 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15000 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15001 unsigned Depth) const {
15002 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15003 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15004 return Op.getValueType().getScalarType().getSizeInBits();
15010 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15011 /// node is a GlobalAddress + offset.
15012 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15013 const GlobalValue* &GA,
15014 int64_t &Offset) const {
15015 if (N->getOpcode() == X86ISD::Wrapper) {
15016 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15017 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15018 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15022 return TargetLowering::isGAPlusOffset(N, GA, Offset);
15025 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15026 /// same as extracting the high 128-bit part of 256-bit vector and then
15027 /// inserting the result into the low part of a new 256-bit vector
15028 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15029 EVT VT = SVOp->getValueType(0);
15030 unsigned NumElems = VT.getVectorNumElements();
15032 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15033 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15034 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15035 SVOp->getMaskElt(j) >= 0)
15041 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15042 /// same as extracting the low 128-bit part of 256-bit vector and then
15043 /// inserting the result into the high part of a new 256-bit vector
15044 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15045 EVT VT = SVOp->getValueType(0);
15046 unsigned NumElems = VT.getVectorNumElements();
15048 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15049 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15050 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15051 SVOp->getMaskElt(j) >= 0)
15057 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15058 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15059 TargetLowering::DAGCombinerInfo &DCI,
15060 const X86Subtarget* Subtarget) {
15062 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15063 SDValue V1 = SVOp->getOperand(0);
15064 SDValue V2 = SVOp->getOperand(1);
15065 EVT VT = SVOp->getValueType(0);
15066 unsigned NumElems = VT.getVectorNumElements();
15068 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15069 V2.getOpcode() == ISD::CONCAT_VECTORS) {
15073 // V UNDEF BUILD_VECTOR UNDEF
15075 // CONCAT_VECTOR CONCAT_VECTOR
15078 // RESULT: V + zero extended
15080 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15081 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15082 V1.getOperand(1).getOpcode() != ISD::UNDEF)
15085 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15088 // To match the shuffle mask, the first half of the mask should
15089 // be exactly the first vector, and all the rest a splat with the
15090 // first element of the second one.
15091 for (unsigned i = 0; i != NumElems/2; ++i)
15092 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15093 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15096 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15097 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15098 if (Ld->hasNUsesOfValue(1, 0)) {
15099 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15100 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15102 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15103 array_lengthof(Ops),
15105 Ld->getPointerInfo(),
15106 Ld->getAlignment(),
15107 false/*isVolatile*/, true/*ReadMem*/,
15108 false/*WriteMem*/);
15110 // Make sure the newly-created LOAD is in the same position as Ld in
15111 // terms of dependency. We create a TokenFactor for Ld and ResNode,
15112 // and update uses of Ld's output chain to use the TokenFactor.
15113 if (Ld->hasAnyUseOfValue(1)) {
15114 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15115 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15116 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15117 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15118 SDValue(ResNode.getNode(), 1));
15121 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15125 // Emit a zeroed vector and insert the desired subvector on its
15127 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15128 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15129 return DCI.CombineTo(N, InsV);
15132 //===--------------------------------------------------------------------===//
15133 // Combine some shuffles into subvector extracts and inserts:
15136 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15137 if (isShuffleHigh128VectorInsertLow(SVOp)) {
15138 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15139 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15140 return DCI.CombineTo(N, InsV);
15143 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15144 if (isShuffleLow128VectorInsertHigh(SVOp)) {
15145 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15146 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15147 return DCI.CombineTo(N, InsV);
15153 /// PerformShuffleCombine - Performs several different shuffle combines.
15154 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15155 TargetLowering::DAGCombinerInfo &DCI,
15156 const X86Subtarget *Subtarget) {
15158 EVT VT = N->getValueType(0);
15160 // Don't create instructions with illegal types after legalize types has run.
15161 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15162 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15165 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15166 if (Subtarget->hasFp256() && VT.is256BitVector() &&
15167 N->getOpcode() == ISD::VECTOR_SHUFFLE)
15168 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15170 // Only handle 128 wide vector from here on.
15171 if (!VT.is128BitVector())
15174 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15175 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15176 // consecutive, non-overlapping, and in the right order.
15177 SmallVector<SDValue, 16> Elts;
15178 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15179 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15181 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15184 /// PerformTruncateCombine - Converts truncate operation to
15185 /// a sequence of vector shuffle operations.
15186 /// It is possible when we truncate 256-bit vector to 128-bit vector
15187 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15188 TargetLowering::DAGCombinerInfo &DCI,
15189 const X86Subtarget *Subtarget) {
15193 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15194 /// specific shuffle of a load can be folded into a single element load.
15195 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15196 /// shuffles have been customed lowered so we need to handle those here.
15197 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15198 TargetLowering::DAGCombinerInfo &DCI) {
15199 if (DCI.isBeforeLegalizeOps())
15202 SDValue InVec = N->getOperand(0);
15203 SDValue EltNo = N->getOperand(1);
15205 if (!isa<ConstantSDNode>(EltNo))
15208 EVT VT = InVec.getValueType();
15210 bool HasShuffleIntoBitcast = false;
15211 if (InVec.getOpcode() == ISD::BITCAST) {
15212 // Don't duplicate a load with other uses.
15213 if (!InVec.hasOneUse())
15215 EVT BCVT = InVec.getOperand(0).getValueType();
15216 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15218 InVec = InVec.getOperand(0);
15219 HasShuffleIntoBitcast = true;
15222 if (!isTargetShuffle(InVec.getOpcode()))
15225 // Don't duplicate a load with other uses.
15226 if (!InVec.hasOneUse())
15229 SmallVector<int, 16> ShuffleMask;
15231 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15235 // Select the input vector, guarding against out of range extract vector.
15236 unsigned NumElems = VT.getVectorNumElements();
15237 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15238 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15239 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15240 : InVec.getOperand(1);
15242 // If inputs to shuffle are the same for both ops, then allow 2 uses
15243 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15245 if (LdNode.getOpcode() == ISD::BITCAST) {
15246 // Don't duplicate a load with other uses.
15247 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15250 AllowedUses = 1; // only allow 1 load use if we have a bitcast
15251 LdNode = LdNode.getOperand(0);
15254 if (!ISD::isNormalLoad(LdNode.getNode()))
15257 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15259 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15262 if (HasShuffleIntoBitcast) {
15263 // If there's a bitcast before the shuffle, check if the load type and
15264 // alignment is valid.
15265 unsigned Align = LN0->getAlignment();
15266 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15267 unsigned NewAlign = TLI.getDataLayout()->
15268 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15270 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15274 // All checks match so transform back to vector_shuffle so that DAG combiner
15275 // can finish the job
15278 // Create shuffle node taking into account the case that its a unary shuffle
15279 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15280 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15281 InVec.getOperand(0), Shuffle,
15283 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15284 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15288 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15289 /// generation and convert it from being a bunch of shuffles and extracts
15290 /// to a simple store and scalar loads to extract the elements.
15291 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15292 TargetLowering::DAGCombinerInfo &DCI) {
15293 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15294 if (NewOp.getNode())
15297 SDValue InputVector = N->getOperand(0);
15298 // Detect whether we are trying to convert from mmx to i32 and the bitcast
15299 // from mmx to v2i32 has a single usage.
15300 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15301 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15302 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15303 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15304 N->getValueType(0),
15305 InputVector.getNode()->getOperand(0));
15307 // Only operate on vectors of 4 elements, where the alternative shuffling
15308 // gets to be more expensive.
15309 if (InputVector.getValueType() != MVT::v4i32)
15312 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15313 // single use which is a sign-extend or zero-extend, and all elements are
15315 SmallVector<SDNode *, 4> Uses;
15316 unsigned ExtractedElements = 0;
15317 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15318 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15319 if (UI.getUse().getResNo() != InputVector.getResNo())
15322 SDNode *Extract = *UI;
15323 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15326 if (Extract->getValueType(0) != MVT::i32)
15328 if (!Extract->hasOneUse())
15330 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15331 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15333 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15336 // Record which element was extracted.
15337 ExtractedElements |=
15338 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15340 Uses.push_back(Extract);
15343 // If not all the elements were used, this may not be worthwhile.
15344 if (ExtractedElements != 15)
15347 // Ok, we've now decided to do the transformation.
15348 SDLoc dl(InputVector);
15350 // Store the value to a temporary stack slot.
15351 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15352 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15353 MachinePointerInfo(), false, false, 0);
15355 // Replace each use (extract) with a load of the appropriate element.
15356 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15357 UE = Uses.end(); UI != UE; ++UI) {
15358 SDNode *Extract = *UI;
15360 // cOMpute the element's address.
15361 SDValue Idx = Extract->getOperand(1);
15363 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15364 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15365 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15366 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15368 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15369 StackPtr, OffsetVal);
15371 // Load the scalar.
15372 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15373 ScalarAddr, MachinePointerInfo(),
15374 false, false, false, 0);
15376 // Replace the exact with the load.
15377 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15380 // The replacement was made in place; don't return anything.
15384 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15385 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15386 SDValue RHS, SelectionDAG &DAG,
15387 const X86Subtarget *Subtarget) {
15388 if (!VT.isVector())
15391 switch (VT.getSimpleVT().SimpleTy) {
15396 if (!Subtarget->hasAVX2())
15401 if (!Subtarget->hasSSE2())
15405 // SSE2 has only a small subset of the operations.
15406 bool hasUnsigned = Subtarget->hasSSE41() ||
15407 (Subtarget->hasSSE2() && VT == MVT::v16i8);
15408 bool hasSigned = Subtarget->hasSSE41() ||
15409 (Subtarget->hasSSE2() && VT == MVT::v8i16);
15411 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15413 // Check for x CC y ? x : y.
15414 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15415 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15420 return hasUnsigned ? X86ISD::UMIN : 0;
15423 return hasUnsigned ? X86ISD::UMAX : 0;
15426 return hasSigned ? X86ISD::SMIN : 0;
15429 return hasSigned ? X86ISD::SMAX : 0;
15431 // Check for x CC y ? y : x -- a min/max with reversed arms.
15432 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15433 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15438 return hasUnsigned ? X86ISD::UMAX : 0;
15441 return hasUnsigned ? X86ISD::UMIN : 0;
15444 return hasSigned ? X86ISD::SMAX : 0;
15447 return hasSigned ? X86ISD::SMIN : 0;
15454 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15456 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15457 TargetLowering::DAGCombinerInfo &DCI,
15458 const X86Subtarget *Subtarget) {
15460 SDValue Cond = N->getOperand(0);
15461 // Get the LHS/RHS of the select.
15462 SDValue LHS = N->getOperand(1);
15463 SDValue RHS = N->getOperand(2);
15464 EVT VT = LHS.getValueType();
15466 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15467 // instructions match the semantics of the common C idiom x<y?x:y but not
15468 // x<=y?x:y, because of how they handle negative zero (which can be
15469 // ignored in unsafe-math mode).
15470 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15471 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15472 (Subtarget->hasSSE2() ||
15473 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15474 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15476 unsigned Opcode = 0;
15477 // Check for x CC y ? x : y.
15478 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15479 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15483 // Converting this to a min would handle NaNs incorrectly, and swapping
15484 // the operands would cause it to handle comparisons between positive
15485 // and negative zero incorrectly.
15486 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15487 if (!DAG.getTarget().Options.UnsafeFPMath &&
15488 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15490 std::swap(LHS, RHS);
15492 Opcode = X86ISD::FMIN;
15495 // Converting this to a min would handle comparisons between positive
15496 // and negative zero incorrectly.
15497 if (!DAG.getTarget().Options.UnsafeFPMath &&
15498 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15500 Opcode = X86ISD::FMIN;
15503 // Converting this to a min would handle both negative zeros and NaNs
15504 // incorrectly, but we can swap the operands to fix both.
15505 std::swap(LHS, RHS);
15509 Opcode = X86ISD::FMIN;
15513 // Converting this to a max would handle comparisons between positive
15514 // and negative zero incorrectly.
15515 if (!DAG.getTarget().Options.UnsafeFPMath &&
15516 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15518 Opcode = X86ISD::FMAX;
15521 // Converting this to a max would handle NaNs incorrectly, and swapping
15522 // the operands would cause it to handle comparisons between positive
15523 // and negative zero incorrectly.
15524 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15525 if (!DAG.getTarget().Options.UnsafeFPMath &&
15526 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15528 std::swap(LHS, RHS);
15530 Opcode = X86ISD::FMAX;
15533 // Converting this to a max would handle both negative zeros and NaNs
15534 // incorrectly, but we can swap the operands to fix both.
15535 std::swap(LHS, RHS);
15539 Opcode = X86ISD::FMAX;
15542 // Check for x CC y ? y : x -- a min/max with reversed arms.
15543 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15544 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15548 // Converting this to a min would handle comparisons between positive
15549 // and negative zero incorrectly, and swapping the operands would
15550 // cause it to handle NaNs incorrectly.
15551 if (!DAG.getTarget().Options.UnsafeFPMath &&
15552 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15553 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15555 std::swap(LHS, RHS);
15557 Opcode = X86ISD::FMIN;
15560 // Converting this to a min would handle NaNs incorrectly.
15561 if (!DAG.getTarget().Options.UnsafeFPMath &&
15562 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15564 Opcode = X86ISD::FMIN;
15567 // Converting this to a min would handle both negative zeros and NaNs
15568 // incorrectly, but we can swap the operands to fix both.
15569 std::swap(LHS, RHS);
15573 Opcode = X86ISD::FMIN;
15577 // Converting this to a max would handle NaNs incorrectly.
15578 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15580 Opcode = X86ISD::FMAX;
15583 // Converting this to a max would handle comparisons between positive
15584 // and negative zero incorrectly, and swapping the operands would
15585 // cause it to handle NaNs incorrectly.
15586 if (!DAG.getTarget().Options.UnsafeFPMath &&
15587 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15588 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15590 std::swap(LHS, RHS);
15592 Opcode = X86ISD::FMAX;
15595 // Converting this to a max would handle both negative zeros and NaNs
15596 // incorrectly, but we can swap the operands to fix both.
15597 std::swap(LHS, RHS);
15601 Opcode = X86ISD::FMAX;
15607 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15610 // If this is a select between two integer constants, try to do some
15612 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15613 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15614 // Don't do this for crazy integer types.
15615 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15616 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15617 // so that TrueC (the true value) is larger than FalseC.
15618 bool NeedsCondInvert = false;
15620 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15621 // Efficiently invertible.
15622 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15623 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15624 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15625 NeedsCondInvert = true;
15626 std::swap(TrueC, FalseC);
15629 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15630 if (FalseC->getAPIntValue() == 0 &&
15631 TrueC->getAPIntValue().isPowerOf2()) {
15632 if (NeedsCondInvert) // Invert the condition if needed.
15633 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15634 DAG.getConstant(1, Cond.getValueType()));
15636 // Zero extend the condition if needed.
15637 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15639 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15640 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15641 DAG.getConstant(ShAmt, MVT::i8));
15644 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15645 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15646 if (NeedsCondInvert) // Invert the condition if needed.
15647 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15648 DAG.getConstant(1, Cond.getValueType()));
15650 // Zero extend the condition if needed.
15651 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15652 FalseC->getValueType(0), Cond);
15653 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15654 SDValue(FalseC, 0));
15657 // Optimize cases that will turn into an LEA instruction. This requires
15658 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15659 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15660 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15661 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15663 bool isFastMultiplier = false;
15665 switch ((unsigned char)Diff) {
15667 case 1: // result = add base, cond
15668 case 2: // result = lea base( , cond*2)
15669 case 3: // result = lea base(cond, cond*2)
15670 case 4: // result = lea base( , cond*4)
15671 case 5: // result = lea base(cond, cond*4)
15672 case 8: // result = lea base( , cond*8)
15673 case 9: // result = lea base(cond, cond*8)
15674 isFastMultiplier = true;
15679 if (isFastMultiplier) {
15680 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15681 if (NeedsCondInvert) // Invert the condition if needed.
15682 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15683 DAG.getConstant(1, Cond.getValueType()));
15685 // Zero extend the condition if needed.
15686 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15688 // Scale the condition by the difference.
15690 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15691 DAG.getConstant(Diff, Cond.getValueType()));
15693 // Add the base if non-zero.
15694 if (FalseC->getAPIntValue() != 0)
15695 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15696 SDValue(FalseC, 0));
15703 // Canonicalize max and min:
15704 // (x > y) ? x : y -> (x >= y) ? x : y
15705 // (x < y) ? x : y -> (x <= y) ? x : y
15706 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15707 // the need for an extra compare
15708 // against zero. e.g.
15709 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15711 // testl %edi, %edi
15713 // cmovgl %edi, %eax
15717 // cmovsl %eax, %edi
15718 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15719 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15720 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15721 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15726 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15727 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
15728 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15729 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15734 // Match VSELECTs into subs with unsigned saturation.
15735 if (!DCI.isBeforeLegalize() &&
15736 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15737 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15738 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15739 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15740 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15742 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15743 // left side invert the predicate to simplify logic below.
15745 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15747 CC = ISD::getSetCCInverse(CC, true);
15748 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15752 if (Other.getNode() && Other->getNumOperands() == 2 &&
15753 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15754 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15755 SDValue CondRHS = Cond->getOperand(1);
15757 // Look for a general sub with unsigned saturation first.
15758 // x >= y ? x-y : 0 --> subus x, y
15759 // x > y ? x-y : 0 --> subus x, y
15760 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15761 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15762 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15764 // If the RHS is a constant we have to reverse the const canonicalization.
15765 // x > C-1 ? x+-C : 0 --> subus x, C
15766 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15767 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15768 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15769 if (CondRHS.getConstantOperandVal(0) == -A-1)
15770 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15771 DAG.getConstant(-A, VT));
15774 // Another special case: If C was a sign bit, the sub has been
15775 // canonicalized into a xor.
15776 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15777 // it's safe to decanonicalize the xor?
15778 // x s< 0 ? x^C : 0 --> subus x, C
15779 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15780 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15781 isSplatVector(OpRHS.getNode())) {
15782 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15784 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15789 // Try to match a min/max vector operation.
15790 if (!DCI.isBeforeLegalize() &&
15791 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15792 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15793 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15795 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15796 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15797 Cond.getOpcode() == ISD::SETCC) {
15799 assert(Cond.getValueType().isVector() &&
15800 "vector select expects a vector selector!");
15802 EVT IntVT = Cond.getValueType();
15803 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15804 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15806 if (!TValIsAllOnes && !FValIsAllZeros) {
15807 // Try invert the condition if true value is not all 1s and false value
15809 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15810 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15812 if (TValIsAllZeros || FValIsAllOnes) {
15813 SDValue CC = Cond.getOperand(2);
15814 ISD::CondCode NewCC =
15815 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15816 Cond.getOperand(0).getValueType().isInteger());
15817 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15818 std::swap(LHS, RHS);
15819 TValIsAllOnes = FValIsAllOnes;
15820 FValIsAllZeros = TValIsAllZeros;
15824 if (TValIsAllOnes || FValIsAllZeros) {
15827 if (TValIsAllOnes && FValIsAllZeros)
15829 else if (TValIsAllOnes)
15830 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15831 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15832 else if (FValIsAllZeros)
15833 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15834 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15836 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15840 // If we know that this node is legal then we know that it is going to be
15841 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15842 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15843 // to simplify previous instructions.
15844 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15845 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15846 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15847 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15849 // Don't optimize vector selects that map to mask-registers.
15853 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15854 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15856 APInt KnownZero, KnownOne;
15857 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15858 DCI.isBeforeLegalizeOps());
15859 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15860 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15861 DCI.CommitTargetLoweringOpt(TLO);
15867 // Check whether a boolean test is testing a boolean value generated by
15868 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15871 // Simplify the following patterns:
15872 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15873 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15874 // to (Op EFLAGS Cond)
15876 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15877 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15878 // to (Op EFLAGS !Cond)
15880 // where Op could be BRCOND or CMOV.
15882 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15883 // Quit if not CMP and SUB with its value result used.
15884 if (Cmp.getOpcode() != X86ISD::CMP &&
15885 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15888 // Quit if not used as a boolean value.
15889 if (CC != X86::COND_E && CC != X86::COND_NE)
15892 // Check CMP operands. One of them should be 0 or 1 and the other should be
15893 // an SetCC or extended from it.
15894 SDValue Op1 = Cmp.getOperand(0);
15895 SDValue Op2 = Cmp.getOperand(1);
15898 const ConstantSDNode* C = 0;
15899 bool needOppositeCond = (CC == X86::COND_E);
15900 bool checkAgainstTrue = false; // Is it a comparison against 1?
15902 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15904 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15906 else // Quit if all operands are not constants.
15909 if (C->getZExtValue() == 1) {
15910 needOppositeCond = !needOppositeCond;
15911 checkAgainstTrue = true;
15912 } else if (C->getZExtValue() != 0)
15913 // Quit if the constant is neither 0 or 1.
15916 bool truncatedToBoolWithAnd = false;
15917 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15918 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15919 SetCC.getOpcode() == ISD::TRUNCATE ||
15920 SetCC.getOpcode() == ISD::AND) {
15921 if (SetCC.getOpcode() == ISD::AND) {
15923 ConstantSDNode *CS;
15924 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15925 CS->getZExtValue() == 1)
15927 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15928 CS->getZExtValue() == 1)
15932 SetCC = SetCC.getOperand(OpIdx);
15933 truncatedToBoolWithAnd = true;
15935 SetCC = SetCC.getOperand(0);
15938 switch (SetCC.getOpcode()) {
15939 case X86ISD::SETCC_CARRY:
15940 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15941 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15942 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15943 // truncated to i1 using 'and'.
15944 if (checkAgainstTrue && !truncatedToBoolWithAnd)
15946 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15947 "Invalid use of SETCC_CARRY!");
15949 case X86ISD::SETCC:
15950 // Set the condition code or opposite one if necessary.
15951 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15952 if (needOppositeCond)
15953 CC = X86::GetOppositeBranchCondition(CC);
15954 return SetCC.getOperand(1);
15955 case X86ISD::CMOV: {
15956 // Check whether false/true value has canonical one, i.e. 0 or 1.
15957 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15958 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15959 // Quit if true value is not a constant.
15962 // Quit if false value is not a constant.
15964 SDValue Op = SetCC.getOperand(0);
15965 // Skip 'zext' or 'trunc' node.
15966 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15967 Op.getOpcode() == ISD::TRUNCATE)
15968 Op = Op.getOperand(0);
15969 // A special case for rdrand/rdseed, where 0 is set if false cond is
15971 if ((Op.getOpcode() != X86ISD::RDRAND &&
15972 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15975 // Quit if false value is not the constant 0 or 1.
15976 bool FValIsFalse = true;
15977 if (FVal && FVal->getZExtValue() != 0) {
15978 if (FVal->getZExtValue() != 1)
15980 // If FVal is 1, opposite cond is needed.
15981 needOppositeCond = !needOppositeCond;
15982 FValIsFalse = false;
15984 // Quit if TVal is not the constant opposite of FVal.
15985 if (FValIsFalse && TVal->getZExtValue() != 1)
15987 if (!FValIsFalse && TVal->getZExtValue() != 0)
15989 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15990 if (needOppositeCond)
15991 CC = X86::GetOppositeBranchCondition(CC);
15992 return SetCC.getOperand(3);
15999 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16000 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16001 TargetLowering::DAGCombinerInfo &DCI,
16002 const X86Subtarget *Subtarget) {
16005 // If the flag operand isn't dead, don't touch this CMOV.
16006 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16009 SDValue FalseOp = N->getOperand(0);
16010 SDValue TrueOp = N->getOperand(1);
16011 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16012 SDValue Cond = N->getOperand(3);
16014 if (CC == X86::COND_E || CC == X86::COND_NE) {
16015 switch (Cond.getOpcode()) {
16019 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16020 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16021 return (CC == X86::COND_E) ? FalseOp : TrueOp;
16027 Flags = checkBoolTestSetCCCombine(Cond, CC);
16028 if (Flags.getNode() &&
16029 // Extra check as FCMOV only supports a subset of X86 cond.
16030 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16031 SDValue Ops[] = { FalseOp, TrueOp,
16032 DAG.getConstant(CC, MVT::i8), Flags };
16033 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16034 Ops, array_lengthof(Ops));
16037 // If this is a select between two integer constants, try to do some
16038 // optimizations. Note that the operands are ordered the opposite of SELECT
16040 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16041 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16042 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16043 // larger than FalseC (the false value).
16044 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16045 CC = X86::GetOppositeBranchCondition(CC);
16046 std::swap(TrueC, FalseC);
16047 std::swap(TrueOp, FalseOp);
16050 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
16051 // This is efficient for any integer data type (including i8/i16) and
16053 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16054 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16055 DAG.getConstant(CC, MVT::i8), Cond);
16057 // Zero extend the condition if needed.
16058 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16060 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16061 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16062 DAG.getConstant(ShAmt, MVT::i8));
16063 if (N->getNumValues() == 2) // Dead flag value?
16064 return DCI.CombineTo(N, Cond, SDValue());
16068 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
16069 // for any integer data type, including i8/i16.
16070 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16071 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16072 DAG.getConstant(CC, MVT::i8), Cond);
16074 // Zero extend the condition if needed.
16075 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16076 FalseC->getValueType(0), Cond);
16077 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16078 SDValue(FalseC, 0));
16080 if (N->getNumValues() == 2) // Dead flag value?
16081 return DCI.CombineTo(N, Cond, SDValue());
16085 // Optimize cases that will turn into an LEA instruction. This requires
16086 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16087 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16088 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16089 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16091 bool isFastMultiplier = false;
16093 switch ((unsigned char)Diff) {
16095 case 1: // result = add base, cond
16096 case 2: // result = lea base( , cond*2)
16097 case 3: // result = lea base(cond, cond*2)
16098 case 4: // result = lea base( , cond*4)
16099 case 5: // result = lea base(cond, cond*4)
16100 case 8: // result = lea base( , cond*8)
16101 case 9: // result = lea base(cond, cond*8)
16102 isFastMultiplier = true;
16107 if (isFastMultiplier) {
16108 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16109 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16110 DAG.getConstant(CC, MVT::i8), Cond);
16111 // Zero extend the condition if needed.
16112 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16114 // Scale the condition by the difference.
16116 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16117 DAG.getConstant(Diff, Cond.getValueType()));
16119 // Add the base if non-zero.
16120 if (FalseC->getAPIntValue() != 0)
16121 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16122 SDValue(FalseC, 0));
16123 if (N->getNumValues() == 2) // Dead flag value?
16124 return DCI.CombineTo(N, Cond, SDValue());
16131 // Handle these cases:
16132 // (select (x != c), e, c) -> select (x != c), e, x),
16133 // (select (x == c), c, e) -> select (x == c), x, e)
16134 // where the c is an integer constant, and the "select" is the combination
16135 // of CMOV and CMP.
16137 // The rationale for this change is that the conditional-move from a constant
16138 // needs two instructions, however, conditional-move from a register needs
16139 // only one instruction.
16141 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16142 // some instruction-combining opportunities. This opt needs to be
16143 // postponed as late as possible.
16145 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16146 // the DCI.xxxx conditions are provided to postpone the optimization as
16147 // late as possible.
16149 ConstantSDNode *CmpAgainst = 0;
16150 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16151 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16152 !isa<ConstantSDNode>(Cond.getOperand(0))) {
16154 if (CC == X86::COND_NE &&
16155 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16156 CC = X86::GetOppositeBranchCondition(CC);
16157 std::swap(TrueOp, FalseOp);
16160 if (CC == X86::COND_E &&
16161 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16162 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16163 DAG.getConstant(CC, MVT::i8), Cond };
16164 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16165 array_lengthof(Ops));
16173 /// PerformMulCombine - Optimize a single multiply with constant into two
16174 /// in order to implement it with two cheaper instructions, e.g.
16175 /// LEA + SHL, LEA + LEA.
16176 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16177 TargetLowering::DAGCombinerInfo &DCI) {
16178 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16181 EVT VT = N->getValueType(0);
16182 if (VT != MVT::i64)
16185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16188 uint64_t MulAmt = C->getZExtValue();
16189 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16192 uint64_t MulAmt1 = 0;
16193 uint64_t MulAmt2 = 0;
16194 if ((MulAmt % 9) == 0) {
16196 MulAmt2 = MulAmt / 9;
16197 } else if ((MulAmt % 5) == 0) {
16199 MulAmt2 = MulAmt / 5;
16200 } else if ((MulAmt % 3) == 0) {
16202 MulAmt2 = MulAmt / 3;
16205 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16208 if (isPowerOf2_64(MulAmt2) &&
16209 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16210 // If second multiplifer is pow2, issue it first. We want the multiply by
16211 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16213 std::swap(MulAmt1, MulAmt2);
16216 if (isPowerOf2_64(MulAmt1))
16217 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16218 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16220 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16221 DAG.getConstant(MulAmt1, VT));
16223 if (isPowerOf2_64(MulAmt2))
16224 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16225 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16227 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16228 DAG.getConstant(MulAmt2, VT));
16230 // Do not add new nodes to DAG combiner worklist.
16231 DCI.CombineTo(N, NewMul, false);
16236 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16237 SDValue N0 = N->getOperand(0);
16238 SDValue N1 = N->getOperand(1);
16239 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16240 EVT VT = N0.getValueType();
16242 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16243 // since the result of setcc_c is all zero's or all ones.
16244 if (VT.isInteger() && !VT.isVector() &&
16245 N1C && N0.getOpcode() == ISD::AND &&
16246 N0.getOperand(1).getOpcode() == ISD::Constant) {
16247 SDValue N00 = N0.getOperand(0);
16248 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16249 ((N00.getOpcode() == ISD::ANY_EXTEND ||
16250 N00.getOpcode() == ISD::ZERO_EXTEND) &&
16251 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16252 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16253 APInt ShAmt = N1C->getAPIntValue();
16254 Mask = Mask.shl(ShAmt);
16256 return DAG.getNode(ISD::AND, SDLoc(N), VT,
16257 N00, DAG.getConstant(Mask, VT));
16261 // Hardware support for vector shifts is sparse which makes us scalarize the
16262 // vector operations in many cases. Also, on sandybridge ADD is faster than
16264 // (shl V, 1) -> add V,V
16265 if (isSplatVector(N1.getNode())) {
16266 assert(N0.getValueType().isVector() && "Invalid vector shift type");
16267 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16268 // We shift all of the values by one. In many cases we do not have
16269 // hardware support for this operation. This is better expressed as an ADD
16271 if (N1C && (1 == N1C->getZExtValue())) {
16272 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16279 /// PerformShiftCombine - Combine shifts.
16280 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16281 TargetLowering::DAGCombinerInfo &DCI,
16282 const X86Subtarget *Subtarget) {
16283 if (N->getOpcode() == ISD::SHL) {
16284 SDValue V = PerformSHLCombine(N, DAG);
16285 if (V.getNode()) return V;
16291 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
16292 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16293 // and friends. Likewise for OR -> CMPNEQSS.
16294 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16295 TargetLowering::DAGCombinerInfo &DCI,
16296 const X86Subtarget *Subtarget) {
16299 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16300 // we're requiring SSE2 for both.
16301 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16302 SDValue N0 = N->getOperand(0);
16303 SDValue N1 = N->getOperand(1);
16304 SDValue CMP0 = N0->getOperand(1);
16305 SDValue CMP1 = N1->getOperand(1);
16308 // The SETCCs should both refer to the same CMP.
16309 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16312 SDValue CMP00 = CMP0->getOperand(0);
16313 SDValue CMP01 = CMP0->getOperand(1);
16314 EVT VT = CMP00.getValueType();
16316 if (VT == MVT::f32 || VT == MVT::f64) {
16317 bool ExpectingFlags = false;
16318 // Check for any users that want flags:
16319 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16320 !ExpectingFlags && UI != UE; ++UI)
16321 switch (UI->getOpcode()) {
16326 ExpectingFlags = true;
16328 case ISD::CopyToReg:
16329 case ISD::SIGN_EXTEND:
16330 case ISD::ZERO_EXTEND:
16331 case ISD::ANY_EXTEND:
16335 if (!ExpectingFlags) {
16336 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16337 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16339 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16340 X86::CondCode tmp = cc0;
16345 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
16346 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16347 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16348 X86ISD::NodeType NTOperator = is64BitFP ?
16349 X86ISD::FSETCCsd : X86ISD::FSETCCss;
16350 // FIXME: need symbolic constants for these magic numbers.
16351 // See X86ATTInstPrinter.cpp:printSSECC().
16352 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16353 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16354 DAG.getConstant(x86cc, MVT::i8));
16355 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16357 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16358 DAG.getConstant(1, MVT::i32));
16359 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16360 return OneBitOfTruth;
16368 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16369 /// so it can be folded inside ANDNP.
16370 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16371 EVT VT = N->getValueType(0);
16373 // Match direct AllOnes for 128 and 256-bit vectors
16374 if (ISD::isBuildVectorAllOnes(N))
16377 // Look through a bit convert.
16378 if (N->getOpcode() == ISD::BITCAST)
16379 N = N->getOperand(0).getNode();
16381 // Sometimes the operand may come from a insert_subvector building a 256-bit
16383 if (VT.is256BitVector() &&
16384 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16385 SDValue V1 = N->getOperand(0);
16386 SDValue V2 = N->getOperand(1);
16388 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16389 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16390 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16391 ISD::isBuildVectorAllOnes(V2.getNode()))
16398 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16399 // register. In most cases we actually compare or select YMM-sized registers
16400 // and mixing the two types creates horrible code. This method optimizes
16401 // some of the transition sequences.
16402 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16403 TargetLowering::DAGCombinerInfo &DCI,
16404 const X86Subtarget *Subtarget) {
16405 EVT VT = N->getValueType(0);
16406 if (!VT.is256BitVector())
16409 assert((N->getOpcode() == ISD::ANY_EXTEND ||
16410 N->getOpcode() == ISD::ZERO_EXTEND ||
16411 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16413 SDValue Narrow = N->getOperand(0);
16414 EVT NarrowVT = Narrow->getValueType(0);
16415 if (!NarrowVT.is128BitVector())
16418 if (Narrow->getOpcode() != ISD::XOR &&
16419 Narrow->getOpcode() != ISD::AND &&
16420 Narrow->getOpcode() != ISD::OR)
16423 SDValue N0 = Narrow->getOperand(0);
16424 SDValue N1 = Narrow->getOperand(1);
16427 // The Left side has to be a trunc.
16428 if (N0.getOpcode() != ISD::TRUNCATE)
16431 // The type of the truncated inputs.
16432 EVT WideVT = N0->getOperand(0)->getValueType(0);
16436 // The right side has to be a 'trunc' or a constant vector.
16437 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16438 bool RHSConst = (isSplatVector(N1.getNode()) &&
16439 isa<ConstantSDNode>(N1->getOperand(0)));
16440 if (!RHSTrunc && !RHSConst)
16443 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16445 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16448 // Set N0 and N1 to hold the inputs to the new wide operation.
16449 N0 = N0->getOperand(0);
16451 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16452 N1->getOperand(0));
16453 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16454 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16455 } else if (RHSTrunc) {
16456 N1 = N1->getOperand(0);
16459 // Generate the wide operation.
16460 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16461 unsigned Opcode = N->getOpcode();
16463 case ISD::ANY_EXTEND:
16465 case ISD::ZERO_EXTEND: {
16466 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16467 APInt Mask = APInt::getAllOnesValue(InBits);
16468 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16469 return DAG.getNode(ISD::AND, DL, VT,
16470 Op, DAG.getConstant(Mask, VT));
16472 case ISD::SIGN_EXTEND:
16473 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16474 Op, DAG.getValueType(NarrowVT));
16476 llvm_unreachable("Unexpected opcode");
16480 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16481 TargetLowering::DAGCombinerInfo &DCI,
16482 const X86Subtarget *Subtarget) {
16483 EVT VT = N->getValueType(0);
16484 if (DCI.isBeforeLegalizeOps())
16487 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16491 // Create BLSI, and BLSR instructions
16492 // BLSI is X & (-X)
16493 // BLSR is X & (X-1)
16494 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16495 SDValue N0 = N->getOperand(0);
16496 SDValue N1 = N->getOperand(1);
16499 // Check LHS for neg
16500 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16501 isZero(N0.getOperand(0)))
16502 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16504 // Check RHS for neg
16505 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16506 isZero(N1.getOperand(0)))
16507 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16509 // Check LHS for X-1
16510 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16511 isAllOnes(N0.getOperand(1)))
16512 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16514 // Check RHS for X-1
16515 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16516 isAllOnes(N1.getOperand(1)))
16517 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16522 // Want to form ANDNP nodes:
16523 // 1) In the hopes of then easily combining them with OR and AND nodes
16524 // to form PBLEND/PSIGN.
16525 // 2) To match ANDN packed intrinsics
16526 if (VT != MVT::v2i64 && VT != MVT::v4i64)
16529 SDValue N0 = N->getOperand(0);
16530 SDValue N1 = N->getOperand(1);
16533 // Check LHS for vnot
16534 if (N0.getOpcode() == ISD::XOR &&
16535 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16536 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16537 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16539 // Check RHS for vnot
16540 if (N1.getOpcode() == ISD::XOR &&
16541 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16542 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16543 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16548 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16549 TargetLowering::DAGCombinerInfo &DCI,
16550 const X86Subtarget *Subtarget) {
16551 EVT VT = N->getValueType(0);
16552 if (DCI.isBeforeLegalizeOps())
16555 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16559 SDValue N0 = N->getOperand(0);
16560 SDValue N1 = N->getOperand(1);
16562 // look for psign/blend
16563 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16564 if (!Subtarget->hasSSSE3() ||
16565 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16568 // Canonicalize pandn to RHS
16569 if (N0.getOpcode() == X86ISD::ANDNP)
16571 // or (and (m, y), (pandn m, x))
16572 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16573 SDValue Mask = N1.getOperand(0);
16574 SDValue X = N1.getOperand(1);
16576 if (N0.getOperand(0) == Mask)
16577 Y = N0.getOperand(1);
16578 if (N0.getOperand(1) == Mask)
16579 Y = N0.getOperand(0);
16581 // Check to see if the mask appeared in both the AND and ANDNP and
16585 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16586 // Look through mask bitcast.
16587 if (Mask.getOpcode() == ISD::BITCAST)
16588 Mask = Mask.getOperand(0);
16589 if (X.getOpcode() == ISD::BITCAST)
16590 X = X.getOperand(0);
16591 if (Y.getOpcode() == ISD::BITCAST)
16592 Y = Y.getOperand(0);
16594 EVT MaskVT = Mask.getValueType();
16596 // Validate that the Mask operand is a vector sra node.
16597 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16598 // there is no psrai.b
16599 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16600 unsigned SraAmt = ~0;
16601 if (Mask.getOpcode() == ISD::SRA) {
16602 SDValue Amt = Mask.getOperand(1);
16603 if (isSplatVector(Amt.getNode())) {
16604 SDValue SclrAmt = Amt->getOperand(0);
16605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16606 SraAmt = C->getZExtValue();
16608 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16609 SDValue SraC = Mask.getOperand(1);
16610 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16612 if ((SraAmt + 1) != EltBits)
16617 // Now we know we at least have a plendvb with the mask val. See if
16618 // we can form a psignb/w/d.
16619 // psign = x.type == y.type == mask.type && y = sub(0, x);
16620 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16621 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16622 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16623 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16624 "Unsupported VT for PSIGN");
16625 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16626 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16628 // PBLENDVB only available on SSE 4.1
16629 if (!Subtarget->hasSSE41())
16632 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16634 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16635 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16636 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16637 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16638 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16642 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16645 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16646 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16648 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16650 if (!N0.hasOneUse() || !N1.hasOneUse())
16653 SDValue ShAmt0 = N0.getOperand(1);
16654 if (ShAmt0.getValueType() != MVT::i8)
16656 SDValue ShAmt1 = N1.getOperand(1);
16657 if (ShAmt1.getValueType() != MVT::i8)
16659 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16660 ShAmt0 = ShAmt0.getOperand(0);
16661 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16662 ShAmt1 = ShAmt1.getOperand(0);
16665 unsigned Opc = X86ISD::SHLD;
16666 SDValue Op0 = N0.getOperand(0);
16667 SDValue Op1 = N1.getOperand(0);
16668 if (ShAmt0.getOpcode() == ISD::SUB) {
16669 Opc = X86ISD::SHRD;
16670 std::swap(Op0, Op1);
16671 std::swap(ShAmt0, ShAmt1);
16674 unsigned Bits = VT.getSizeInBits();
16675 if (ShAmt1.getOpcode() == ISD::SUB) {
16676 SDValue Sum = ShAmt1.getOperand(0);
16677 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16678 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16679 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16680 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16681 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16682 return DAG.getNode(Opc, DL, VT,
16684 DAG.getNode(ISD::TRUNCATE, DL,
16687 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16688 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16690 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16691 return DAG.getNode(Opc, DL, VT,
16692 N0.getOperand(0), N1.getOperand(0),
16693 DAG.getNode(ISD::TRUNCATE, DL,
16700 // Generate NEG and CMOV for integer abs.
16701 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16702 EVT VT = N->getValueType(0);
16704 // Since X86 does not have CMOV for 8-bit integer, we don't convert
16705 // 8-bit integer abs to NEG and CMOV.
16706 if (VT.isInteger() && VT.getSizeInBits() == 8)
16709 SDValue N0 = N->getOperand(0);
16710 SDValue N1 = N->getOperand(1);
16713 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16714 // and change it to SUB and CMOV.
16715 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16716 N0.getOpcode() == ISD::ADD &&
16717 N0.getOperand(1) == N1 &&
16718 N1.getOpcode() == ISD::SRA &&
16719 N1.getOperand(0) == N0.getOperand(0))
16720 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16721 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16722 // Generate SUB & CMOV.
16723 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16724 DAG.getConstant(0, VT), N0.getOperand(0));
16726 SDValue Ops[] = { N0.getOperand(0), Neg,
16727 DAG.getConstant(X86::COND_GE, MVT::i8),
16728 SDValue(Neg.getNode(), 1) };
16729 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16730 Ops, array_lengthof(Ops));
16735 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16736 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16737 TargetLowering::DAGCombinerInfo &DCI,
16738 const X86Subtarget *Subtarget) {
16739 EVT VT = N->getValueType(0);
16740 if (DCI.isBeforeLegalizeOps())
16743 if (Subtarget->hasCMov()) {
16744 SDValue RV = performIntegerAbsCombine(N, DAG);
16749 // Try forming BMI if it is available.
16750 if (!Subtarget->hasBMI())
16753 if (VT != MVT::i32 && VT != MVT::i64)
16756 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16758 // Create BLSMSK instructions by finding X ^ (X-1)
16759 SDValue N0 = N->getOperand(0);
16760 SDValue N1 = N->getOperand(1);
16763 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16764 isAllOnes(N0.getOperand(1)))
16765 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16767 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16768 isAllOnes(N1.getOperand(1)))
16769 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16774 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16775 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16776 TargetLowering::DAGCombinerInfo &DCI,
16777 const X86Subtarget *Subtarget) {
16778 LoadSDNode *Ld = cast<LoadSDNode>(N);
16779 EVT RegVT = Ld->getValueType(0);
16780 EVT MemVT = Ld->getMemoryVT();
16782 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16783 unsigned RegSz = RegVT.getSizeInBits();
16785 // On Sandybridge unaligned 256bit loads are inefficient.
16786 ISD::LoadExtType Ext = Ld->getExtensionType();
16787 unsigned Alignment = Ld->getAlignment();
16788 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16789 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16790 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16791 unsigned NumElems = RegVT.getVectorNumElements();
16795 SDValue Ptr = Ld->getBasePtr();
16796 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16798 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16800 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16801 Ld->getPointerInfo(), Ld->isVolatile(),
16802 Ld->isNonTemporal(), Ld->isInvariant(),
16804 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16805 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16806 Ld->getPointerInfo(), Ld->isVolatile(),
16807 Ld->isNonTemporal(), Ld->isInvariant(),
16808 std::min(16U, Alignment));
16809 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16811 Load2.getValue(1));
16813 SDValue NewVec = DAG.getUNDEF(RegVT);
16814 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16815 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16816 return DCI.CombineTo(N, NewVec, TF, true);
16819 // If this is a vector EXT Load then attempt to optimize it using a
16820 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16821 // expansion is still better than scalar code.
16822 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16823 // emit a shuffle and a arithmetic shift.
16824 // TODO: It is possible to support ZExt by zeroing the undef values
16825 // during the shuffle phase or after the shuffle.
16826 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16827 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16828 assert(MemVT != RegVT && "Cannot extend to the same type");
16829 assert(MemVT.isVector() && "Must load a vector from memory");
16831 unsigned NumElems = RegVT.getVectorNumElements();
16832 unsigned MemSz = MemVT.getSizeInBits();
16833 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16835 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16838 // All sizes must be a power of two.
16839 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16842 // Attempt to load the original value using scalar loads.
16843 // Find the largest scalar type that divides the total loaded size.
16844 MVT SclrLoadTy = MVT::i8;
16845 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16846 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16847 MVT Tp = (MVT::SimpleValueType)tp;
16848 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16853 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16854 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16856 SclrLoadTy = MVT::f64;
16858 // Calculate the number of scalar loads that we need to perform
16859 // in order to load our vector from memory.
16860 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16861 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16864 unsigned loadRegZize = RegSz;
16865 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16868 // Represent our vector as a sequence of elements which are the
16869 // largest scalar that we can load.
16870 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16871 loadRegZize/SclrLoadTy.getSizeInBits());
16873 // Represent the data using the same element type that is stored in
16874 // memory. In practice, we ''widen'' MemVT.
16876 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16877 loadRegZize/MemVT.getScalarType().getSizeInBits());
16879 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16880 "Invalid vector type");
16882 // We can't shuffle using an illegal type.
16883 if (!TLI.isTypeLegal(WideVecVT))
16886 SmallVector<SDValue, 8> Chains;
16887 SDValue Ptr = Ld->getBasePtr();
16888 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16889 TLI.getPointerTy());
16890 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16892 for (unsigned i = 0; i < NumLoads; ++i) {
16893 // Perform a single load.
16894 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16895 Ptr, Ld->getPointerInfo(),
16896 Ld->isVolatile(), Ld->isNonTemporal(),
16897 Ld->isInvariant(), Ld->getAlignment());
16898 Chains.push_back(ScalarLoad.getValue(1));
16899 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16900 // another round of DAGCombining.
16902 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16904 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16905 ScalarLoad, DAG.getIntPtrConstant(i));
16907 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16910 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16913 // Bitcast the loaded value to a vector of the original element type, in
16914 // the size of the target vector type.
16915 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16916 unsigned SizeRatio = RegSz/MemSz;
16918 if (Ext == ISD::SEXTLOAD) {
16919 // If we have SSE4.1 we can directly emit a VSEXT node.
16920 if (Subtarget->hasSSE41()) {
16921 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16922 return DCI.CombineTo(N, Sext, TF, true);
16925 // Otherwise we'll shuffle the small elements in the high bits of the
16926 // larger type and perform an arithmetic shift. If the shift is not legal
16927 // it's better to scalarize.
16928 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16931 // Redistribute the loaded elements into the different locations.
16932 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16933 for (unsigned i = 0; i != NumElems; ++i)
16934 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16936 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16937 DAG.getUNDEF(WideVecVT),
16940 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16942 // Build the arithmetic shift.
16943 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16944 MemVT.getVectorElementType().getSizeInBits();
16945 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16946 DAG.getConstant(Amt, RegVT));
16948 return DCI.CombineTo(N, Shuff, TF, true);
16951 // Redistribute the loaded elements into the different locations.
16952 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16953 for (unsigned i = 0; i != NumElems; ++i)
16954 ShuffleVec[i*SizeRatio] = i;
16956 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16957 DAG.getUNDEF(WideVecVT),
16960 // Bitcast to the requested type.
16961 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16962 // Replace the original load with the new sequence
16963 // and return the new chain.
16964 return DCI.CombineTo(N, Shuff, TF, true);
16970 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16971 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16972 const X86Subtarget *Subtarget) {
16973 StoreSDNode *St = cast<StoreSDNode>(N);
16974 EVT VT = St->getValue().getValueType();
16975 EVT StVT = St->getMemoryVT();
16977 SDValue StoredVal = St->getOperand(1);
16978 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16980 // If we are saving a concatenation of two XMM registers, perform two stores.
16981 // On Sandy Bridge, 256-bit memory operations are executed by two
16982 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16983 // memory operation.
16984 unsigned Alignment = St->getAlignment();
16985 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
16986 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16987 StVT == VT && !IsAligned) {
16988 unsigned NumElems = VT.getVectorNumElements();
16992 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16993 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16995 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16996 SDValue Ptr0 = St->getBasePtr();
16997 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16999 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17000 St->getPointerInfo(), St->isVolatile(),
17001 St->isNonTemporal(), Alignment);
17002 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17003 St->getPointerInfo(), St->isVolatile(),
17004 St->isNonTemporal(),
17005 std::min(16U, Alignment));
17006 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17009 // Optimize trunc store (of multiple scalars) to shuffle and store.
17010 // First, pack all of the elements in one place. Next, store to memory
17011 // in fewer chunks.
17012 if (St->isTruncatingStore() && VT.isVector()) {
17013 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17014 unsigned NumElems = VT.getVectorNumElements();
17015 assert(StVT != VT && "Cannot truncate to the same type");
17016 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17017 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17019 // From, To sizes and ElemCount must be pow of two
17020 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17021 // We are going to use the original vector elt for storing.
17022 // Accumulated smaller vector elements must be a multiple of the store size.
17023 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17025 unsigned SizeRatio = FromSz / ToSz;
17027 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17029 // Create a type on which we perform the shuffle
17030 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17031 StVT.getScalarType(), NumElems*SizeRatio);
17033 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17035 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17036 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17037 for (unsigned i = 0; i != NumElems; ++i)
17038 ShuffleVec[i] = i * SizeRatio;
17040 // Can't shuffle using an illegal type.
17041 if (!TLI.isTypeLegal(WideVecVT))
17044 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17045 DAG.getUNDEF(WideVecVT),
17047 // At this point all of the data is stored at the bottom of the
17048 // register. We now need to save it to mem.
17050 // Find the largest store unit
17051 MVT StoreType = MVT::i8;
17052 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17053 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17054 MVT Tp = (MVT::SimpleValueType)tp;
17055 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17059 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17060 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17061 (64 <= NumElems * ToSz))
17062 StoreType = MVT::f64;
17064 // Bitcast the original vector into a vector of store-size units
17065 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17066 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17067 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17068 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17069 SmallVector<SDValue, 8> Chains;
17070 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17071 TLI.getPointerTy());
17072 SDValue Ptr = St->getBasePtr();
17074 // Perform one or more big stores into memory.
17075 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17076 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17077 StoreType, ShuffWide,
17078 DAG.getIntPtrConstant(i));
17079 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17080 St->getPointerInfo(), St->isVolatile(),
17081 St->isNonTemporal(), St->getAlignment());
17082 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17083 Chains.push_back(Ch);
17086 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17090 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
17091 // the FP state in cases where an emms may be missing.
17092 // A preferable solution to the general problem is to figure out the right
17093 // places to insert EMMS. This qualifies as a quick hack.
17095 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17096 if (VT.getSizeInBits() != 64)
17099 const Function *F = DAG.getMachineFunction().getFunction();
17100 bool NoImplicitFloatOps = F->getAttributes().
17101 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17102 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17103 && Subtarget->hasSSE2();
17104 if ((VT.isVector() ||
17105 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17106 isa<LoadSDNode>(St->getValue()) &&
17107 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17108 St->getChain().hasOneUse() && !St->isVolatile()) {
17109 SDNode* LdVal = St->getValue().getNode();
17110 LoadSDNode *Ld = 0;
17111 int TokenFactorIndex = -1;
17112 SmallVector<SDValue, 8> Ops;
17113 SDNode* ChainVal = St->getChain().getNode();
17114 // Must be a store of a load. We currently handle two cases: the load
17115 // is a direct child, and it's under an intervening TokenFactor. It is
17116 // possible to dig deeper under nested TokenFactors.
17117 if (ChainVal == LdVal)
17118 Ld = cast<LoadSDNode>(St->getChain());
17119 else if (St->getValue().hasOneUse() &&
17120 ChainVal->getOpcode() == ISD::TokenFactor) {
17121 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17122 if (ChainVal->getOperand(i).getNode() == LdVal) {
17123 TokenFactorIndex = i;
17124 Ld = cast<LoadSDNode>(St->getValue());
17126 Ops.push_back(ChainVal->getOperand(i));
17130 if (!Ld || !ISD::isNormalLoad(Ld))
17133 // If this is not the MMX case, i.e. we are just turning i64 load/store
17134 // into f64 load/store, avoid the transformation if there are multiple
17135 // uses of the loaded value.
17136 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17141 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17142 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17144 if (Subtarget->is64Bit() || F64IsLegal) {
17145 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17146 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17147 Ld->getPointerInfo(), Ld->isVolatile(),
17148 Ld->isNonTemporal(), Ld->isInvariant(),
17149 Ld->getAlignment());
17150 SDValue NewChain = NewLd.getValue(1);
17151 if (TokenFactorIndex != -1) {
17152 Ops.push_back(NewChain);
17153 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17156 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17157 St->getPointerInfo(),
17158 St->isVolatile(), St->isNonTemporal(),
17159 St->getAlignment());
17162 // Otherwise, lower to two pairs of 32-bit loads / stores.
17163 SDValue LoAddr = Ld->getBasePtr();
17164 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17165 DAG.getConstant(4, MVT::i32));
17167 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17168 Ld->getPointerInfo(),
17169 Ld->isVolatile(), Ld->isNonTemporal(),
17170 Ld->isInvariant(), Ld->getAlignment());
17171 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17172 Ld->getPointerInfo().getWithOffset(4),
17173 Ld->isVolatile(), Ld->isNonTemporal(),
17175 MinAlign(Ld->getAlignment(), 4));
17177 SDValue NewChain = LoLd.getValue(1);
17178 if (TokenFactorIndex != -1) {
17179 Ops.push_back(LoLd);
17180 Ops.push_back(HiLd);
17181 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17185 LoAddr = St->getBasePtr();
17186 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17187 DAG.getConstant(4, MVT::i32));
17189 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17190 St->getPointerInfo(),
17191 St->isVolatile(), St->isNonTemporal(),
17192 St->getAlignment());
17193 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17194 St->getPointerInfo().getWithOffset(4),
17196 St->isNonTemporal(),
17197 MinAlign(St->getAlignment(), 4));
17198 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17203 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17204 /// and return the operands for the horizontal operation in LHS and RHS. A
17205 /// horizontal operation performs the binary operation on successive elements
17206 /// of its first operand, then on successive elements of its second operand,
17207 /// returning the resulting values in a vector. For example, if
17208 /// A = < float a0, float a1, float a2, float a3 >
17210 /// B = < float b0, float b1, float b2, float b3 >
17211 /// then the result of doing a horizontal operation on A and B is
17212 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17213 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17214 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17215 /// set to A, RHS to B, and the routine returns 'true'.
17216 /// Note that the binary operation should have the property that if one of the
17217 /// operands is UNDEF then the result is UNDEF.
17218 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17219 // Look for the following pattern: if
17220 // A = < float a0, float a1, float a2, float a3 >
17221 // B = < float b0, float b1, float b2, float b3 >
17223 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17224 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17225 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17226 // which is A horizontal-op B.
17228 // At least one of the operands should be a vector shuffle.
17229 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17230 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17233 EVT VT = LHS.getValueType();
17235 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17236 "Unsupported vector type for horizontal add/sub");
17238 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17239 // operate independently on 128-bit lanes.
17240 unsigned NumElts = VT.getVectorNumElements();
17241 unsigned NumLanes = VT.getSizeInBits()/128;
17242 unsigned NumLaneElts = NumElts / NumLanes;
17243 assert((NumLaneElts % 2 == 0) &&
17244 "Vector type should have an even number of elements in each lane");
17245 unsigned HalfLaneElts = NumLaneElts/2;
17247 // View LHS in the form
17248 // LHS = VECTOR_SHUFFLE A, B, LMask
17249 // If LHS is not a shuffle then pretend it is the shuffle
17250 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17251 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17254 SmallVector<int, 16> LMask(NumElts);
17255 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17256 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17257 A = LHS.getOperand(0);
17258 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17259 B = LHS.getOperand(1);
17260 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17261 std::copy(Mask.begin(), Mask.end(), LMask.begin());
17263 if (LHS.getOpcode() != ISD::UNDEF)
17265 for (unsigned i = 0; i != NumElts; ++i)
17269 // Likewise, view RHS in the form
17270 // RHS = VECTOR_SHUFFLE C, D, RMask
17272 SmallVector<int, 16> RMask(NumElts);
17273 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17274 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17275 C = RHS.getOperand(0);
17276 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17277 D = RHS.getOperand(1);
17278 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17279 std::copy(Mask.begin(), Mask.end(), RMask.begin());
17281 if (RHS.getOpcode() != ISD::UNDEF)
17283 for (unsigned i = 0; i != NumElts; ++i)
17287 // Check that the shuffles are both shuffling the same vectors.
17288 if (!(A == C && B == D) && !(A == D && B == C))
17291 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17292 if (!A.getNode() && !B.getNode())
17295 // If A and B occur in reverse order in RHS, then "swap" them (which means
17296 // rewriting the mask).
17298 CommuteVectorShuffleMask(RMask, NumElts);
17300 // At this point LHS and RHS are equivalent to
17301 // LHS = VECTOR_SHUFFLE A, B, LMask
17302 // RHS = VECTOR_SHUFFLE A, B, RMask
17303 // Check that the masks correspond to performing a horizontal operation.
17304 for (unsigned i = 0; i != NumElts; ++i) {
17305 int LIdx = LMask[i], RIdx = RMask[i];
17307 // Ignore any UNDEF components.
17308 if (LIdx < 0 || RIdx < 0 ||
17309 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17310 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17313 // Check that successive elements are being operated on. If not, this is
17314 // not a horizontal operation.
17315 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17316 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17317 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17318 if (!(LIdx == Index && RIdx == Index + 1) &&
17319 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17323 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17324 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17328 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17329 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17330 const X86Subtarget *Subtarget) {
17331 EVT VT = N->getValueType(0);
17332 SDValue LHS = N->getOperand(0);
17333 SDValue RHS = N->getOperand(1);
17335 // Try to synthesize horizontal adds from adds of shuffles.
17336 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17337 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17338 isHorizontalBinOp(LHS, RHS, true))
17339 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17343 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17344 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17345 const X86Subtarget *Subtarget) {
17346 EVT VT = N->getValueType(0);
17347 SDValue LHS = N->getOperand(0);
17348 SDValue RHS = N->getOperand(1);
17350 // Try to synthesize horizontal subs from subs of shuffles.
17351 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17352 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17353 isHorizontalBinOp(LHS, RHS, false))
17354 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17358 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17359 /// X86ISD::FXOR nodes.
17360 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17361 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17362 // F[X]OR(0.0, x) -> x
17363 // F[X]OR(x, 0.0) -> x
17364 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17365 if (C->getValueAPF().isPosZero())
17366 return N->getOperand(1);
17367 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17368 if (C->getValueAPF().isPosZero())
17369 return N->getOperand(0);
17373 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17374 /// X86ISD::FMAX nodes.
17375 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17376 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17378 // Only perform optimizations if UnsafeMath is used.
17379 if (!DAG.getTarget().Options.UnsafeFPMath)
17382 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17383 // into FMINC and FMAXC, which are Commutative operations.
17384 unsigned NewOp = 0;
17385 switch (N->getOpcode()) {
17386 default: llvm_unreachable("unknown opcode");
17387 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
17388 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
17391 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17392 N->getOperand(0), N->getOperand(1));
17395 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17396 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17397 // FAND(0.0, x) -> 0.0
17398 // FAND(x, 0.0) -> 0.0
17399 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17400 if (C->getValueAPF().isPosZero())
17401 return N->getOperand(0);
17402 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17403 if (C->getValueAPF().isPosZero())
17404 return N->getOperand(1);
17408 static SDValue PerformBTCombine(SDNode *N,
17410 TargetLowering::DAGCombinerInfo &DCI) {
17411 // BT ignores high bits in the bit index operand.
17412 SDValue Op1 = N->getOperand(1);
17413 if (Op1.hasOneUse()) {
17414 unsigned BitWidth = Op1.getValueSizeInBits();
17415 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17416 APInt KnownZero, KnownOne;
17417 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17418 !DCI.isBeforeLegalizeOps());
17419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17420 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17421 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17422 DCI.CommitTargetLoweringOpt(TLO);
17427 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17428 SDValue Op = N->getOperand(0);
17429 if (Op.getOpcode() == ISD::BITCAST)
17430 Op = Op.getOperand(0);
17431 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17432 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17433 VT.getVectorElementType().getSizeInBits() ==
17434 OpVT.getVectorElementType().getSizeInBits()) {
17435 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17440 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17441 const X86Subtarget *Subtarget) {
17442 EVT VT = N->getValueType(0);
17443 if (!VT.isVector())
17446 SDValue N0 = N->getOperand(0);
17447 SDValue N1 = N->getOperand(1);
17448 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17451 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17452 // both SSE and AVX2 since there is no sign-extended shift right
17453 // operation on a vector with 64-bit elements.
17454 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17455 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17456 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17457 N0.getOpcode() == ISD::SIGN_EXTEND)) {
17458 SDValue N00 = N0.getOperand(0);
17460 // EXTLOAD has a better solution on AVX2,
17461 // it may be replaced with X86ISD::VSEXT node.
17462 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17463 if (!ISD::isNormalLoad(N00.getNode()))
17466 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17467 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17469 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17475 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17476 TargetLowering::DAGCombinerInfo &DCI,
17477 const X86Subtarget *Subtarget) {
17478 if (!DCI.isBeforeLegalizeOps())
17481 if (!Subtarget->hasFp256())
17484 EVT VT = N->getValueType(0);
17485 if (VT.isVector() && VT.getSizeInBits() == 256) {
17486 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17494 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17495 const X86Subtarget* Subtarget) {
17497 EVT VT = N->getValueType(0);
17499 // Let legalize expand this if it isn't a legal type yet.
17500 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17503 EVT ScalarVT = VT.getScalarType();
17504 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17505 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17508 SDValue A = N->getOperand(0);
17509 SDValue B = N->getOperand(1);
17510 SDValue C = N->getOperand(2);
17512 bool NegA = (A.getOpcode() == ISD::FNEG);
17513 bool NegB = (B.getOpcode() == ISD::FNEG);
17514 bool NegC = (C.getOpcode() == ISD::FNEG);
17516 // Negative multiplication when NegA xor NegB
17517 bool NegMul = (NegA != NegB);
17519 A = A.getOperand(0);
17521 B = B.getOperand(0);
17523 C = C.getOperand(0);
17527 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17529 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17531 return DAG.getNode(Opcode, dl, VT, A, B, C);
17534 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17535 TargetLowering::DAGCombinerInfo &DCI,
17536 const X86Subtarget *Subtarget) {
17537 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
17538 // (and (i32 x86isd::setcc_carry), 1)
17539 // This eliminates the zext. This transformation is necessary because
17540 // ISD::SETCC is always legalized to i8.
17542 SDValue N0 = N->getOperand(0);
17543 EVT VT = N->getValueType(0);
17545 if (N0.getOpcode() == ISD::AND &&
17547 N0.getOperand(0).hasOneUse()) {
17548 SDValue N00 = N0.getOperand(0);
17549 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17550 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17551 if (!C || C->getZExtValue() != 1)
17553 return DAG.getNode(ISD::AND, dl, VT,
17554 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17555 N00.getOperand(0), N00.getOperand(1)),
17556 DAG.getConstant(1, VT));
17560 if (VT.is256BitVector()) {
17561 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17569 // Optimize x == -y --> x+y == 0
17570 // x != -y --> x+y != 0
17571 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17572 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17573 SDValue LHS = N->getOperand(0);
17574 SDValue RHS = N->getOperand(1);
17576 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17577 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17578 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17579 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17580 LHS.getValueType(), RHS, LHS.getOperand(1));
17581 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17582 addV, DAG.getConstant(0, addV.getValueType()), CC);
17584 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17585 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17586 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17587 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17588 RHS.getValueType(), LHS, RHS.getOperand(1));
17589 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17590 addV, DAG.getConstant(0, addV.getValueType()), CC);
17595 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17596 // as "sbb reg,reg", since it can be extended without zext and produces
17597 // an all-ones bit which is more useful than 0/1 in some cases.
17598 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17599 return DAG.getNode(ISD::AND, DL, MVT::i8,
17600 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17601 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17602 DAG.getConstant(1, MVT::i8));
17605 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17606 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17607 TargetLowering::DAGCombinerInfo &DCI,
17608 const X86Subtarget *Subtarget) {
17610 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17611 SDValue EFLAGS = N->getOperand(1);
17613 if (CC == X86::COND_A) {
17614 // Try to convert COND_A into COND_B in an attempt to facilitate
17615 // materializing "setb reg".
17617 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17618 // cannot take an immediate as its first operand.
17620 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17621 EFLAGS.getValueType().isInteger() &&
17622 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17623 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
17624 EFLAGS.getNode()->getVTList(),
17625 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17626 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17627 return MaterializeSETB(DL, NewEFLAGS, DAG);
17631 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17632 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17634 if (CC == X86::COND_B)
17635 return MaterializeSETB(DL, EFLAGS, DAG);
17639 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17640 if (Flags.getNode()) {
17641 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17642 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17648 // Optimize branch condition evaluation.
17650 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17651 TargetLowering::DAGCombinerInfo &DCI,
17652 const X86Subtarget *Subtarget) {
17654 SDValue Chain = N->getOperand(0);
17655 SDValue Dest = N->getOperand(1);
17656 SDValue EFLAGS = N->getOperand(3);
17657 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17661 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17662 if (Flags.getNode()) {
17663 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17664 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17671 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17672 const X86TargetLowering *XTLI) {
17673 SDValue Op0 = N->getOperand(0);
17674 EVT InVT = Op0->getValueType(0);
17676 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17677 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17679 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17680 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17681 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17684 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17685 // a 32-bit target where SSE doesn't support i64->FP operations.
17686 if (Op0.getOpcode() == ISD::LOAD) {
17687 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17688 EVT VT = Ld->getValueType(0);
17689 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17690 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17691 !XTLI->getSubtarget()->is64Bit() &&
17692 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17693 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17694 Ld->getChain(), Op0, DAG);
17695 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17702 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17703 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17704 X86TargetLowering::DAGCombinerInfo &DCI) {
17705 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17706 // the result is either zero or one (depending on the input carry bit).
17707 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17708 if (X86::isZeroNode(N->getOperand(0)) &&
17709 X86::isZeroNode(N->getOperand(1)) &&
17710 // We don't have a good way to replace an EFLAGS use, so only do this when
17712 SDValue(N, 1).use_empty()) {
17714 EVT VT = N->getValueType(0);
17715 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17716 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17717 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17718 DAG.getConstant(X86::COND_B,MVT::i8),
17720 DAG.getConstant(1, VT));
17721 return DCI.CombineTo(N, Res1, CarryOut);
17727 // fold (add Y, (sete X, 0)) -> adc 0, Y
17728 // (add Y, (setne X, 0)) -> sbb -1, Y
17729 // (sub (sete X, 0), Y) -> sbb 0, Y
17730 // (sub (setne X, 0), Y) -> adc -1, Y
17731 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17734 // Look through ZExts.
17735 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17736 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17739 SDValue SetCC = Ext.getOperand(0);
17740 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17743 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17744 if (CC != X86::COND_E && CC != X86::COND_NE)
17747 SDValue Cmp = SetCC.getOperand(1);
17748 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17749 !X86::isZeroNode(Cmp.getOperand(1)) ||
17750 !Cmp.getOperand(0).getValueType().isInteger())
17753 SDValue CmpOp0 = Cmp.getOperand(0);
17754 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17755 DAG.getConstant(1, CmpOp0.getValueType()));
17757 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17758 if (CC == X86::COND_NE)
17759 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17760 DL, OtherVal.getValueType(), OtherVal,
17761 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17762 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17763 DL, OtherVal.getValueType(), OtherVal,
17764 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17767 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17768 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17769 const X86Subtarget *Subtarget) {
17770 EVT VT = N->getValueType(0);
17771 SDValue Op0 = N->getOperand(0);
17772 SDValue Op1 = N->getOperand(1);
17774 // Try to synthesize horizontal adds from adds of shuffles.
17775 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17776 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17777 isHorizontalBinOp(Op0, Op1, true))
17778 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
17780 return OptimizeConditionalInDecrement(N, DAG);
17783 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17784 const X86Subtarget *Subtarget) {
17785 SDValue Op0 = N->getOperand(0);
17786 SDValue Op1 = N->getOperand(1);
17788 // X86 can't encode an immediate LHS of a sub. See if we can push the
17789 // negation into a preceding instruction.
17790 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17791 // If the RHS of the sub is a XOR with one use and a constant, invert the
17792 // immediate. Then add one to the LHS of the sub so we can turn
17793 // X-Y -> X+~Y+1, saving one register.
17794 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17795 isa<ConstantSDNode>(Op1.getOperand(1))) {
17796 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17797 EVT VT = Op0.getValueType();
17798 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
17800 DAG.getConstant(~XorC, VT));
17801 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
17802 DAG.getConstant(C->getAPIntValue()+1, VT));
17806 // Try to synthesize horizontal adds from adds of shuffles.
17807 EVT VT = N->getValueType(0);
17808 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17809 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17810 isHorizontalBinOp(Op0, Op1, true))
17811 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
17813 return OptimizeConditionalInDecrement(N, DAG);
17816 /// performVZEXTCombine - Performs build vector combines
17817 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17818 TargetLowering::DAGCombinerInfo &DCI,
17819 const X86Subtarget *Subtarget) {
17820 // (vzext (bitcast (vzext (x)) -> (vzext x)
17821 SDValue In = N->getOperand(0);
17822 while (In.getOpcode() == ISD::BITCAST)
17823 In = In.getOperand(0);
17825 if (In.getOpcode() != X86ISD::VZEXT)
17828 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
17832 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17833 DAGCombinerInfo &DCI) const {
17834 SelectionDAG &DAG = DCI.DAG;
17835 switch (N->getOpcode()) {
17837 case ISD::EXTRACT_VECTOR_ELT:
17838 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17840 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17841 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17842 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17843 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17844 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17845 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17848 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17849 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17850 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17851 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17852 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17853 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17854 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17855 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17856 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17858 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17860 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17861 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17862 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17863 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17864 case ISD::ANY_EXTEND:
17865 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17866 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17867 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17868 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17869 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17870 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17871 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17872 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17873 case X86ISD::SHUFP: // Handle all target specific shuffles
17874 case X86ISD::PALIGNR:
17875 case X86ISD::UNPCKH:
17876 case X86ISD::UNPCKL:
17877 case X86ISD::MOVHLPS:
17878 case X86ISD::MOVLHPS:
17879 case X86ISD::PSHUFD:
17880 case X86ISD::PSHUFHW:
17881 case X86ISD::PSHUFLW:
17882 case X86ISD::MOVSS:
17883 case X86ISD::MOVSD:
17884 case X86ISD::VPERMILP:
17885 case X86ISD::VPERM2X128:
17886 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17887 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17893 /// isTypeDesirableForOp - Return true if the target has native support for
17894 /// the specified value type and it is 'desirable' to use the type for the
17895 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17896 /// instruction encodings are longer and some i16 instructions are slow.
17897 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17898 if (!isTypeLegal(VT))
17900 if (VT != MVT::i16)
17907 case ISD::SIGN_EXTEND:
17908 case ISD::ZERO_EXTEND:
17909 case ISD::ANY_EXTEND:
17922 /// IsDesirableToPromoteOp - This method query the target whether it is
17923 /// beneficial for dag combiner to promote the specified node. If true, it
17924 /// should return the desired promotion type by reference.
17925 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17926 EVT VT = Op.getValueType();
17927 if (VT != MVT::i16)
17930 bool Promote = false;
17931 bool Commute = false;
17932 switch (Op.getOpcode()) {
17935 LoadSDNode *LD = cast<LoadSDNode>(Op);
17936 // If the non-extending load has a single use and it's not live out, then it
17937 // might be folded.
17938 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17939 Op.hasOneUse()*/) {
17940 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17941 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17942 // The only case where we'd want to promote LOAD (rather then it being
17943 // promoted as an operand is when it's only use is liveout.
17944 if (UI->getOpcode() != ISD::CopyToReg)
17951 case ISD::SIGN_EXTEND:
17952 case ISD::ZERO_EXTEND:
17953 case ISD::ANY_EXTEND:
17958 SDValue N0 = Op.getOperand(0);
17959 // Look out for (store (shl (load), x)).
17960 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17973 SDValue N0 = Op.getOperand(0);
17974 SDValue N1 = Op.getOperand(1);
17975 if (!Commute && MayFoldLoad(N1))
17977 // Avoid disabling potential load folding opportunities.
17978 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17980 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17990 //===----------------------------------------------------------------------===//
17991 // X86 Inline Assembly Support
17992 //===----------------------------------------------------------------------===//
17995 // Helper to match a string separated by whitespace.
17996 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17997 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17999 for (unsigned i = 0, e = args.size(); i != e; ++i) {
18000 StringRef piece(*args[i]);
18001 if (!s.startswith(piece)) // Check if the piece matches.
18004 s = s.substr(piece.size());
18005 StringRef::size_type pos = s.find_first_not_of(" \t");
18006 if (pos == 0) // We matched a prefix.
18014 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18017 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18018 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18020 std::string AsmStr = IA->getAsmString();
18022 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18023 if (!Ty || Ty->getBitWidth() % 16 != 0)
18026 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18027 SmallVector<StringRef, 4> AsmPieces;
18028 SplitString(AsmStr, AsmPieces, ";\n");
18030 switch (AsmPieces.size()) {
18031 default: return false;
18033 // FIXME: this should verify that we are targeting a 486 or better. If not,
18034 // we will turn this bswap into something that will be lowered to logical
18035 // ops instead of emitting the bswap asm. For now, we don't support 486 or
18036 // lower so don't worry about this.
18038 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18039 matchAsm(AsmPieces[0], "bswapl", "$0") ||
18040 matchAsm(AsmPieces[0], "bswapq", "$0") ||
18041 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18042 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18043 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18044 // No need to check constraints, nothing other than the equivalent of
18045 // "=r,0" would be valid here.
18046 return IntrinsicLowering::LowerToByteSwap(CI);
18049 // rorw $$8, ${0:w} --> llvm.bswap.i16
18050 if (CI->getType()->isIntegerTy(16) &&
18051 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18052 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18053 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18055 const std::string &ConstraintsStr = IA->getConstraintString();
18056 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18057 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18058 if (AsmPieces.size() == 4 &&
18059 AsmPieces[0] == "~{cc}" &&
18060 AsmPieces[1] == "~{dirflag}" &&
18061 AsmPieces[2] == "~{flags}" &&
18062 AsmPieces[3] == "~{fpsr}")
18063 return IntrinsicLowering::LowerToByteSwap(CI);
18067 if (CI->getType()->isIntegerTy(32) &&
18068 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18069 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18070 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18071 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18073 const std::string &ConstraintsStr = IA->getConstraintString();
18074 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18075 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18076 if (AsmPieces.size() == 4 &&
18077 AsmPieces[0] == "~{cc}" &&
18078 AsmPieces[1] == "~{dirflag}" &&
18079 AsmPieces[2] == "~{flags}" &&
18080 AsmPieces[3] == "~{fpsr}")
18081 return IntrinsicLowering::LowerToByteSwap(CI);
18084 if (CI->getType()->isIntegerTy(64)) {
18085 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18086 if (Constraints.size() >= 2 &&
18087 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18088 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18089 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
18090 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18091 matchAsm(AsmPieces[1], "bswap", "%edx") &&
18092 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18093 return IntrinsicLowering::LowerToByteSwap(CI);
18101 /// getConstraintType - Given a constraint letter, return the type of
18102 /// constraint it is for this target.
18103 X86TargetLowering::ConstraintType
18104 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18105 if (Constraint.size() == 1) {
18106 switch (Constraint[0]) {
18117 return C_RegisterClass;
18141 return TargetLowering::getConstraintType(Constraint);
18144 /// Examine constraint type and operand type and determine a weight value.
18145 /// This object must already have been set up with the operand type
18146 /// and the current alternative constraint selected.
18147 TargetLowering::ConstraintWeight
18148 X86TargetLowering::getSingleConstraintMatchWeight(
18149 AsmOperandInfo &info, const char *constraint) const {
18150 ConstraintWeight weight = CW_Invalid;
18151 Value *CallOperandVal = info.CallOperandVal;
18152 // If we don't have a value, we can't do a match,
18153 // but allow it at the lowest weight.
18154 if (CallOperandVal == NULL)
18156 Type *type = CallOperandVal->getType();
18157 // Look at the constraint type.
18158 switch (*constraint) {
18160 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18171 if (CallOperandVal->getType()->isIntegerTy())
18172 weight = CW_SpecificReg;
18177 if (type->isFloatingPointTy())
18178 weight = CW_SpecificReg;
18181 if (type->isX86_MMXTy() && Subtarget->hasMMX())
18182 weight = CW_SpecificReg;
18186 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18187 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18188 weight = CW_Register;
18191 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18192 if (C->getZExtValue() <= 31)
18193 weight = CW_Constant;
18197 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18198 if (C->getZExtValue() <= 63)
18199 weight = CW_Constant;
18203 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18204 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18205 weight = CW_Constant;
18209 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18210 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18211 weight = CW_Constant;
18215 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18216 if (C->getZExtValue() <= 3)
18217 weight = CW_Constant;
18221 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18222 if (C->getZExtValue() <= 0xff)
18223 weight = CW_Constant;
18228 if (dyn_cast<ConstantFP>(CallOperandVal)) {
18229 weight = CW_Constant;
18233 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18234 if ((C->getSExtValue() >= -0x80000000LL) &&
18235 (C->getSExtValue() <= 0x7fffffffLL))
18236 weight = CW_Constant;
18240 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18241 if (C->getZExtValue() <= 0xffffffff)
18242 weight = CW_Constant;
18249 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18250 /// with another that has more specific requirements based on the type of the
18251 /// corresponding operand.
18252 const char *X86TargetLowering::
18253 LowerXConstraint(EVT ConstraintVT) const {
18254 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18255 // 'f' like normal targets.
18256 if (ConstraintVT.isFloatingPoint()) {
18257 if (Subtarget->hasSSE2())
18259 if (Subtarget->hasSSE1())
18263 return TargetLowering::LowerXConstraint(ConstraintVT);
18266 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18267 /// vector. If it is invalid, don't add anything to Ops.
18268 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18269 std::string &Constraint,
18270 std::vector<SDValue>&Ops,
18271 SelectionDAG &DAG) const {
18272 SDValue Result(0, 0);
18274 // Only support length 1 constraints for now.
18275 if (Constraint.length() > 1) return;
18277 char ConstraintLetter = Constraint[0];
18278 switch (ConstraintLetter) {
18281 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18282 if (C->getZExtValue() <= 31) {
18283 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18289 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18290 if (C->getZExtValue() <= 63) {
18291 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18297 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18298 if (isInt<8>(C->getSExtValue())) {
18299 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18305 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18306 if (C->getZExtValue() <= 255) {
18307 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18313 // 32-bit signed value
18314 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18315 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18316 C->getSExtValue())) {
18317 // Widen to 64 bits here to get it sign extended.
18318 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18321 // FIXME gcc accepts some relocatable values here too, but only in certain
18322 // memory models; it's complicated.
18327 // 32-bit unsigned value
18328 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18329 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18330 C->getZExtValue())) {
18331 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18335 // FIXME gcc accepts some relocatable values here too, but only in certain
18336 // memory models; it's complicated.
18340 // Literal immediates are always ok.
18341 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18342 // Widen to 64 bits here to get it sign extended.
18343 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18347 // In any sort of PIC mode addresses need to be computed at runtime by
18348 // adding in a register or some sort of table lookup. These can't
18349 // be used as immediates.
18350 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18353 // If we are in non-pic codegen mode, we allow the address of a global (with
18354 // an optional displacement) to be used with 'i'.
18355 GlobalAddressSDNode *GA = 0;
18356 int64_t Offset = 0;
18358 // Match either (GA), (GA+C), (GA+C1+C2), etc.
18360 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18361 Offset += GA->getOffset();
18363 } else if (Op.getOpcode() == ISD::ADD) {
18364 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18365 Offset += C->getZExtValue();
18366 Op = Op.getOperand(0);
18369 } else if (Op.getOpcode() == ISD::SUB) {
18370 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18371 Offset += -C->getZExtValue();
18372 Op = Op.getOperand(0);
18377 // Otherwise, this isn't something we can handle, reject it.
18381 const GlobalValue *GV = GA->getGlobal();
18382 // If we require an extra load to get this address, as in PIC mode, we
18383 // can't accept it.
18384 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18385 getTargetMachine())))
18388 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18389 GA->getValueType(0), Offset);
18394 if (Result.getNode()) {
18395 Ops.push_back(Result);
18398 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18401 std::pair<unsigned, const TargetRegisterClass*>
18402 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18404 // First, see if this is a constraint that directly corresponds to an LLVM
18406 if (Constraint.size() == 1) {
18407 // GCC Constraint Letters
18408 switch (Constraint[0]) {
18410 // TODO: Slight differences here in allocation order and leaving
18411 // RIP in the class. Do they matter any more here than they do
18412 // in the normal allocation?
18413 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18414 if (Subtarget->is64Bit()) {
18415 if (VT == MVT::i32 || VT == MVT::f32)
18416 return std::make_pair(0U, &X86::GR32RegClass);
18417 if (VT == MVT::i16)
18418 return std::make_pair(0U, &X86::GR16RegClass);
18419 if (VT == MVT::i8 || VT == MVT::i1)
18420 return std::make_pair(0U, &X86::GR8RegClass);
18421 if (VT == MVT::i64 || VT == MVT::f64)
18422 return std::make_pair(0U, &X86::GR64RegClass);
18425 // 32-bit fallthrough
18426 case 'Q': // Q_REGS
18427 if (VT == MVT::i32 || VT == MVT::f32)
18428 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18429 if (VT == MVT::i16)
18430 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18431 if (VT == MVT::i8 || VT == MVT::i1)
18432 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18433 if (VT == MVT::i64)
18434 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18436 case 'r': // GENERAL_REGS
18437 case 'l': // INDEX_REGS
18438 if (VT == MVT::i8 || VT == MVT::i1)
18439 return std::make_pair(0U, &X86::GR8RegClass);
18440 if (VT == MVT::i16)
18441 return std::make_pair(0U, &X86::GR16RegClass);
18442 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18443 return std::make_pair(0U, &X86::GR32RegClass);
18444 return std::make_pair(0U, &X86::GR64RegClass);
18445 case 'R': // LEGACY_REGS
18446 if (VT == MVT::i8 || VT == MVT::i1)
18447 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18448 if (VT == MVT::i16)
18449 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18450 if (VT == MVT::i32 || !Subtarget->is64Bit())
18451 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18452 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18453 case 'f': // FP Stack registers.
18454 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18455 // value to the correct fpstack register class.
18456 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18457 return std::make_pair(0U, &X86::RFP32RegClass);
18458 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18459 return std::make_pair(0U, &X86::RFP64RegClass);
18460 return std::make_pair(0U, &X86::RFP80RegClass);
18461 case 'y': // MMX_REGS if MMX allowed.
18462 if (!Subtarget->hasMMX()) break;
18463 return std::make_pair(0U, &X86::VR64RegClass);
18464 case 'Y': // SSE_REGS if SSE2 allowed
18465 if (!Subtarget->hasSSE2()) break;
18467 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18468 if (!Subtarget->hasSSE1()) break;
18470 switch (VT.getSimpleVT().SimpleTy) {
18472 // Scalar SSE types.
18475 return std::make_pair(0U, &X86::FR32RegClass);
18478 return std::make_pair(0U, &X86::FR64RegClass);
18486 return std::make_pair(0U, &X86::VR128RegClass);
18494 return std::make_pair(0U, &X86::VR256RegClass);
18500 // Use the default implementation in TargetLowering to convert the register
18501 // constraint into a member of a register class.
18502 std::pair<unsigned, const TargetRegisterClass*> Res;
18503 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18505 // Not found as a standard register?
18506 if (Res.second == 0) {
18507 // Map st(0) -> st(7) -> ST0
18508 if (Constraint.size() == 7 && Constraint[0] == '{' &&
18509 tolower(Constraint[1]) == 's' &&
18510 tolower(Constraint[2]) == 't' &&
18511 Constraint[3] == '(' &&
18512 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18513 Constraint[5] == ')' &&
18514 Constraint[6] == '}') {
18516 Res.first = X86::ST0+Constraint[4]-'0';
18517 Res.second = &X86::RFP80RegClass;
18521 // GCC allows "st(0)" to be called just plain "st".
18522 if (StringRef("{st}").equals_lower(Constraint)) {
18523 Res.first = X86::ST0;
18524 Res.second = &X86::RFP80RegClass;
18529 if (StringRef("{flags}").equals_lower(Constraint)) {
18530 Res.first = X86::EFLAGS;
18531 Res.second = &X86::CCRRegClass;
18535 // 'A' means EAX + EDX.
18536 if (Constraint == "A") {
18537 Res.first = X86::EAX;
18538 Res.second = &X86::GR32_ADRegClass;
18544 // Otherwise, check to see if this is a register class of the wrong value
18545 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18546 // turn into {ax},{dx}.
18547 if (Res.second->hasType(VT))
18548 return Res; // Correct type already, nothing to do.
18550 // All of the single-register GCC register classes map their values onto
18551 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
18552 // really want an 8-bit or 32-bit register, map to the appropriate register
18553 // class and return the appropriate register.
18554 if (Res.second == &X86::GR16RegClass) {
18555 if (VT == MVT::i8 || VT == MVT::i1) {
18556 unsigned DestReg = 0;
18557 switch (Res.first) {
18559 case X86::AX: DestReg = X86::AL; break;
18560 case X86::DX: DestReg = X86::DL; break;
18561 case X86::CX: DestReg = X86::CL; break;
18562 case X86::BX: DestReg = X86::BL; break;
18565 Res.first = DestReg;
18566 Res.second = &X86::GR8RegClass;
18568 } else if (VT == MVT::i32 || VT == MVT::f32) {
18569 unsigned DestReg = 0;
18570 switch (Res.first) {
18572 case X86::AX: DestReg = X86::EAX; break;
18573 case X86::DX: DestReg = X86::EDX; break;
18574 case X86::CX: DestReg = X86::ECX; break;
18575 case X86::BX: DestReg = X86::EBX; break;
18576 case X86::SI: DestReg = X86::ESI; break;
18577 case X86::DI: DestReg = X86::EDI; break;
18578 case X86::BP: DestReg = X86::EBP; break;
18579 case X86::SP: DestReg = X86::ESP; break;
18582 Res.first = DestReg;
18583 Res.second = &X86::GR32RegClass;
18585 } else if (VT == MVT::i64 || VT == MVT::f64) {
18586 unsigned DestReg = 0;
18587 switch (Res.first) {
18589 case X86::AX: DestReg = X86::RAX; break;
18590 case X86::DX: DestReg = X86::RDX; break;
18591 case X86::CX: DestReg = X86::RCX; break;
18592 case X86::BX: DestReg = X86::RBX; break;
18593 case X86::SI: DestReg = X86::RSI; break;
18594 case X86::DI: DestReg = X86::RDI; break;
18595 case X86::BP: DestReg = X86::RBP; break;
18596 case X86::SP: DestReg = X86::RSP; break;
18599 Res.first = DestReg;
18600 Res.second = &X86::GR64RegClass;
18603 } else if (Res.second == &X86::FR32RegClass ||
18604 Res.second == &X86::FR64RegClass ||
18605 Res.second == &X86::VR128RegClass) {
18606 // Handle references to XMM physical registers that got mapped into the
18607 // wrong class. This can happen with constraints like {xmm0} where the
18608 // target independent register mapper will just pick the first match it can
18609 // find, ignoring the required type.
18611 if (VT == MVT::f32 || VT == MVT::i32)
18612 Res.second = &X86::FR32RegClass;
18613 else if (VT == MVT::f64 || VT == MVT::i64)
18614 Res.second = &X86::FR64RegClass;
18615 else if (X86::VR128RegClass.hasType(VT))
18616 Res.second = &X86::VR128RegClass;
18617 else if (X86::VR256RegClass.hasType(VT))
18618 Res.second = &X86::VR256RegClass;