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, DebugLoc 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, DebugLoc 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::MEMBARRIER , MVT::Other, Custom);
530 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
532 // On X86 and X86-64, atomic operations are lowered to locked instructions.
533 // Locked instructions, in turn, have implicit fence semantics (all memory
534 // operations are flushed before issuing the locked instruction, and they
535 // are not buffered), so we can fold away the common pattern of
536 // fence-atomic-fence.
537 setShouldFoldAtomicFences(true);
539 // Expand certain atomics
540 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
542 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
543 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
544 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
547 if (!Subtarget->is64Bit()) {
548 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
549 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
550 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
551 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
552 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
553 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
554 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
555 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
556 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
557 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
558 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
559 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
562 if (Subtarget->hasCmpxchg16b()) {
563 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
566 // FIXME - use subtarget debug flags
567 if (!Subtarget->isTargetDarwin() &&
568 !Subtarget->isTargetELF() &&
569 !Subtarget->isTargetCygMing()) {
570 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
573 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
574 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
575 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
576 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
577 if (Subtarget->is64Bit()) {
578 setExceptionPointerRegister(X86::RAX);
579 setExceptionSelectorRegister(X86::RDX);
581 setExceptionPointerRegister(X86::EAX);
582 setExceptionSelectorRegister(X86::EDX);
584 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
585 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
587 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
588 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
590 setOperationAction(ISD::TRAP, MVT::Other, Legal);
591 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
593 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
594 setOperationAction(ISD::VASTART , MVT::Other, Custom);
595 setOperationAction(ISD::VAEND , MVT::Other, Expand);
596 if (Subtarget->is64Bit()) {
597 setOperationAction(ISD::VAARG , MVT::Other, Custom);
598 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
600 setOperationAction(ISD::VAARG , MVT::Other, Expand);
601 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
604 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
605 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
607 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
608 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
609 MVT::i64 : MVT::i32, Custom);
610 else if (TM.Options.EnableSegmentedStacks)
611 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
612 MVT::i64 : MVT::i32, Custom);
614 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
615 MVT::i64 : MVT::i32, Expand);
617 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
618 // f32 and f64 use SSE.
619 // Set up the FP register classes.
620 addRegisterClass(MVT::f32, &X86::FR32RegClass);
621 addRegisterClass(MVT::f64, &X86::FR64RegClass);
623 // Use ANDPD to simulate FABS.
624 setOperationAction(ISD::FABS , MVT::f64, Custom);
625 setOperationAction(ISD::FABS , MVT::f32, Custom);
627 // Use XORP to simulate FNEG.
628 setOperationAction(ISD::FNEG , MVT::f64, Custom);
629 setOperationAction(ISD::FNEG , MVT::f32, Custom);
631 // Use ANDPD and ORPD to simulate FCOPYSIGN.
632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635 // Lower this to FGETSIGNx86 plus an AND.
636 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
637 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
639 // We don't support sin/cos/fmod
640 setOperationAction(ISD::FSIN , MVT::f64, Expand);
641 setOperationAction(ISD::FCOS , MVT::f64, Expand);
642 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
643 setOperationAction(ISD::FSIN , MVT::f32, Expand);
644 setOperationAction(ISD::FCOS , MVT::f32, Expand);
645 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
647 // Expand FP immediates into loads from the stack, except for the special
649 addLegalFPImmediate(APFloat(+0.0)); // xorpd
650 addLegalFPImmediate(APFloat(+0.0f)); // xorps
651 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
652 // Use SSE for f32, x87 for f64.
653 // Set up the FP register classes.
654 addRegisterClass(MVT::f32, &X86::FR32RegClass);
655 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
657 // Use ANDPS to simulate FABS.
658 setOperationAction(ISD::FABS , MVT::f32, Custom);
660 // Use XORP to simulate FNEG.
661 setOperationAction(ISD::FNEG , MVT::f32, Custom);
663 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
665 // Use ANDPS and ORPS to simulate FCOPYSIGN.
666 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
667 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
669 // We don't support sin/cos/fmod
670 setOperationAction(ISD::FSIN , MVT::f32, Expand);
671 setOperationAction(ISD::FCOS , MVT::f32, Expand);
672 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
674 // Special cases we handle for FP constants.
675 addLegalFPImmediate(APFloat(+0.0f)); // xorps
676 addLegalFPImmediate(APFloat(+0.0)); // FLD0
677 addLegalFPImmediate(APFloat(+1.0)); // FLD1
678 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
679 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
681 if (!TM.Options.UnsafeFPMath) {
682 setOperationAction(ISD::FSIN , MVT::f64, Expand);
683 setOperationAction(ISD::FCOS , MVT::f64, Expand);
684 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
686 } else if (!TM.Options.UseSoftFloat) {
687 // f32 and f64 in x87.
688 // Set up the FP register classes.
689 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
690 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
692 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
693 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
694 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
695 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
697 if (!TM.Options.UnsafeFPMath) {
698 setOperationAction(ISD::FSIN , MVT::f64, Expand);
699 setOperationAction(ISD::FSIN , MVT::f32, Expand);
700 setOperationAction(ISD::FCOS , MVT::f64, Expand);
701 setOperationAction(ISD::FCOS , MVT::f32, Expand);
702 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
703 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
705 addLegalFPImmediate(APFloat(+0.0)); // FLD0
706 addLegalFPImmediate(APFloat(+1.0)); // FLD1
707 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
708 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
709 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
710 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
711 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
712 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
715 // We don't support FMA.
716 setOperationAction(ISD::FMA, MVT::f64, Expand);
717 setOperationAction(ISD::FMA, MVT::f32, Expand);
719 // Long double always uses X87.
720 if (!TM.Options.UseSoftFloat) {
721 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
722 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
723 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
725 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
726 addLegalFPImmediate(TmpFlt); // FLD0
728 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
731 APFloat TmpFlt2(+1.0);
732 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
734 addLegalFPImmediate(TmpFlt2); // FLD1
735 TmpFlt2.changeSign();
736 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
739 if (!TM.Options.UnsafeFPMath) {
740 setOperationAction(ISD::FSIN , MVT::f80, Expand);
741 setOperationAction(ISD::FCOS , MVT::f80, Expand);
742 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
745 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
746 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
747 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
748 setOperationAction(ISD::FRINT, MVT::f80, Expand);
749 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
750 setOperationAction(ISD::FMA, MVT::f80, Expand);
753 // Always use a library call for pow.
754 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
755 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
756 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
758 setOperationAction(ISD::FLOG, MVT::f80, Expand);
759 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
760 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
761 setOperationAction(ISD::FEXP, MVT::f80, Expand);
762 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
764 // First set operation action for all vector types to either promote
765 // (for widening) or expand (for scalarization). Then we will selectively
766 // turn on ones that can be effectively codegen'd.
767 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
768 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
769 MVT VT = (MVT::SimpleValueType)i;
770 setOperationAction(ISD::ADD , VT, Expand);
771 setOperationAction(ISD::SUB , VT, Expand);
772 setOperationAction(ISD::FADD, VT, Expand);
773 setOperationAction(ISD::FNEG, VT, Expand);
774 setOperationAction(ISD::FSUB, VT, Expand);
775 setOperationAction(ISD::MUL , VT, Expand);
776 setOperationAction(ISD::FMUL, VT, Expand);
777 setOperationAction(ISD::SDIV, VT, Expand);
778 setOperationAction(ISD::UDIV, VT, Expand);
779 setOperationAction(ISD::FDIV, VT, Expand);
780 setOperationAction(ISD::SREM, VT, Expand);
781 setOperationAction(ISD::UREM, VT, Expand);
782 setOperationAction(ISD::LOAD, VT, Expand);
783 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
784 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
785 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
786 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
787 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
788 setOperationAction(ISD::FABS, VT, Expand);
789 setOperationAction(ISD::FSIN, VT, Expand);
790 setOperationAction(ISD::FSINCOS, VT, Expand);
791 setOperationAction(ISD::FCOS, VT, Expand);
792 setOperationAction(ISD::FSINCOS, VT, Expand);
793 setOperationAction(ISD::FREM, VT, Expand);
794 setOperationAction(ISD::FMA, VT, Expand);
795 setOperationAction(ISD::FPOWI, VT, Expand);
796 setOperationAction(ISD::FSQRT, VT, Expand);
797 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
798 setOperationAction(ISD::FFLOOR, VT, Expand);
799 setOperationAction(ISD::FCEIL, VT, Expand);
800 setOperationAction(ISD::FTRUNC, VT, Expand);
801 setOperationAction(ISD::FRINT, VT, Expand);
802 setOperationAction(ISD::FNEARBYINT, VT, Expand);
803 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
804 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
805 setOperationAction(ISD::SDIVREM, VT, Expand);
806 setOperationAction(ISD::UDIVREM, VT, Expand);
807 setOperationAction(ISD::FPOW, VT, Expand);
808 setOperationAction(ISD::CTPOP, VT, Expand);
809 setOperationAction(ISD::CTTZ, VT, Expand);
810 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
811 setOperationAction(ISD::CTLZ, VT, Expand);
812 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
813 setOperationAction(ISD::SHL, VT, Expand);
814 setOperationAction(ISD::SRA, VT, Expand);
815 setOperationAction(ISD::SRL, VT, Expand);
816 setOperationAction(ISD::ROTL, VT, Expand);
817 setOperationAction(ISD::ROTR, VT, Expand);
818 setOperationAction(ISD::BSWAP, VT, Expand);
819 setOperationAction(ISD::SETCC, VT, Expand);
820 setOperationAction(ISD::FLOG, VT, Expand);
821 setOperationAction(ISD::FLOG2, VT, Expand);
822 setOperationAction(ISD::FLOG10, VT, Expand);
823 setOperationAction(ISD::FEXP, VT, Expand);
824 setOperationAction(ISD::FEXP2, VT, Expand);
825 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
826 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
827 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
828 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
829 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
830 setOperationAction(ISD::TRUNCATE, VT, Expand);
831 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
832 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
833 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
834 setOperationAction(ISD::VSELECT, VT, Expand);
835 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
836 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
837 setTruncStoreAction(VT,
838 (MVT::SimpleValueType)InnerVT, Expand);
839 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
840 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
841 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
844 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
845 // with -msoft-float, disable use of MMX as well.
846 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
847 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
848 // No operations on x86mmx supported, everything uses intrinsics.
851 // MMX-sized vectors (other than x86mmx) are expected to be expanded
852 // into smaller operations.
853 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
854 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
855 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
856 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
857 setOperationAction(ISD::AND, MVT::v8i8, Expand);
858 setOperationAction(ISD::AND, MVT::v4i16, Expand);
859 setOperationAction(ISD::AND, MVT::v2i32, Expand);
860 setOperationAction(ISD::AND, MVT::v1i64, Expand);
861 setOperationAction(ISD::OR, MVT::v8i8, Expand);
862 setOperationAction(ISD::OR, MVT::v4i16, Expand);
863 setOperationAction(ISD::OR, MVT::v2i32, Expand);
864 setOperationAction(ISD::OR, MVT::v1i64, Expand);
865 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
866 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
867 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
868 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
869 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
870 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
871 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
872 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
873 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
874 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
875 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
876 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
877 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
878 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
879 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
880 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
881 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
883 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
884 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
886 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
887 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
888 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
889 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
890 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
891 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
892 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
893 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
894 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
895 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
896 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
897 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
900 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
901 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
903 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
904 // registers cannot be used even for integer operations.
905 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
906 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
907 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
908 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
910 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
911 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
912 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
913 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
914 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
915 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
916 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
917 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
918 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
919 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
920 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
921 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
922 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
923 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
924 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
925 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
926 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
927 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
929 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
930 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
931 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
932 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
934 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
935 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
940 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
941 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
942 MVT VT = (MVT::SimpleValueType)i;
943 // Do not attempt to custom lower non-power-of-2 vectors
944 if (!isPowerOf2_32(VT.getVectorNumElements()))
946 // Do not attempt to custom lower non-128-bit vectors
947 if (!VT.is128BitVector())
949 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
950 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
951 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
954 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
955 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
956 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
957 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
958 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
959 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
961 if (Subtarget->is64Bit()) {
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
963 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
966 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
967 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
968 MVT VT = (MVT::SimpleValueType)i;
970 // Do not attempt to promote non-128-bit vectors
971 if (!VT.is128BitVector())
974 setOperationAction(ISD::AND, VT, Promote);
975 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
976 setOperationAction(ISD::OR, VT, Promote);
977 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
978 setOperationAction(ISD::XOR, VT, Promote);
979 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
980 setOperationAction(ISD::LOAD, VT, Promote);
981 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
982 setOperationAction(ISD::SELECT, VT, Promote);
983 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
986 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
988 // Custom lower v2i64 and v2f64 selects.
989 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
990 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
991 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
992 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
994 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
995 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
997 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
998 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
999 // As there is no 64-bit GPR available, we need build a special custom
1000 // sequence to convert from v2i32 to v2f32.
1001 if (!Subtarget->is64Bit())
1002 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1004 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1005 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1007 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1010 if (Subtarget->hasSSE41()) {
1011 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1012 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1013 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1014 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1015 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1016 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1017 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1018 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1019 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1020 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1022 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1023 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1024 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1025 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1026 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1027 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1028 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1029 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1030 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1031 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1033 // FIXME: Do we need to handle scalar-to-vector here?
1034 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1036 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1037 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1038 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1039 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1040 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1042 // i8 and i16 vectors are custom , because the source register and source
1043 // source memory operand types are not the same width. f32 vectors are
1044 // custom since the immediate controlling the insert encodes additional
1046 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1047 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1048 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1049 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1051 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1052 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1053 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1054 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1056 // FIXME: these should be Legal but thats only for the case where
1057 // the index is constant. For now custom expand to deal with that.
1058 if (Subtarget->is64Bit()) {
1059 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1060 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1064 if (Subtarget->hasSSE2()) {
1065 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1066 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1068 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1069 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1071 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1072 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1074 // In the customized shift lowering, the legal cases in AVX2 will be
1076 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1077 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1079 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1080 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1082 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1084 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1085 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1088 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1089 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1090 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1091 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1092 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1093 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1094 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1096 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1097 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1098 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1100 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1101 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1102 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1103 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1104 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1105 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1106 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1107 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1108 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1109 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1110 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1111 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1113 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1114 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1115 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1116 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1117 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1118 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1119 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1120 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1121 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1122 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1123 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1124 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1126 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1127 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1129 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1131 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1132 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1133 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1134 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1136 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1137 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1138 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1140 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1142 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1143 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1145 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1146 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1148 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1149 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1151 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1153 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1154 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1155 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1156 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1158 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1159 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1160 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1162 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1163 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1164 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1165 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1167 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1168 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1169 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1170 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1171 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1172 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1174 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1175 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1176 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1177 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1178 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1179 setOperationAction(ISD::FMA, MVT::f32, Legal);
1180 setOperationAction(ISD::FMA, MVT::f64, Legal);
1183 if (Subtarget->hasInt256()) {
1184 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1185 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1186 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1187 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1189 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1190 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1191 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1192 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1194 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1195 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1196 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1197 // Don't lower v32i8 because there is no 128-bit byte mul
1199 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1201 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1203 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1204 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1205 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1206 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1208 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1209 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1210 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1211 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1213 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1214 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1215 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1216 // Don't lower v32i8 because there is no 128-bit byte mul
1219 // In the customized shift lowering, the legal cases in AVX2 will be
1221 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1222 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1224 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1225 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1227 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1229 // Custom lower several nodes for 256-bit types.
1230 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1231 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1232 MVT VT = (MVT::SimpleValueType)i;
1234 // Extract subvector is special because the value type
1235 // (result) is 128-bit but the source is 256-bit wide.
1236 if (VT.is128BitVector())
1237 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1239 // Do not attempt to custom lower other non-256-bit vectors
1240 if (!VT.is256BitVector())
1243 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1244 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1245 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1246 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1247 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1248 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1249 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1252 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1253 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1254 MVT VT = (MVT::SimpleValueType)i;
1256 // Do not attempt to promote non-256-bit vectors
1257 if (!VT.is256BitVector())
1260 setOperationAction(ISD::AND, VT, Promote);
1261 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1262 setOperationAction(ISD::OR, VT, Promote);
1263 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1264 setOperationAction(ISD::XOR, VT, Promote);
1265 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1266 setOperationAction(ISD::LOAD, VT, Promote);
1267 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1268 setOperationAction(ISD::SELECT, VT, Promote);
1269 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1273 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1274 // of this type with custom code.
1275 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1276 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1277 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1281 // We want to custom lower some of our intrinsics.
1282 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1283 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1285 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1286 // handle type legalization for these operations here.
1288 // FIXME: We really should do custom legalization for addition and
1289 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1290 // than generic legalization for 64-bit multiplication-with-overflow, though.
1291 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1292 // Add/Sub/Mul with overflow operations are custom lowered.
1294 setOperationAction(ISD::SADDO, VT, Custom);
1295 setOperationAction(ISD::UADDO, VT, Custom);
1296 setOperationAction(ISD::SSUBO, VT, Custom);
1297 setOperationAction(ISD::USUBO, VT, Custom);
1298 setOperationAction(ISD::SMULO, VT, Custom);
1299 setOperationAction(ISD::UMULO, VT, Custom);
1302 // There are no 8-bit 3-address imul/mul instructions
1303 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1304 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1306 if (!Subtarget->is64Bit()) {
1307 // These libcalls are not available in 32-bit.
1308 setLibcallName(RTLIB::SHL_I128, 0);
1309 setLibcallName(RTLIB::SRL_I128, 0);
1310 setLibcallName(RTLIB::SRA_I128, 0);
1313 // Combine sin / cos into one node or libcall if possible.
1314 if (Subtarget->hasSinCos()) {
1315 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1316 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1317 if (Subtarget->isTargetDarwin()) {
1318 // For MacOSX, we don't want to the normal expansion of a libcall to
1319 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1321 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1322 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1326 // We have target-specific dag combine patterns for the following nodes:
1327 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1328 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1329 setTargetDAGCombine(ISD::VSELECT);
1330 setTargetDAGCombine(ISD::SELECT);
1331 setTargetDAGCombine(ISD::SHL);
1332 setTargetDAGCombine(ISD::SRA);
1333 setTargetDAGCombine(ISD::SRL);
1334 setTargetDAGCombine(ISD::OR);
1335 setTargetDAGCombine(ISD::AND);
1336 setTargetDAGCombine(ISD::ADD);
1337 setTargetDAGCombine(ISD::FADD);
1338 setTargetDAGCombine(ISD::FSUB);
1339 setTargetDAGCombine(ISD::FMA);
1340 setTargetDAGCombine(ISD::SUB);
1341 setTargetDAGCombine(ISD::LOAD);
1342 setTargetDAGCombine(ISD::STORE);
1343 setTargetDAGCombine(ISD::ZERO_EXTEND);
1344 setTargetDAGCombine(ISD::ANY_EXTEND);
1345 setTargetDAGCombine(ISD::SIGN_EXTEND);
1346 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1347 setTargetDAGCombine(ISD::TRUNCATE);
1348 setTargetDAGCombine(ISD::SINT_TO_FP);
1349 setTargetDAGCombine(ISD::SETCC);
1350 if (Subtarget->is64Bit())
1351 setTargetDAGCombine(ISD::MUL);
1352 setTargetDAGCombine(ISD::XOR);
1354 computeRegisterProperties();
1356 // On Darwin, -Os means optimize for size without hurting performance,
1357 // do not reduce the limit.
1358 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1359 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1360 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1361 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1362 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1363 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1364 setPrefLoopAlignment(4); // 2^4 bytes.
1366 // Predictable cmov don't hurt on atom because it's in-order.
1367 PredictableSelectIsExpensive = !Subtarget->isAtom();
1369 setPrefFunctionAlignment(4); // 2^4 bytes.
1372 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1373 if (!VT.isVector()) return MVT::i8;
1374 return VT.changeVectorElementTypeToInteger();
1377 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1378 /// the desired ByVal argument alignment.
1379 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1382 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1383 if (VTy->getBitWidth() == 128)
1385 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1386 unsigned EltAlign = 0;
1387 getMaxByValAlign(ATy->getElementType(), EltAlign);
1388 if (EltAlign > MaxAlign)
1389 MaxAlign = EltAlign;
1390 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1391 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1392 unsigned EltAlign = 0;
1393 getMaxByValAlign(STy->getElementType(i), EltAlign);
1394 if (EltAlign > MaxAlign)
1395 MaxAlign = EltAlign;
1402 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1403 /// function arguments in the caller parameter area. For X86, aggregates
1404 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1405 /// are at 4-byte boundaries.
1406 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1407 if (Subtarget->is64Bit()) {
1408 // Max of 8 and alignment of type.
1409 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1416 if (Subtarget->hasSSE1())
1417 getMaxByValAlign(Ty, Align);
1421 /// getOptimalMemOpType - Returns the target specific optimal type for load
1422 /// and store operations as a result of memset, memcpy, and memmove
1423 /// lowering. If DstAlign is zero that means it's safe to destination
1424 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1425 /// means there isn't a need to check it against alignment requirement,
1426 /// probably because the source does not need to be loaded. If 'IsMemset' is
1427 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1428 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1429 /// source is constant so it does not need to be loaded.
1430 /// It returns EVT::Other if the type should be determined using generic
1431 /// target-independent logic.
1433 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1434 unsigned DstAlign, unsigned SrcAlign,
1435 bool IsMemset, bool ZeroMemset,
1437 MachineFunction &MF) const {
1438 const Function *F = MF.getFunction();
1439 if ((!IsMemset || ZeroMemset) &&
1440 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1441 Attribute::NoImplicitFloat)) {
1443 (Subtarget->isUnalignedMemAccessFast() ||
1444 ((DstAlign == 0 || DstAlign >= 16) &&
1445 (SrcAlign == 0 || SrcAlign >= 16)))) {
1447 if (Subtarget->hasInt256())
1449 if (Subtarget->hasFp256())
1452 if (Subtarget->hasSSE2())
1454 if (Subtarget->hasSSE1())
1456 } else if (!MemcpyStrSrc && Size >= 8 &&
1457 !Subtarget->is64Bit() &&
1458 Subtarget->hasSSE2()) {
1459 // Do not use f64 to lower memcpy if source is string constant. It's
1460 // better to use i32 to avoid the loads.
1464 if (Subtarget->is64Bit() && Size >= 8)
1469 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1471 return X86ScalarSSEf32;
1472 else if (VT == MVT::f64)
1473 return X86ScalarSSEf64;
1478 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1480 *Fast = Subtarget->isUnalignedMemAccessFast();
1484 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1485 /// current function. The returned value is a member of the
1486 /// MachineJumpTableInfo::JTEntryKind enum.
1487 unsigned X86TargetLowering::getJumpTableEncoding() const {
1488 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1490 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1491 Subtarget->isPICStyleGOT())
1492 return MachineJumpTableInfo::EK_Custom32;
1494 // Otherwise, use the normal jump table encoding heuristics.
1495 return TargetLowering::getJumpTableEncoding();
1499 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1500 const MachineBasicBlock *MBB,
1501 unsigned uid,MCContext &Ctx) const{
1502 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1503 Subtarget->isPICStyleGOT());
1504 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1506 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1507 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1510 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1512 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1513 SelectionDAG &DAG) const {
1514 if (!Subtarget->is64Bit())
1515 // This doesn't have DebugLoc associated with it, but is not really the
1516 // same as a Register.
1517 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1521 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1522 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1524 const MCExpr *X86TargetLowering::
1525 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1526 MCContext &Ctx) const {
1527 // X86-64 uses RIP relative addressing based on the jump table label.
1528 if (Subtarget->isPICStyleRIPRel())
1529 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1531 // Otherwise, the reference is relative to the PIC base.
1532 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1535 // FIXME: Why this routine is here? Move to RegInfo!
1536 std::pair<const TargetRegisterClass*, uint8_t>
1537 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1538 const TargetRegisterClass *RRC = 0;
1540 switch (VT.SimpleTy) {
1542 return TargetLowering::findRepresentativeClass(VT);
1543 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1544 RRC = Subtarget->is64Bit() ?
1545 (const TargetRegisterClass*)&X86::GR64RegClass :
1546 (const TargetRegisterClass*)&X86::GR32RegClass;
1549 RRC = &X86::VR64RegClass;
1551 case MVT::f32: case MVT::f64:
1552 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1553 case MVT::v4f32: case MVT::v2f64:
1554 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1556 RRC = &X86::VR128RegClass;
1559 return std::make_pair(RRC, Cost);
1562 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1563 unsigned &Offset) const {
1564 if (!Subtarget->isTargetLinux())
1567 if (Subtarget->is64Bit()) {
1568 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1570 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1582 //===----------------------------------------------------------------------===//
1583 // Return Value Calling Convention Implementation
1584 //===----------------------------------------------------------------------===//
1586 #include "X86GenCallingConv.inc"
1589 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1590 MachineFunction &MF, bool isVarArg,
1591 const SmallVectorImpl<ISD::OutputArg> &Outs,
1592 LLVMContext &Context) const {
1593 SmallVector<CCValAssign, 16> RVLocs;
1594 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1596 return CCInfo.CheckReturn(Outs, RetCC_X86);
1600 X86TargetLowering::LowerReturn(SDValue Chain,
1601 CallingConv::ID CallConv, bool isVarArg,
1602 const SmallVectorImpl<ISD::OutputArg> &Outs,
1603 const SmallVectorImpl<SDValue> &OutVals,
1604 DebugLoc dl, SelectionDAG &DAG) const {
1605 MachineFunction &MF = DAG.getMachineFunction();
1606 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1608 SmallVector<CCValAssign, 16> RVLocs;
1609 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1610 RVLocs, *DAG.getContext());
1611 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1614 SmallVector<SDValue, 6> RetOps;
1615 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1616 // Operand #1 = Bytes To Pop
1617 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1620 // Copy the result values into the output registers.
1621 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1622 CCValAssign &VA = RVLocs[i];
1623 assert(VA.isRegLoc() && "Can only return in registers!");
1624 SDValue ValToCopy = OutVals[i];
1625 EVT ValVT = ValToCopy.getValueType();
1627 // Promote values to the appropriate types
1628 if (VA.getLocInfo() == CCValAssign::SExt)
1629 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1630 else if (VA.getLocInfo() == CCValAssign::ZExt)
1631 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1632 else if (VA.getLocInfo() == CCValAssign::AExt)
1633 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1634 else if (VA.getLocInfo() == CCValAssign::BCvt)
1635 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1637 // If this is x86-64, and we disabled SSE, we can't return FP values,
1638 // or SSE or MMX vectors.
1639 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1640 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1641 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1642 report_fatal_error("SSE register return with SSE disabled");
1644 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1645 // llvm-gcc has never done it right and no one has noticed, so this
1646 // should be OK for now.
1647 if (ValVT == MVT::f64 &&
1648 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1649 report_fatal_error("SSE2 register return with SSE2 disabled");
1651 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1652 // the RET instruction and handled by the FP Stackifier.
1653 if (VA.getLocReg() == X86::ST0 ||
1654 VA.getLocReg() == X86::ST1) {
1655 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1656 // change the value to the FP stack register class.
1657 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1658 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1659 RetOps.push_back(ValToCopy);
1660 // Don't emit a copytoreg.
1664 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1665 // which is returned in RAX / RDX.
1666 if (Subtarget->is64Bit()) {
1667 if (ValVT == MVT::x86mmx) {
1668 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1669 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1670 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1672 // If we don't have SSE2 available, convert to v4f32 so the generated
1673 // register is legal.
1674 if (!Subtarget->hasSSE2())
1675 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1680 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1681 Flag = Chain.getValue(1);
1682 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1685 // The x86-64 ABIs require that for returning structs by value we copy
1686 // the sret argument into %rax/%eax (depending on ABI) for the return.
1687 // Win32 requires us to put the sret argument to %eax as well.
1688 // We saved the argument into a virtual register in the entry block,
1689 // so now we copy the value out and into %rax/%eax.
1690 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1691 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1692 MachineFunction &MF = DAG.getMachineFunction();
1693 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1694 unsigned Reg = FuncInfo->getSRetReturnReg();
1696 "SRetReturnReg should have been set in LowerFormalArguments().");
1697 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1700 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1701 X86::RAX : X86::EAX;
1702 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1703 Flag = Chain.getValue(1);
1705 // RAX/EAX now acts like a return value.
1706 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1709 RetOps[0] = Chain; // Update chain.
1711 // Add the flag if we have it.
1713 RetOps.push_back(Flag);
1715 return DAG.getNode(X86ISD::RET_FLAG, dl,
1716 MVT::Other, &RetOps[0], RetOps.size());
1719 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1720 if (N->getNumValues() != 1)
1722 if (!N->hasNUsesOfValue(1, 0))
1725 SDValue TCChain = Chain;
1726 SDNode *Copy = *N->use_begin();
1727 if (Copy->getOpcode() == ISD::CopyToReg) {
1728 // If the copy has a glue operand, we conservatively assume it isn't safe to
1729 // perform a tail call.
1730 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1732 TCChain = Copy->getOperand(0);
1733 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1736 bool HasRet = false;
1737 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1739 if (UI->getOpcode() != X86ISD::RET_FLAG)
1752 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1753 ISD::NodeType ExtendKind) const {
1755 // TODO: Is this also valid on 32-bit?
1756 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1757 ReturnMVT = MVT::i8;
1759 ReturnMVT = MVT::i32;
1761 MVT MinVT = getRegisterType(ReturnMVT);
1762 return VT.bitsLT(MinVT) ? MinVT : VT;
1765 /// LowerCallResult - Lower the result values of a call into the
1766 /// appropriate copies out of appropriate physical registers.
1769 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1770 CallingConv::ID CallConv, bool isVarArg,
1771 const SmallVectorImpl<ISD::InputArg> &Ins,
1772 DebugLoc dl, SelectionDAG &DAG,
1773 SmallVectorImpl<SDValue> &InVals) const {
1775 // Assign locations to each value returned by this call.
1776 SmallVector<CCValAssign, 16> RVLocs;
1777 bool Is64Bit = Subtarget->is64Bit();
1778 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1779 getTargetMachine(), RVLocs, *DAG.getContext());
1780 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1782 // Copy all of the result registers out of their specified physreg.
1783 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1784 CCValAssign &VA = RVLocs[i];
1785 EVT CopyVT = VA.getValVT();
1787 // If this is x86-64, and we disabled SSE, we can't return FP values
1788 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1789 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1790 report_fatal_error("SSE register return with SSE disabled");
1795 // If this is a call to a function that returns an fp value on the floating
1796 // point stack, we must guarantee the value is popped from the stack, so
1797 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1798 // if the return value is not used. We use the FpPOP_RETVAL instruction
1800 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1801 // If we prefer to use the value in xmm registers, copy it out as f80 and
1802 // use a truncate to move it from fp stack reg to xmm reg.
1803 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1804 SDValue Ops[] = { Chain, InFlag };
1805 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1806 MVT::Other, MVT::Glue, Ops, 2), 1);
1807 Val = Chain.getValue(0);
1809 // Round the f80 to the right size, which also moves it to the appropriate
1811 if (CopyVT != VA.getValVT())
1812 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1813 // This truncation won't change the value.
1814 DAG.getIntPtrConstant(1));
1816 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1817 CopyVT, InFlag).getValue(1);
1818 Val = Chain.getValue(0);
1820 InFlag = Chain.getValue(2);
1821 InVals.push_back(Val);
1827 //===----------------------------------------------------------------------===//
1828 // C & StdCall & Fast Calling Convention implementation
1829 //===----------------------------------------------------------------------===//
1830 // StdCall calling convention seems to be standard for many Windows' API
1831 // routines and around. It differs from C calling convention just a little:
1832 // callee should clean up the stack, not caller. Symbols should be also
1833 // decorated in some fancy way :) It doesn't support any vector arguments.
1834 // For info on fast calling convention see Fast Calling Convention (tail call)
1835 // implementation LowerX86_32FastCCCallTo.
1837 /// CallIsStructReturn - Determines whether a call uses struct return
1839 enum StructReturnType {
1844 static StructReturnType
1845 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1847 return NotStructReturn;
1849 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1850 if (!Flags.isSRet())
1851 return NotStructReturn;
1852 if (Flags.isInReg())
1853 return RegStructReturn;
1854 return StackStructReturn;
1857 /// ArgsAreStructReturn - Determines whether a function uses struct
1858 /// return semantics.
1859 static StructReturnType
1860 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1862 return NotStructReturn;
1864 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1865 if (!Flags.isSRet())
1866 return NotStructReturn;
1867 if (Flags.isInReg())
1868 return RegStructReturn;
1869 return StackStructReturn;
1872 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1873 /// by "Src" to address "Dst" with size and alignment information specified by
1874 /// the specific parameter attribute. The copy will be passed as a byval
1875 /// function parameter.
1877 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1878 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1880 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1882 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1883 /*isVolatile*/false, /*AlwaysInline=*/true,
1884 MachinePointerInfo(), MachinePointerInfo());
1887 /// IsTailCallConvention - Return true if the calling convention is one that
1888 /// supports tail call optimization.
1889 static bool IsTailCallConvention(CallingConv::ID CC) {
1890 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1891 CC == CallingConv::HiPE);
1894 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1895 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1899 CallingConv::ID CalleeCC = CS.getCallingConv();
1900 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1906 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1907 /// a tailcall target by changing its ABI.
1908 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1909 bool GuaranteedTailCallOpt) {
1910 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1914 X86TargetLowering::LowerMemArgument(SDValue Chain,
1915 CallingConv::ID CallConv,
1916 const SmallVectorImpl<ISD::InputArg> &Ins,
1917 DebugLoc dl, SelectionDAG &DAG,
1918 const CCValAssign &VA,
1919 MachineFrameInfo *MFI,
1921 // Create the nodes corresponding to a load from this parameter slot.
1922 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1923 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1924 getTargetMachine().Options.GuaranteedTailCallOpt);
1925 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1928 // If value is passed by pointer we have address passed instead of the value
1930 if (VA.getLocInfo() == CCValAssign::Indirect)
1931 ValVT = VA.getLocVT();
1933 ValVT = VA.getValVT();
1935 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1936 // changed with more analysis.
1937 // In case of tail call optimization mark all arguments mutable. Since they
1938 // could be overwritten by lowering of arguments in case of a tail call.
1939 if (Flags.isByVal()) {
1940 unsigned Bytes = Flags.getByValSize();
1941 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1942 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1943 return DAG.getFrameIndex(FI, getPointerTy());
1945 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1946 VA.getLocMemOffset(), isImmutable);
1947 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1948 return DAG.getLoad(ValVT, dl, Chain, FIN,
1949 MachinePointerInfo::getFixedStack(FI),
1950 false, false, false, 0);
1955 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1956 CallingConv::ID CallConv,
1958 const SmallVectorImpl<ISD::InputArg> &Ins,
1961 SmallVectorImpl<SDValue> &InVals)
1963 MachineFunction &MF = DAG.getMachineFunction();
1964 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1966 const Function* Fn = MF.getFunction();
1967 if (Fn->hasExternalLinkage() &&
1968 Subtarget->isTargetCygMing() &&
1969 Fn->getName() == "main")
1970 FuncInfo->setForceFramePointer(true);
1972 MachineFrameInfo *MFI = MF.getFrameInfo();
1973 bool Is64Bit = Subtarget->is64Bit();
1974 bool IsWindows = Subtarget->isTargetWindows();
1975 bool IsWin64 = Subtarget->isTargetWin64();
1977 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1978 "Var args not supported with calling convention fastcc, ghc or hipe");
1980 // Assign locations to all of the incoming arguments.
1981 SmallVector<CCValAssign, 16> ArgLocs;
1982 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1983 ArgLocs, *DAG.getContext());
1985 // Allocate shadow area for Win64
1987 CCInfo.AllocateStack(32, 8);
1990 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1992 unsigned LastVal = ~0U;
1994 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1995 CCValAssign &VA = ArgLocs[i];
1996 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1998 assert(VA.getValNo() != LastVal &&
1999 "Don't support value assigned to multiple locs yet");
2001 LastVal = VA.getValNo();
2003 if (VA.isRegLoc()) {
2004 EVT RegVT = VA.getLocVT();
2005 const TargetRegisterClass *RC;
2006 if (RegVT == MVT::i32)
2007 RC = &X86::GR32RegClass;
2008 else if (Is64Bit && RegVT == MVT::i64)
2009 RC = &X86::GR64RegClass;
2010 else if (RegVT == MVT::f32)
2011 RC = &X86::FR32RegClass;
2012 else if (RegVT == MVT::f64)
2013 RC = &X86::FR64RegClass;
2014 else if (RegVT.is256BitVector())
2015 RC = &X86::VR256RegClass;
2016 else if (RegVT.is128BitVector())
2017 RC = &X86::VR128RegClass;
2018 else if (RegVT == MVT::x86mmx)
2019 RC = &X86::VR64RegClass;
2021 llvm_unreachable("Unknown argument type!");
2023 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2024 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2026 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2027 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2029 if (VA.getLocInfo() == CCValAssign::SExt)
2030 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2031 DAG.getValueType(VA.getValVT()));
2032 else if (VA.getLocInfo() == CCValAssign::ZExt)
2033 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2034 DAG.getValueType(VA.getValVT()));
2035 else if (VA.getLocInfo() == CCValAssign::BCvt)
2036 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2038 if (VA.isExtInLoc()) {
2039 // Handle MMX values passed in XMM regs.
2040 if (RegVT.isVector())
2041 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2043 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2046 assert(VA.isMemLoc());
2047 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2050 // If value is passed via pointer - do a load.
2051 if (VA.getLocInfo() == CCValAssign::Indirect)
2052 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2053 MachinePointerInfo(), false, false, false, 0);
2055 InVals.push_back(ArgValue);
2058 // The x86-64 ABIs require that for returning structs by value we copy
2059 // the sret argument into %rax/%eax (depending on ABI) for the return.
2060 // Win32 requires us to put the sret argument to %eax as well.
2061 // Save the argument into a virtual register so that we can access it
2062 // from the return points.
2063 if (MF.getFunction()->hasStructRetAttr() &&
2064 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2065 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2066 unsigned Reg = FuncInfo->getSRetReturnReg();
2068 MVT PtrTy = getPointerTy();
2069 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2070 FuncInfo->setSRetReturnReg(Reg);
2072 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2073 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2076 unsigned StackSize = CCInfo.getNextStackOffset();
2077 // Align stack specially for tail calls.
2078 if (FuncIsMadeTailCallSafe(CallConv,
2079 MF.getTarget().Options.GuaranteedTailCallOpt))
2080 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2082 // If the function takes variable number of arguments, make a frame index for
2083 // the start of the first vararg value... for expansion of llvm.va_start.
2085 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2086 CallConv != CallingConv::X86_ThisCall)) {
2087 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2090 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2092 // FIXME: We should really autogenerate these arrays
2093 static const uint16_t GPR64ArgRegsWin64[] = {
2094 X86::RCX, X86::RDX, X86::R8, X86::R9
2096 static const uint16_t GPR64ArgRegs64Bit[] = {
2097 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2099 static const uint16_t XMMArgRegs64Bit[] = {
2100 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2101 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2103 const uint16_t *GPR64ArgRegs;
2104 unsigned NumXMMRegs = 0;
2107 // The XMM registers which might contain var arg parameters are shadowed
2108 // in their paired GPR. So we only need to save the GPR to their home
2110 TotalNumIntRegs = 4;
2111 GPR64ArgRegs = GPR64ArgRegsWin64;
2113 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2114 GPR64ArgRegs = GPR64ArgRegs64Bit;
2116 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2119 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2122 bool NoImplicitFloatOps = Fn->getAttributes().
2123 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2124 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2125 "SSE register cannot be used when SSE is disabled!");
2126 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2127 NoImplicitFloatOps) &&
2128 "SSE register cannot be used when SSE is disabled!");
2129 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2130 !Subtarget->hasSSE1())
2131 // Kernel mode asks for SSE to be disabled, so don't push them
2133 TotalNumXMMRegs = 0;
2136 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2137 // Get to the caller-allocated home save location. Add 8 to account
2138 // for the return address.
2139 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2140 FuncInfo->setRegSaveFrameIndex(
2141 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2142 // Fixup to set vararg frame on shadow area (4 x i64).
2144 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2146 // For X86-64, if there are vararg parameters that are passed via
2147 // registers, then we must store them to their spots on the stack so
2148 // they may be loaded by deferencing the result of va_next.
2149 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2150 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2151 FuncInfo->setRegSaveFrameIndex(
2152 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2156 // Store the integer parameter registers.
2157 SmallVector<SDValue, 8> MemOps;
2158 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2160 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2161 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2162 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2163 DAG.getIntPtrConstant(Offset));
2164 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2165 &X86::GR64RegClass);
2166 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2168 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2169 MachinePointerInfo::getFixedStack(
2170 FuncInfo->getRegSaveFrameIndex(), Offset),
2172 MemOps.push_back(Store);
2176 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2177 // Now store the XMM (fp + vector) parameter registers.
2178 SmallVector<SDValue, 11> SaveXMMOps;
2179 SaveXMMOps.push_back(Chain);
2181 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2182 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2183 SaveXMMOps.push_back(ALVal);
2185 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2186 FuncInfo->getRegSaveFrameIndex()));
2187 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2188 FuncInfo->getVarArgsFPOffset()));
2190 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2191 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2192 &X86::VR128RegClass);
2193 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2194 SaveXMMOps.push_back(Val);
2196 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2198 &SaveXMMOps[0], SaveXMMOps.size()));
2201 if (!MemOps.empty())
2202 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2203 &MemOps[0], MemOps.size());
2207 // Some CCs need callee pop.
2208 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2209 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2210 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2212 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2213 // If this is an sret function, the return should pop the hidden pointer.
2214 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2215 argsAreStructReturn(Ins) == StackStructReturn)
2216 FuncInfo->setBytesToPopOnReturn(4);
2220 // RegSaveFrameIndex is X86-64 only.
2221 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2222 if (CallConv == CallingConv::X86_FastCall ||
2223 CallConv == CallingConv::X86_ThisCall)
2224 // fastcc functions can't have varargs.
2225 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2228 FuncInfo->setArgumentStackSize(StackSize);
2234 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2235 SDValue StackPtr, SDValue Arg,
2236 DebugLoc dl, SelectionDAG &DAG,
2237 const CCValAssign &VA,
2238 ISD::ArgFlagsTy Flags) const {
2239 unsigned LocMemOffset = VA.getLocMemOffset();
2240 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2241 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2242 if (Flags.isByVal())
2243 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2245 return DAG.getStore(Chain, dl, Arg, PtrOff,
2246 MachinePointerInfo::getStack(LocMemOffset),
2250 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2251 /// optimization is performed and it is required.
2253 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2254 SDValue &OutRetAddr, SDValue Chain,
2255 bool IsTailCall, bool Is64Bit,
2256 int FPDiff, DebugLoc dl) const {
2257 // Adjust the Return address stack slot.
2258 EVT VT = getPointerTy();
2259 OutRetAddr = getReturnAddressFrameIndex(DAG);
2261 // Load the "old" Return address.
2262 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2263 false, false, false, 0);
2264 return SDValue(OutRetAddr.getNode(), 1);
2267 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2268 /// optimization is performed and it is required (FPDiff!=0).
2270 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2271 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2272 unsigned SlotSize, int FPDiff, DebugLoc dl) {
2273 // Store the return address to the appropriate stack slot.
2274 if (!FPDiff) return Chain;
2275 // Calculate the new stack slot for the return address.
2276 int NewReturnAddrFI =
2277 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2278 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2279 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2280 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2286 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2287 SmallVectorImpl<SDValue> &InVals) const {
2288 SelectionDAG &DAG = CLI.DAG;
2289 DebugLoc &dl = CLI.DL;
2290 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2291 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2292 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2293 SDValue Chain = CLI.Chain;
2294 SDValue Callee = CLI.Callee;
2295 CallingConv::ID CallConv = CLI.CallConv;
2296 bool &isTailCall = CLI.IsTailCall;
2297 bool isVarArg = CLI.IsVarArg;
2299 MachineFunction &MF = DAG.getMachineFunction();
2300 bool Is64Bit = Subtarget->is64Bit();
2301 bool IsWin64 = Subtarget->isTargetWin64();
2302 bool IsWindows = Subtarget->isTargetWindows();
2303 StructReturnType SR = callIsStructReturn(Outs);
2304 bool IsSibcall = false;
2306 if (MF.getTarget().Options.DisableTailCalls)
2310 // Check if it's really possible to do a tail call.
2311 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2312 isVarArg, SR != NotStructReturn,
2313 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2314 Outs, OutVals, Ins, DAG);
2316 // Sibcalls are automatically detected tailcalls which do not require
2318 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2325 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2326 "Var args not supported with calling convention fastcc, ghc or hipe");
2328 // Analyze operands of the call, assigning locations to each operand.
2329 SmallVector<CCValAssign, 16> ArgLocs;
2330 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2331 ArgLocs, *DAG.getContext());
2333 // Allocate shadow area for Win64
2335 CCInfo.AllocateStack(32, 8);
2338 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2340 // Get a count of how many bytes are to be pushed on the stack.
2341 unsigned NumBytes = CCInfo.getNextStackOffset();
2343 // This is a sibcall. The memory operands are available in caller's
2344 // own caller's stack.
2346 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2347 IsTailCallConvention(CallConv))
2348 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2351 if (isTailCall && !IsSibcall) {
2352 // Lower arguments at fp - stackoffset + fpdiff.
2353 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2354 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2356 FPDiff = NumBytesCallerPushed - NumBytes;
2358 // Set the delta of movement of the returnaddr stackslot.
2359 // But only set if delta is greater than previous delta.
2360 if (FPDiff < X86Info->getTCReturnAddrDelta())
2361 X86Info->setTCReturnAddrDelta(FPDiff);
2365 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2367 SDValue RetAddrFrIdx;
2368 // Load return address for tail calls.
2369 if (isTailCall && FPDiff)
2370 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2371 Is64Bit, FPDiff, dl);
2373 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2374 SmallVector<SDValue, 8> MemOpChains;
2377 // Walk the register/memloc assignments, inserting copies/loads. In the case
2378 // of tail call optimization arguments are handle later.
2379 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2380 CCValAssign &VA = ArgLocs[i];
2381 EVT RegVT = VA.getLocVT();
2382 SDValue Arg = OutVals[i];
2383 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2384 bool isByVal = Flags.isByVal();
2386 // Promote the value if needed.
2387 switch (VA.getLocInfo()) {
2388 default: llvm_unreachable("Unknown loc info!");
2389 case CCValAssign::Full: break;
2390 case CCValAssign::SExt:
2391 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2393 case CCValAssign::ZExt:
2394 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2396 case CCValAssign::AExt:
2397 if (RegVT.is128BitVector()) {
2398 // Special case: passing MMX values in XMM registers.
2399 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2400 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2401 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2403 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2405 case CCValAssign::BCvt:
2406 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2408 case CCValAssign::Indirect: {
2409 // Store the argument.
2410 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2411 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2412 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2413 MachinePointerInfo::getFixedStack(FI),
2420 if (VA.isRegLoc()) {
2421 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2422 if (isVarArg && IsWin64) {
2423 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2424 // shadow reg if callee is a varargs function.
2425 unsigned ShadowReg = 0;
2426 switch (VA.getLocReg()) {
2427 case X86::XMM0: ShadowReg = X86::RCX; break;
2428 case X86::XMM1: ShadowReg = X86::RDX; break;
2429 case X86::XMM2: ShadowReg = X86::R8; break;
2430 case X86::XMM3: ShadowReg = X86::R9; break;
2433 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2435 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2436 assert(VA.isMemLoc());
2437 if (StackPtr.getNode() == 0)
2438 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2440 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2441 dl, DAG, VA, Flags));
2445 if (!MemOpChains.empty())
2446 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2447 &MemOpChains[0], MemOpChains.size());
2449 if (Subtarget->isPICStyleGOT()) {
2450 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2453 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2454 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2456 // If we are tail calling and generating PIC/GOT style code load the
2457 // address of the callee into ECX. The value in ecx is used as target of
2458 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2459 // for tail calls on PIC/GOT architectures. Normally we would just put the
2460 // address of GOT into ebx and then call target@PLT. But for tail calls
2461 // ebx would be restored (since ebx is callee saved) before jumping to the
2464 // Note: The actual moving to ECX is done further down.
2465 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2466 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2467 !G->getGlobal()->hasProtectedVisibility())
2468 Callee = LowerGlobalAddress(Callee, DAG);
2469 else if (isa<ExternalSymbolSDNode>(Callee))
2470 Callee = LowerExternalSymbol(Callee, DAG);
2474 if (Is64Bit && isVarArg && !IsWin64) {
2475 // From AMD64 ABI document:
2476 // For calls that may call functions that use varargs or stdargs
2477 // (prototype-less calls or calls to functions containing ellipsis (...) in
2478 // the declaration) %al is used as hidden argument to specify the number
2479 // of SSE registers used. The contents of %al do not need to match exactly
2480 // the number of registers, but must be an ubound on the number of SSE
2481 // registers used and is in the range 0 - 8 inclusive.
2483 // Count the number of XMM registers allocated.
2484 static const uint16_t XMMArgRegs[] = {
2485 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2486 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2488 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2489 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2490 && "SSE registers cannot be used when SSE is disabled");
2492 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2493 DAG.getConstant(NumXMMRegs, MVT::i8)));
2496 // For tail calls lower the arguments to the 'real' stack slot.
2498 // Force all the incoming stack arguments to be loaded from the stack
2499 // before any new outgoing arguments are stored to the stack, because the
2500 // outgoing stack slots may alias the incoming argument stack slots, and
2501 // the alias isn't otherwise explicit. This is slightly more conservative
2502 // than necessary, because it means that each store effectively depends
2503 // on every argument instead of just those arguments it would clobber.
2504 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2506 SmallVector<SDValue, 8> MemOpChains2;
2509 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2510 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2511 CCValAssign &VA = ArgLocs[i];
2514 assert(VA.isMemLoc());
2515 SDValue Arg = OutVals[i];
2516 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2517 // Create frame index.
2518 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2519 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2520 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2521 FIN = DAG.getFrameIndex(FI, getPointerTy());
2523 if (Flags.isByVal()) {
2524 // Copy relative to framepointer.
2525 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2526 if (StackPtr.getNode() == 0)
2527 StackPtr = DAG.getCopyFromReg(Chain, dl,
2528 RegInfo->getStackRegister(),
2530 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2532 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2536 // Store relative to framepointer.
2537 MemOpChains2.push_back(
2538 DAG.getStore(ArgChain, dl, Arg, FIN,
2539 MachinePointerInfo::getFixedStack(FI),
2545 if (!MemOpChains2.empty())
2546 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2547 &MemOpChains2[0], MemOpChains2.size());
2549 // Store the return address to the appropriate stack slot.
2550 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2551 getPointerTy(), RegInfo->getSlotSize(),
2555 // Build a sequence of copy-to-reg nodes chained together with token chain
2556 // and flag operands which copy the outgoing args into registers.
2558 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2559 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2560 RegsToPass[i].second, InFlag);
2561 InFlag = Chain.getValue(1);
2564 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2565 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2566 // In the 64-bit large code model, we have to make all calls
2567 // through a register, since the call instruction's 32-bit
2568 // pc-relative offset may not be large enough to hold the whole
2570 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2571 // If the callee is a GlobalAddress node (quite common, every direct call
2572 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2575 // We should use extra load for direct calls to dllimported functions in
2577 const GlobalValue *GV = G->getGlobal();
2578 if (!GV->hasDLLImportLinkage()) {
2579 unsigned char OpFlags = 0;
2580 bool ExtraLoad = false;
2581 unsigned WrapperKind = ISD::DELETED_NODE;
2583 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2584 // external symbols most go through the PLT in PIC mode. If the symbol
2585 // has hidden or protected visibility, or if it is static or local, then
2586 // we don't need to use the PLT - we can directly call it.
2587 if (Subtarget->isTargetELF() &&
2588 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2589 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2590 OpFlags = X86II::MO_PLT;
2591 } else if (Subtarget->isPICStyleStubAny() &&
2592 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2593 (!Subtarget->getTargetTriple().isMacOSX() ||
2594 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2595 // PC-relative references to external symbols should go through $stub,
2596 // unless we're building with the leopard linker or later, which
2597 // automatically synthesizes these stubs.
2598 OpFlags = X86II::MO_DARWIN_STUB;
2599 } else if (Subtarget->isPICStyleRIPRel() &&
2600 isa<Function>(GV) &&
2601 cast<Function>(GV)->getAttributes().
2602 hasAttribute(AttributeSet::FunctionIndex,
2603 Attribute::NonLazyBind)) {
2604 // If the function is marked as non-lazy, generate an indirect call
2605 // which loads from the GOT directly. This avoids runtime overhead
2606 // at the cost of eager binding (and one extra byte of encoding).
2607 OpFlags = X86II::MO_GOTPCREL;
2608 WrapperKind = X86ISD::WrapperRIP;
2612 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2613 G->getOffset(), OpFlags);
2615 // Add a wrapper if needed.
2616 if (WrapperKind != ISD::DELETED_NODE)
2617 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2618 // Add extra indirection if needed.
2620 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2621 MachinePointerInfo::getGOT(),
2622 false, false, false, 0);
2624 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2625 unsigned char OpFlags = 0;
2627 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2628 // external symbols should go through the PLT.
2629 if (Subtarget->isTargetELF() &&
2630 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2631 OpFlags = X86II::MO_PLT;
2632 } else if (Subtarget->isPICStyleStubAny() &&
2633 (!Subtarget->getTargetTriple().isMacOSX() ||
2634 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2635 // PC-relative references to external symbols should go through $stub,
2636 // unless we're building with the leopard linker or later, which
2637 // automatically synthesizes these stubs.
2638 OpFlags = X86II::MO_DARWIN_STUB;
2641 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2645 // Returns a chain & a flag for retval copy to use.
2646 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2647 SmallVector<SDValue, 8> Ops;
2649 if (!IsSibcall && isTailCall) {
2650 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2651 DAG.getIntPtrConstant(0, true), InFlag);
2652 InFlag = Chain.getValue(1);
2655 Ops.push_back(Chain);
2656 Ops.push_back(Callee);
2659 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2661 // Add argument registers to the end of the list so that they are known live
2663 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2664 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2665 RegsToPass[i].second.getValueType()));
2667 // Add a register mask operand representing the call-preserved registers.
2668 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2669 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2670 assert(Mask && "Missing call preserved mask for calling convention");
2671 Ops.push_back(DAG.getRegisterMask(Mask));
2673 if (InFlag.getNode())
2674 Ops.push_back(InFlag);
2678 //// If this is the first return lowered for this function, add the regs
2679 //// to the liveout set for the function.
2680 // This isn't right, although it's probably harmless on x86; liveouts
2681 // should be computed from returns not tail calls. Consider a void
2682 // function making a tail call to a function returning int.
2683 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2686 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2687 InFlag = Chain.getValue(1);
2689 // Create the CALLSEQ_END node.
2690 unsigned NumBytesForCalleeToPush;
2691 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2692 getTargetMachine().Options.GuaranteedTailCallOpt))
2693 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2694 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2695 SR == StackStructReturn)
2696 // If this is a call to a struct-return function, the callee
2697 // pops the hidden struct pointer, so we have to push it back.
2698 // This is common for Darwin/X86, Linux & Mingw32 targets.
2699 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2700 NumBytesForCalleeToPush = 4;
2702 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2704 // Returns a flag for retval copy to use.
2706 Chain = DAG.getCALLSEQ_END(Chain,
2707 DAG.getIntPtrConstant(NumBytes, true),
2708 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2711 InFlag = Chain.getValue(1);
2714 // Handle result values, copying them out of physregs into vregs that we
2716 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2717 Ins, dl, DAG, InVals);
2720 //===----------------------------------------------------------------------===//
2721 // Fast Calling Convention (tail call) implementation
2722 //===----------------------------------------------------------------------===//
2724 // Like std call, callee cleans arguments, convention except that ECX is
2725 // reserved for storing the tail called function address. Only 2 registers are
2726 // free for argument passing (inreg). Tail call optimization is performed
2728 // * tailcallopt is enabled
2729 // * caller/callee are fastcc
2730 // On X86_64 architecture with GOT-style position independent code only local
2731 // (within module) calls are supported at the moment.
2732 // To keep the stack aligned according to platform abi the function
2733 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2734 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2735 // If a tail called function callee has more arguments than the caller the
2736 // caller needs to make sure that there is room to move the RETADDR to. This is
2737 // achieved by reserving an area the size of the argument delta right after the
2738 // original REtADDR, but before the saved framepointer or the spilled registers
2739 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2751 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2752 /// for a 16 byte align requirement.
2754 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2755 SelectionDAG& DAG) const {
2756 MachineFunction &MF = DAG.getMachineFunction();
2757 const TargetMachine &TM = MF.getTarget();
2758 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2759 unsigned StackAlignment = TFI.getStackAlignment();
2760 uint64_t AlignMask = StackAlignment - 1;
2761 int64_t Offset = StackSize;
2762 unsigned SlotSize = RegInfo->getSlotSize();
2763 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2764 // Number smaller than 12 so just add the difference.
2765 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2767 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2768 Offset = ((~AlignMask) & Offset) + StackAlignment +
2769 (StackAlignment-SlotSize);
2774 /// MatchingStackOffset - Return true if the given stack call argument is
2775 /// already available in the same position (relatively) of the caller's
2776 /// incoming argument stack.
2778 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2779 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2780 const X86InstrInfo *TII) {
2781 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2783 if (Arg.getOpcode() == ISD::CopyFromReg) {
2784 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2785 if (!TargetRegisterInfo::isVirtualRegister(VR))
2787 MachineInstr *Def = MRI->getVRegDef(VR);
2790 if (!Flags.isByVal()) {
2791 if (!TII->isLoadFromStackSlot(Def, FI))
2794 unsigned Opcode = Def->getOpcode();
2795 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2796 Def->getOperand(1).isFI()) {
2797 FI = Def->getOperand(1).getIndex();
2798 Bytes = Flags.getByValSize();
2802 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2803 if (Flags.isByVal())
2804 // ByVal argument is passed in as a pointer but it's now being
2805 // dereferenced. e.g.
2806 // define @foo(%struct.X* %A) {
2807 // tail call @bar(%struct.X* byval %A)
2810 SDValue Ptr = Ld->getBasePtr();
2811 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2814 FI = FINode->getIndex();
2815 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2816 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2817 FI = FINode->getIndex();
2818 Bytes = Flags.getByValSize();
2822 assert(FI != INT_MAX);
2823 if (!MFI->isFixedObjectIndex(FI))
2825 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2828 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2829 /// for tail call optimization. Targets which want to do tail call
2830 /// optimization should implement this function.
2832 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2833 CallingConv::ID CalleeCC,
2835 bool isCalleeStructRet,
2836 bool isCallerStructRet,
2838 const SmallVectorImpl<ISD::OutputArg> &Outs,
2839 const SmallVectorImpl<SDValue> &OutVals,
2840 const SmallVectorImpl<ISD::InputArg> &Ins,
2841 SelectionDAG &DAG) const {
2842 if (!IsTailCallConvention(CalleeCC) &&
2843 CalleeCC != CallingConv::C)
2846 // If -tailcallopt is specified, make fastcc functions tail-callable.
2847 const MachineFunction &MF = DAG.getMachineFunction();
2848 const Function *CallerF = DAG.getMachineFunction().getFunction();
2850 // If the function return type is x86_fp80 and the callee return type is not,
2851 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2852 // perform a tailcall optimization here.
2853 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2856 CallingConv::ID CallerCC = CallerF->getCallingConv();
2857 bool CCMatch = CallerCC == CalleeCC;
2859 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2860 if (IsTailCallConvention(CalleeCC) && CCMatch)
2865 // Look for obvious safe cases to perform tail call optimization that do not
2866 // require ABI changes. This is what gcc calls sibcall.
2868 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2869 // emit a special epilogue.
2870 if (RegInfo->needsStackRealignment(MF))
2873 // Also avoid sibcall optimization if either caller or callee uses struct
2874 // return semantics.
2875 if (isCalleeStructRet || isCallerStructRet)
2878 // An stdcall caller is expected to clean up its arguments; the callee
2879 // isn't going to do that.
2880 if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2883 // Do not sibcall optimize vararg calls unless all arguments are passed via
2885 if (isVarArg && !Outs.empty()) {
2887 // Optimizing for varargs on Win64 is unlikely to be safe without
2888 // additional testing.
2889 if (Subtarget->isTargetWin64())
2892 SmallVector<CCValAssign, 16> ArgLocs;
2893 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2894 getTargetMachine(), ArgLocs, *DAG.getContext());
2896 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2897 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2898 if (!ArgLocs[i].isRegLoc())
2902 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2903 // stack. Therefore, if it's not used by the call it is not safe to optimize
2904 // this into a sibcall.
2905 bool Unused = false;
2906 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2913 SmallVector<CCValAssign, 16> RVLocs;
2914 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2915 getTargetMachine(), RVLocs, *DAG.getContext());
2916 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2917 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2918 CCValAssign &VA = RVLocs[i];
2919 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2924 // If the calling conventions do not match, then we'd better make sure the
2925 // results are returned in the same way as what the caller expects.
2927 SmallVector<CCValAssign, 16> RVLocs1;
2928 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2929 getTargetMachine(), RVLocs1, *DAG.getContext());
2930 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2932 SmallVector<CCValAssign, 16> RVLocs2;
2933 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2934 getTargetMachine(), RVLocs2, *DAG.getContext());
2935 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2937 if (RVLocs1.size() != RVLocs2.size())
2939 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2940 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2942 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2944 if (RVLocs1[i].isRegLoc()) {
2945 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2948 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2954 // If the callee takes no arguments then go on to check the results of the
2956 if (!Outs.empty()) {
2957 // Check if stack adjustment is needed. For now, do not do this if any
2958 // argument is passed on the stack.
2959 SmallVector<CCValAssign, 16> ArgLocs;
2960 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2961 getTargetMachine(), ArgLocs, *DAG.getContext());
2963 // Allocate shadow area for Win64
2964 if (Subtarget->isTargetWin64()) {
2965 CCInfo.AllocateStack(32, 8);
2968 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2969 if (CCInfo.getNextStackOffset()) {
2970 MachineFunction &MF = DAG.getMachineFunction();
2971 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2974 // Check if the arguments are already laid out in the right way as
2975 // the caller's fixed stack objects.
2976 MachineFrameInfo *MFI = MF.getFrameInfo();
2977 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2978 const X86InstrInfo *TII =
2979 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2980 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2981 CCValAssign &VA = ArgLocs[i];
2982 SDValue Arg = OutVals[i];
2983 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2984 if (VA.getLocInfo() == CCValAssign::Indirect)
2986 if (!VA.isRegLoc()) {
2987 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2994 // If the tailcall address may be in a register, then make sure it's
2995 // possible to register allocate for it. In 32-bit, the call address can
2996 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2997 // callee-saved registers are restored. These happen to be the same
2998 // registers used to pass 'inreg' arguments so watch out for those.
2999 if (!Subtarget->is64Bit() &&
3000 ((!isa<GlobalAddressSDNode>(Callee) &&
3001 !isa<ExternalSymbolSDNode>(Callee)) ||
3002 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3003 unsigned NumInRegs = 0;
3004 // In PIC we need an extra register to formulate the address computation
3006 unsigned MaxInRegs =
3007 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3009 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3010 CCValAssign &VA = ArgLocs[i];
3013 unsigned Reg = VA.getLocReg();
3016 case X86::EAX: case X86::EDX: case X86::ECX:
3017 if (++NumInRegs == MaxInRegs)
3029 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3030 const TargetLibraryInfo *libInfo) const {
3031 return X86::createFastISel(funcInfo, libInfo);
3034 //===----------------------------------------------------------------------===//
3035 // Other Lowering Hooks
3036 //===----------------------------------------------------------------------===//
3038 static bool MayFoldLoad(SDValue Op) {
3039 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3042 static bool MayFoldIntoStore(SDValue Op) {
3043 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3046 static bool isTargetShuffle(unsigned Opcode) {
3048 default: return false;
3049 case X86ISD::PSHUFD:
3050 case X86ISD::PSHUFHW:
3051 case X86ISD::PSHUFLW:
3053 case X86ISD::PALIGNR:
3054 case X86ISD::MOVLHPS:
3055 case X86ISD::MOVLHPD:
3056 case X86ISD::MOVHLPS:
3057 case X86ISD::MOVLPS:
3058 case X86ISD::MOVLPD:
3059 case X86ISD::MOVSHDUP:
3060 case X86ISD::MOVSLDUP:
3061 case X86ISD::MOVDDUP:
3064 case X86ISD::UNPCKL:
3065 case X86ISD::UNPCKH:
3066 case X86ISD::VPERMILP:
3067 case X86ISD::VPERM2X128:
3068 case X86ISD::VPERMI:
3073 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3074 SDValue V1, SelectionDAG &DAG) {
3076 default: llvm_unreachable("Unknown x86 shuffle node");
3077 case X86ISD::MOVSHDUP:
3078 case X86ISD::MOVSLDUP:
3079 case X86ISD::MOVDDUP:
3080 return DAG.getNode(Opc, dl, VT, V1);
3084 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3085 SDValue V1, unsigned TargetMask,
3086 SelectionDAG &DAG) {
3088 default: llvm_unreachable("Unknown x86 shuffle node");
3089 case X86ISD::PSHUFD:
3090 case X86ISD::PSHUFHW:
3091 case X86ISD::PSHUFLW:
3092 case X86ISD::VPERMILP:
3093 case X86ISD::VPERMI:
3094 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3098 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3099 SDValue V1, SDValue V2, unsigned TargetMask,
3100 SelectionDAG &DAG) {
3102 default: llvm_unreachable("Unknown x86 shuffle node");
3103 case X86ISD::PALIGNR:
3105 case X86ISD::VPERM2X128:
3106 return DAG.getNode(Opc, dl, VT, V1, V2,
3107 DAG.getConstant(TargetMask, MVT::i8));
3111 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3112 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3114 default: llvm_unreachable("Unknown x86 shuffle node");
3115 case X86ISD::MOVLHPS:
3116 case X86ISD::MOVLHPD:
3117 case X86ISD::MOVHLPS:
3118 case X86ISD::MOVLPS:
3119 case X86ISD::MOVLPD:
3122 case X86ISD::UNPCKL:
3123 case X86ISD::UNPCKH:
3124 return DAG.getNode(Opc, dl, VT, V1, V2);
3128 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3129 MachineFunction &MF = DAG.getMachineFunction();
3130 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3131 int ReturnAddrIndex = FuncInfo->getRAIndex();
3133 if (ReturnAddrIndex == 0) {
3134 // Set up a frame object for the return address.
3135 unsigned SlotSize = RegInfo->getSlotSize();
3136 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3138 FuncInfo->setRAIndex(ReturnAddrIndex);
3141 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3144 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3145 bool hasSymbolicDisplacement) {
3146 // Offset should fit into 32 bit immediate field.
3147 if (!isInt<32>(Offset))
3150 // If we don't have a symbolic displacement - we don't have any extra
3152 if (!hasSymbolicDisplacement)
3155 // FIXME: Some tweaks might be needed for medium code model.
3156 if (M != CodeModel::Small && M != CodeModel::Kernel)
3159 // For small code model we assume that latest object is 16MB before end of 31
3160 // bits boundary. We may also accept pretty large negative constants knowing
3161 // that all objects are in the positive half of address space.
3162 if (M == CodeModel::Small && Offset < 16*1024*1024)
3165 // For kernel code model we know that all object resist in the negative half
3166 // of 32bits address space. We may not accept negative offsets, since they may
3167 // be just off and we may accept pretty large positive ones.
3168 if (M == CodeModel::Kernel && Offset > 0)
3174 /// isCalleePop - Determines whether the callee is required to pop its
3175 /// own arguments. Callee pop is necessary to support tail calls.
3176 bool X86::isCalleePop(CallingConv::ID CallingConv,
3177 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3181 switch (CallingConv) {
3184 case CallingConv::X86_StdCall:
3186 case CallingConv::X86_FastCall:
3188 case CallingConv::X86_ThisCall:
3190 case CallingConv::Fast:
3192 case CallingConv::GHC:
3194 case CallingConv::HiPE:
3199 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3200 /// specific condition code, returning the condition code and the LHS/RHS of the
3201 /// comparison to make.
3202 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3203 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3205 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3206 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3207 // X > -1 -> X == 0, jump !sign.
3208 RHS = DAG.getConstant(0, RHS.getValueType());
3209 return X86::COND_NS;
3211 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3212 // X < 0 -> X == 0, jump on sign.
3215 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3217 RHS = DAG.getConstant(0, RHS.getValueType());
3218 return X86::COND_LE;
3222 switch (SetCCOpcode) {
3223 default: llvm_unreachable("Invalid integer condition!");
3224 case ISD::SETEQ: return X86::COND_E;
3225 case ISD::SETGT: return X86::COND_G;
3226 case ISD::SETGE: return X86::COND_GE;
3227 case ISD::SETLT: return X86::COND_L;
3228 case ISD::SETLE: return X86::COND_LE;
3229 case ISD::SETNE: return X86::COND_NE;
3230 case ISD::SETULT: return X86::COND_B;
3231 case ISD::SETUGT: return X86::COND_A;
3232 case ISD::SETULE: return X86::COND_BE;
3233 case ISD::SETUGE: return X86::COND_AE;
3237 // First determine if it is required or is profitable to flip the operands.
3239 // If LHS is a foldable load, but RHS is not, flip the condition.
3240 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3241 !ISD::isNON_EXTLoad(RHS.getNode())) {
3242 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3243 std::swap(LHS, RHS);
3246 switch (SetCCOpcode) {
3252 std::swap(LHS, RHS);
3256 // On a floating point condition, the flags are set as follows:
3258 // 0 | 0 | 0 | X > Y
3259 // 0 | 0 | 1 | X < Y
3260 // 1 | 0 | 0 | X == Y
3261 // 1 | 1 | 1 | unordered
3262 switch (SetCCOpcode) {
3263 default: llvm_unreachable("Condcode should be pre-legalized away");
3265 case ISD::SETEQ: return X86::COND_E;
3266 case ISD::SETOLT: // flipped
3268 case ISD::SETGT: return X86::COND_A;
3269 case ISD::SETOLE: // flipped
3271 case ISD::SETGE: return X86::COND_AE;
3272 case ISD::SETUGT: // flipped
3274 case ISD::SETLT: return X86::COND_B;
3275 case ISD::SETUGE: // flipped
3277 case ISD::SETLE: return X86::COND_BE;
3279 case ISD::SETNE: return X86::COND_NE;
3280 case ISD::SETUO: return X86::COND_P;
3281 case ISD::SETO: return X86::COND_NP;
3283 case ISD::SETUNE: return X86::COND_INVALID;
3287 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3288 /// code. Current x86 isa includes the following FP cmov instructions:
3289 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3290 static bool hasFPCMov(unsigned X86CC) {
3306 /// isFPImmLegal - Returns true if the target can instruction select the
3307 /// specified FP immediate natively. If false, the legalizer will
3308 /// materialize the FP immediate as a load from a constant pool.
3309 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3310 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3311 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3317 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3318 /// the specified range (L, H].
3319 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3320 return (Val < 0) || (Val >= Low && Val < Hi);
3323 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3324 /// specified value.
3325 static bool isUndefOrEqual(int Val, int CmpVal) {
3326 return (Val < 0 || Val == CmpVal);
3329 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3330 /// from position Pos and ending in Pos+Size, falls within the specified
3331 /// sequential range (L, L+Pos]. or is undef.
3332 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3333 unsigned Pos, unsigned Size, int Low) {
3334 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3335 if (!isUndefOrEqual(Mask[i], Low))
3340 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3341 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3342 /// the second operand.
3343 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3344 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3345 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3346 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3347 return (Mask[0] < 2 && Mask[1] < 2);
3351 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3352 /// is suitable for input to PSHUFHW.
3353 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3354 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3357 // Lower quadword copied in order or undef.
3358 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3361 // Upper quadword shuffled.
3362 for (unsigned i = 4; i != 8; ++i)
3363 if (!isUndefOrInRange(Mask[i], 4, 8))
3366 if (VT == MVT::v16i16) {
3367 // Lower quadword copied in order or undef.
3368 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3371 // Upper quadword shuffled.
3372 for (unsigned i = 12; i != 16; ++i)
3373 if (!isUndefOrInRange(Mask[i], 12, 16))
3380 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3381 /// is suitable for input to PSHUFLW.
3382 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3383 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3386 // Upper quadword copied in order.
3387 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3390 // Lower quadword shuffled.
3391 for (unsigned i = 0; i != 4; ++i)
3392 if (!isUndefOrInRange(Mask[i], 0, 4))
3395 if (VT == MVT::v16i16) {
3396 // Upper quadword copied in order.
3397 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3400 // Lower quadword shuffled.
3401 for (unsigned i = 8; i != 12; ++i)
3402 if (!isUndefOrInRange(Mask[i], 8, 12))
3409 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3410 /// is suitable for input to PALIGNR.
3411 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3412 const X86Subtarget *Subtarget) {
3413 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3414 (VT.is256BitVector() && !Subtarget->hasInt256()))
3417 unsigned NumElts = VT.getVectorNumElements();
3418 unsigned NumLanes = VT.getSizeInBits()/128;
3419 unsigned NumLaneElts = NumElts/NumLanes;
3421 // Do not handle 64-bit element shuffles with palignr.
3422 if (NumLaneElts == 2)
3425 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3427 for (i = 0; i != NumLaneElts; ++i) {
3432 // Lane is all undef, go to next lane
3433 if (i == NumLaneElts)
3436 int Start = Mask[i+l];
3438 // Make sure its in this lane in one of the sources
3439 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3440 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3443 // If not lane 0, then we must match lane 0
3444 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3447 // Correct second source to be contiguous with first source
3448 if (Start >= (int)NumElts)
3449 Start -= NumElts - NumLaneElts;
3451 // Make sure we're shifting in the right direction.
3452 if (Start <= (int)(i+l))
3457 // Check the rest of the elements to see if they are consecutive.
3458 for (++i; i != NumLaneElts; ++i) {
3459 int Idx = Mask[i+l];
3461 // Make sure its in this lane
3462 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3463 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3466 // If not lane 0, then we must match lane 0
3467 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3470 if (Idx >= (int)NumElts)
3471 Idx -= NumElts - NumLaneElts;
3473 if (!isUndefOrEqual(Idx, Start+i))
3482 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3483 /// the two vector operands have swapped position.
3484 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3485 unsigned NumElems) {
3486 for (unsigned i = 0; i != NumElems; ++i) {
3490 else if (idx < (int)NumElems)
3491 Mask[i] = idx + NumElems;
3493 Mask[i] = idx - NumElems;
3497 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3498 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3499 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3500 /// reverse of what x86 shuffles want.
3501 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3502 bool Commuted = false) {
3503 if (!HasFp256 && VT.is256BitVector())
3506 unsigned NumElems = VT.getVectorNumElements();
3507 unsigned NumLanes = VT.getSizeInBits()/128;
3508 unsigned NumLaneElems = NumElems/NumLanes;
3510 if (NumLaneElems != 2 && NumLaneElems != 4)
3513 // VSHUFPSY divides the resulting vector into 4 chunks.
3514 // The sources are also splitted into 4 chunks, and each destination
3515 // chunk must come from a different source chunk.
3517 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3518 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3520 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3521 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3523 // VSHUFPDY divides the resulting vector into 4 chunks.
3524 // The sources are also splitted into 4 chunks, and each destination
3525 // chunk must come from a different source chunk.
3527 // SRC1 => X3 X2 X1 X0
3528 // SRC2 => Y3 Y2 Y1 Y0
3530 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3532 unsigned HalfLaneElems = NumLaneElems/2;
3533 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3534 for (unsigned i = 0; i != NumLaneElems; ++i) {
3535 int Idx = Mask[i+l];
3536 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3537 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3539 // For VSHUFPSY, the mask of the second half must be the same as the
3540 // first but with the appropriate offsets. This works in the same way as
3541 // VPERMILPS works with masks.
3542 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3544 if (!isUndefOrEqual(Idx, Mask[i]+l))
3552 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3553 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3554 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3555 if (!VT.is128BitVector())
3558 unsigned NumElems = VT.getVectorNumElements();
3563 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3564 return isUndefOrEqual(Mask[0], 6) &&
3565 isUndefOrEqual(Mask[1], 7) &&
3566 isUndefOrEqual(Mask[2], 2) &&
3567 isUndefOrEqual(Mask[3], 3);
3570 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3571 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3573 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3574 if (!VT.is128BitVector())
3577 unsigned NumElems = VT.getVectorNumElements();
3582 return isUndefOrEqual(Mask[0], 2) &&
3583 isUndefOrEqual(Mask[1], 3) &&
3584 isUndefOrEqual(Mask[2], 2) &&
3585 isUndefOrEqual(Mask[3], 3);
3588 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3589 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3590 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3591 if (!VT.is128BitVector())
3594 unsigned NumElems = VT.getVectorNumElements();
3596 if (NumElems != 2 && NumElems != 4)
3599 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3600 if (!isUndefOrEqual(Mask[i], i + NumElems))
3603 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3604 if (!isUndefOrEqual(Mask[i], i))
3610 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3611 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3612 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3613 if (!VT.is128BitVector())
3616 unsigned NumElems = VT.getVectorNumElements();
3618 if (NumElems != 2 && NumElems != 4)
3621 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3622 if (!isUndefOrEqual(Mask[i], i))
3625 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3626 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3633 // Some special combinations that can be optimized.
3636 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3637 SelectionDAG &DAG) {
3638 MVT VT = SVOp->getValueType(0).getSimpleVT();
3639 DebugLoc dl = SVOp->getDebugLoc();
3641 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3644 ArrayRef<int> Mask = SVOp->getMask();
3646 // These are the special masks that may be optimized.
3647 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3648 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3649 bool MatchEvenMask = true;
3650 bool MatchOddMask = true;
3651 for (int i=0; i<8; ++i) {
3652 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3653 MatchEvenMask = false;
3654 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3655 MatchOddMask = false;
3658 if (!MatchEvenMask && !MatchOddMask)
3661 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3663 SDValue Op0 = SVOp->getOperand(0);
3664 SDValue Op1 = SVOp->getOperand(1);
3666 if (MatchEvenMask) {
3667 // Shift the second operand right to 32 bits.
3668 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3669 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3671 // Shift the first operand left to 32 bits.
3672 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3673 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3675 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3676 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3679 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3680 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3681 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3682 bool HasInt256, bool V2IsSplat = false) {
3683 unsigned NumElts = VT.getVectorNumElements();
3685 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3686 "Unsupported vector type for unpckh");
3688 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3689 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3692 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3693 // independently on 128-bit lanes.
3694 unsigned NumLanes = VT.getSizeInBits()/128;
3695 unsigned NumLaneElts = NumElts/NumLanes;
3697 for (unsigned l = 0; l != NumLanes; ++l) {
3698 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3699 i != (l+1)*NumLaneElts;
3702 int BitI1 = Mask[i+1];
3703 if (!isUndefOrEqual(BitI, j))
3706 if (!isUndefOrEqual(BitI1, NumElts))
3709 if (!isUndefOrEqual(BitI1, j + NumElts))
3718 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3719 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3720 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3721 bool HasInt256, bool V2IsSplat = false) {
3722 unsigned NumElts = VT.getVectorNumElements();
3724 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3725 "Unsupported vector type for unpckh");
3727 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3728 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3731 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3732 // independently on 128-bit lanes.
3733 unsigned NumLanes = VT.getSizeInBits()/128;
3734 unsigned NumLaneElts = NumElts/NumLanes;
3736 for (unsigned l = 0; l != NumLanes; ++l) {
3737 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3738 i != (l+1)*NumLaneElts; i += 2, ++j) {
3740 int BitI1 = Mask[i+1];
3741 if (!isUndefOrEqual(BitI, j))
3744 if (isUndefOrEqual(BitI1, NumElts))
3747 if (!isUndefOrEqual(BitI1, j+NumElts))
3755 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3756 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3758 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3759 unsigned NumElts = VT.getVectorNumElements();
3760 bool Is256BitVec = VT.is256BitVector();
3762 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3763 "Unsupported vector type for unpckh");
3765 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3766 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3769 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3770 // FIXME: Need a better way to get rid of this, there's no latency difference
3771 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3772 // the former later. We should also remove the "_undef" special mask.
3773 if (NumElts == 4 && Is256BitVec)
3776 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3777 // independently on 128-bit lanes.
3778 unsigned NumLanes = VT.getSizeInBits()/128;
3779 unsigned NumLaneElts = NumElts/NumLanes;
3781 for (unsigned l = 0; l != NumLanes; ++l) {
3782 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3783 i != (l+1)*NumLaneElts;
3786 int BitI1 = Mask[i+1];
3788 if (!isUndefOrEqual(BitI, j))
3790 if (!isUndefOrEqual(BitI1, j))
3798 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3799 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3801 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3802 unsigned NumElts = VT.getVectorNumElements();
3804 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3805 "Unsupported vector type for unpckh");
3807 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3808 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3811 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3812 // independently on 128-bit lanes.
3813 unsigned NumLanes = VT.getSizeInBits()/128;
3814 unsigned NumLaneElts = NumElts/NumLanes;
3816 for (unsigned l = 0; l != NumLanes; ++l) {
3817 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3818 i != (l+1)*NumLaneElts; i += 2, ++j) {
3820 int BitI1 = Mask[i+1];
3821 if (!isUndefOrEqual(BitI, j))
3823 if (!isUndefOrEqual(BitI1, j))
3830 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3831 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3832 /// MOVSD, and MOVD, i.e. setting the lowest element.
3833 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3834 if (VT.getVectorElementType().getSizeInBits() < 32)
3836 if (!VT.is128BitVector())
3839 unsigned NumElts = VT.getVectorNumElements();
3841 if (!isUndefOrEqual(Mask[0], NumElts))
3844 for (unsigned i = 1; i != NumElts; ++i)
3845 if (!isUndefOrEqual(Mask[i], i))
3851 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3852 /// as permutations between 128-bit chunks or halves. As an example: this
3854 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3855 /// The first half comes from the second half of V1 and the second half from the
3856 /// the second half of V2.
3857 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3858 if (!HasFp256 || !VT.is256BitVector())
3861 // The shuffle result is divided into half A and half B. In total the two
3862 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3863 // B must come from C, D, E or F.
3864 unsigned HalfSize = VT.getVectorNumElements()/2;
3865 bool MatchA = false, MatchB = false;
3867 // Check if A comes from one of C, D, E, F.
3868 for (unsigned Half = 0; Half != 4; ++Half) {
3869 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3875 // Check if B comes from one of C, D, E, F.
3876 for (unsigned Half = 0; Half != 4; ++Half) {
3877 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3883 return MatchA && MatchB;
3886 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3887 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3888 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3889 MVT VT = SVOp->getValueType(0).getSimpleVT();
3891 unsigned HalfSize = VT.getVectorNumElements()/2;
3893 unsigned FstHalf = 0, SndHalf = 0;
3894 for (unsigned i = 0; i < HalfSize; ++i) {
3895 if (SVOp->getMaskElt(i) > 0) {
3896 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3900 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3901 if (SVOp->getMaskElt(i) > 0) {
3902 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3907 return (FstHalf | (SndHalf << 4));
3910 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3912 /// Note that VPERMIL mask matching is different depending whether theunderlying
3913 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3914 /// to the same elements of the low, but to the higher half of the source.
3915 /// In VPERMILPD the two lanes could be shuffled independently of each other
3916 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3917 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3921 unsigned NumElts = VT.getVectorNumElements();
3922 // Only match 256-bit with 32/64-bit types
3923 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3926 unsigned NumLanes = VT.getSizeInBits()/128;
3927 unsigned LaneSize = NumElts/NumLanes;
3928 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3929 for (unsigned i = 0; i != LaneSize; ++i) {
3930 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3932 if (NumElts != 8 || l == 0)
3934 // VPERMILPS handling
3937 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3945 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3946 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3947 /// element of vector 2 and the other elements to come from vector 1 in order.
3948 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3949 bool V2IsSplat = false, bool V2IsUndef = false) {
3950 if (!VT.is128BitVector())
3953 unsigned NumOps = VT.getVectorNumElements();
3954 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3957 if (!isUndefOrEqual(Mask[0], 0))
3960 for (unsigned i = 1; i != NumOps; ++i)
3961 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3962 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3963 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3969 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3970 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3971 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3972 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3973 const X86Subtarget *Subtarget) {
3974 if (!Subtarget->hasSSE3())
3977 unsigned NumElems = VT.getVectorNumElements();
3979 if ((VT.is128BitVector() && NumElems != 4) ||
3980 (VT.is256BitVector() && NumElems != 8))
3983 // "i+1" is the value the indexed mask element must have
3984 for (unsigned i = 0; i != NumElems; i += 2)
3985 if (!isUndefOrEqual(Mask[i], i+1) ||
3986 !isUndefOrEqual(Mask[i+1], i+1))
3992 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3993 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3994 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3995 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3996 const X86Subtarget *Subtarget) {
3997 if (!Subtarget->hasSSE3())
4000 unsigned NumElems = VT.getVectorNumElements();
4002 if ((VT.is128BitVector() && NumElems != 4) ||
4003 (VT.is256BitVector() && NumElems != 8))
4006 // "i" is the value the indexed mask element must have
4007 for (unsigned i = 0; i != NumElems; i += 2)
4008 if (!isUndefOrEqual(Mask[i], i) ||
4009 !isUndefOrEqual(Mask[i+1], i))
4015 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4016 /// specifies a shuffle of elements that is suitable for input to 256-bit
4017 /// version of MOVDDUP.
4018 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4019 if (!HasFp256 || !VT.is256BitVector())
4022 unsigned NumElts = VT.getVectorNumElements();
4026 for (unsigned i = 0; i != NumElts/2; ++i)
4027 if (!isUndefOrEqual(Mask[i], 0))
4029 for (unsigned i = NumElts/2; i != NumElts; ++i)
4030 if (!isUndefOrEqual(Mask[i], NumElts/2))
4035 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to 128-bit
4037 /// version of MOVDDUP.
4038 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4039 if (!VT.is128BitVector())
4042 unsigned e = VT.getVectorNumElements() / 2;
4043 for (unsigned i = 0; i != e; ++i)
4044 if (!isUndefOrEqual(Mask[i], i))
4046 for (unsigned i = 0; i != e; ++i)
4047 if (!isUndefOrEqual(Mask[e+i], i))
4052 /// isVEXTRACTF128Index - Return true if the specified
4053 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4054 /// suitable for input to VEXTRACTF128.
4055 bool X86::isVEXTRACTF128Index(SDNode *N) {
4056 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4059 // The index should be aligned on a 128-bit boundary.
4061 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4063 MVT VT = N->getValueType(0).getSimpleVT();
4064 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4065 bool Result = (Index * ElSize) % 128 == 0;
4070 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4071 /// operand specifies a subvector insert that is suitable for input to
4073 bool X86::isVINSERTF128Index(SDNode *N) {
4074 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4077 // The index should be aligned on a 128-bit boundary.
4079 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4081 MVT VT = N->getValueType(0).getSimpleVT();
4082 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4083 bool Result = (Index * ElSize) % 128 == 0;
4088 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4089 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4090 /// Handles 128-bit and 256-bit.
4091 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4092 MVT VT = N->getValueType(0).getSimpleVT();
4094 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4095 "Unsupported vector type for PSHUF/SHUFP");
4097 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4098 // independently on 128-bit lanes.
4099 unsigned NumElts = VT.getVectorNumElements();
4100 unsigned NumLanes = VT.getSizeInBits()/128;
4101 unsigned NumLaneElts = NumElts/NumLanes;
4103 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4104 "Only supports 2 or 4 elements per lane");
4106 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4108 for (unsigned i = 0; i != NumElts; ++i) {
4109 int Elt = N->getMaskElt(i);
4110 if (Elt < 0) continue;
4111 Elt &= NumLaneElts - 1;
4112 unsigned ShAmt = (i << Shift) % 8;
4113 Mask |= Elt << ShAmt;
4119 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4120 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4121 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4122 MVT VT = N->getValueType(0).getSimpleVT();
4124 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4125 "Unsupported vector type for PSHUFHW");
4127 unsigned NumElts = VT.getVectorNumElements();
4130 for (unsigned l = 0; l != NumElts; l += 8) {
4131 // 8 nodes per lane, but we only care about the last 4.
4132 for (unsigned i = 0; i < 4; ++i) {
4133 int Elt = N->getMaskElt(l+i+4);
4134 if (Elt < 0) continue;
4135 Elt &= 0x3; // only 2-bits.
4136 Mask |= Elt << (i * 2);
4143 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4144 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4145 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4146 MVT VT = N->getValueType(0).getSimpleVT();
4148 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4149 "Unsupported vector type for PSHUFHW");
4151 unsigned NumElts = VT.getVectorNumElements();
4154 for (unsigned l = 0; l != NumElts; l += 8) {
4155 // 8 nodes per lane, but we only care about the first 4.
4156 for (unsigned i = 0; i < 4; ++i) {
4157 int Elt = N->getMaskElt(l+i);
4158 if (Elt < 0) continue;
4159 Elt &= 0x3; // only 2-bits
4160 Mask |= Elt << (i * 2);
4167 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4168 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4169 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4170 MVT VT = SVOp->getValueType(0).getSimpleVT();
4171 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4173 unsigned NumElts = VT.getVectorNumElements();
4174 unsigned NumLanes = VT.getSizeInBits()/128;
4175 unsigned NumLaneElts = NumElts/NumLanes;
4179 for (i = 0; i != NumElts; ++i) {
4180 Val = SVOp->getMaskElt(i);
4184 if (Val >= (int)NumElts)
4185 Val -= NumElts - NumLaneElts;
4187 assert(Val - i > 0 && "PALIGNR imm should be positive");
4188 return (Val - i) * EltSize;
4191 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4192 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4194 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4195 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4196 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4199 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4201 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4202 MVT ElVT = VecVT.getVectorElementType();
4204 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4205 return Index / NumElemsPerChunk;
4208 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4209 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4211 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4212 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4213 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4216 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4218 MVT VecVT = N->getValueType(0).getSimpleVT();
4219 MVT ElVT = VecVT.getVectorElementType();
4221 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4222 return Index / NumElemsPerChunk;
4225 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4226 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4227 /// Handles 256-bit.
4228 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4229 MVT VT = N->getValueType(0).getSimpleVT();
4231 unsigned NumElts = VT.getVectorNumElements();
4233 assert((VT.is256BitVector() && NumElts == 4) &&
4234 "Unsupported vector type for VPERMQ/VPERMPD");
4237 for (unsigned i = 0; i != NumElts; ++i) {
4238 int Elt = N->getMaskElt(i);
4241 Mask |= Elt << (i*2);
4246 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4248 bool X86::isZeroNode(SDValue Elt) {
4249 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4250 return CN->isNullValue();
4251 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4252 return CFP->getValueAPF().isPosZero();
4256 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4257 /// their permute mask.
4258 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4259 SelectionDAG &DAG) {
4260 MVT VT = SVOp->getValueType(0).getSimpleVT();
4261 unsigned NumElems = VT.getVectorNumElements();
4262 SmallVector<int, 8> MaskVec;
4264 for (unsigned i = 0; i != NumElems; ++i) {
4265 int Idx = SVOp->getMaskElt(i);
4267 if (Idx < (int)NumElems)
4272 MaskVec.push_back(Idx);
4274 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4275 SVOp->getOperand(0), &MaskVec[0]);
4278 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4279 /// match movhlps. The lower half elements should come from upper half of
4280 /// V1 (and in order), and the upper half elements should come from the upper
4281 /// half of V2 (and in order).
4282 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4283 if (!VT.is128BitVector())
4285 if (VT.getVectorNumElements() != 4)
4287 for (unsigned i = 0, e = 2; i != e; ++i)
4288 if (!isUndefOrEqual(Mask[i], i+2))
4290 for (unsigned i = 2; i != 4; ++i)
4291 if (!isUndefOrEqual(Mask[i], i+4))
4296 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4297 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4299 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4300 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4302 N = N->getOperand(0).getNode();
4303 if (!ISD::isNON_EXTLoad(N))
4306 *LD = cast<LoadSDNode>(N);
4310 // Test whether the given value is a vector value which will be legalized
4312 static bool WillBeConstantPoolLoad(SDNode *N) {
4313 if (N->getOpcode() != ISD::BUILD_VECTOR)
4316 // Check for any non-constant elements.
4317 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4318 switch (N->getOperand(i).getNode()->getOpcode()) {
4320 case ISD::ConstantFP:
4327 // Vectors of all-zeros and all-ones are materialized with special
4328 // instructions rather than being loaded.
4329 return !ISD::isBuildVectorAllZeros(N) &&
4330 !ISD::isBuildVectorAllOnes(N);
4333 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4334 /// match movlp{s|d}. The lower half elements should come from lower half of
4335 /// V1 (and in order), and the upper half elements should come from the upper
4336 /// half of V2 (and in order). And since V1 will become the source of the
4337 /// MOVLP, it must be either a vector load or a scalar load to vector.
4338 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4339 ArrayRef<int> Mask, EVT VT) {
4340 if (!VT.is128BitVector())
4343 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4345 // Is V2 is a vector load, don't do this transformation. We will try to use
4346 // load folding shufps op.
4347 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4350 unsigned NumElems = VT.getVectorNumElements();
4352 if (NumElems != 2 && NumElems != 4)
4354 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4355 if (!isUndefOrEqual(Mask[i], i))
4357 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4358 if (!isUndefOrEqual(Mask[i], i+NumElems))
4363 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4365 static bool isSplatVector(SDNode *N) {
4366 if (N->getOpcode() != ISD::BUILD_VECTOR)
4369 SDValue SplatValue = N->getOperand(0);
4370 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4371 if (N->getOperand(i) != SplatValue)
4376 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4377 /// to an zero vector.
4378 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4379 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4380 SDValue V1 = N->getOperand(0);
4381 SDValue V2 = N->getOperand(1);
4382 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4383 for (unsigned i = 0; i != NumElems; ++i) {
4384 int Idx = N->getMaskElt(i);
4385 if (Idx >= (int)NumElems) {
4386 unsigned Opc = V2.getOpcode();
4387 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4389 if (Opc != ISD::BUILD_VECTOR ||
4390 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4392 } else if (Idx >= 0) {
4393 unsigned Opc = V1.getOpcode();
4394 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4396 if (Opc != ISD::BUILD_VECTOR ||
4397 !X86::isZeroNode(V1.getOperand(Idx)))
4404 /// getZeroVector - Returns a vector of specified type with all zero elements.
4406 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4407 SelectionDAG &DAG, DebugLoc dl) {
4408 assert(VT.isVector() && "Expected a vector type");
4410 // Always build SSE zero vectors as <4 x i32> bitcasted
4411 // to their dest type. This ensures they get CSE'd.
4413 if (VT.is128BitVector()) { // SSE
4414 if (Subtarget->hasSSE2()) { // SSE2
4415 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4416 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4418 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4419 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4421 } else if (VT.is256BitVector()) { // AVX
4422 if (Subtarget->hasInt256()) { // AVX2
4423 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4424 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4425 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4427 // 256-bit logic and arithmetic instructions in AVX are all
4428 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4429 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4430 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4431 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4434 llvm_unreachable("Unexpected vector type");
4436 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4439 /// getOnesVector - Returns a vector of specified type with all bits set.
4440 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4441 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4442 /// Then bitcast to their original type, ensuring they get CSE'd.
4443 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4445 assert(VT.isVector() && "Expected a vector type");
4447 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4449 if (VT.is256BitVector()) {
4450 if (HasInt256) { // AVX2
4451 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4452 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4454 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4455 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4457 } else if (VT.is128BitVector()) {
4458 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4460 llvm_unreachable("Unexpected vector type");
4462 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4465 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4466 /// that point to V2 points to its first element.
4467 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4468 for (unsigned i = 0; i != NumElems; ++i) {
4469 if (Mask[i] > (int)NumElems) {
4475 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4476 /// operation of specified width.
4477 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4479 unsigned NumElems = VT.getVectorNumElements();
4480 SmallVector<int, 8> Mask;
4481 Mask.push_back(NumElems);
4482 for (unsigned i = 1; i != NumElems; ++i)
4484 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4487 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4488 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4490 unsigned NumElems = VT.getVectorNumElements();
4491 SmallVector<int, 8> Mask;
4492 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4494 Mask.push_back(i + NumElems);
4496 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4499 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4500 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4502 unsigned NumElems = VT.getVectorNumElements();
4503 SmallVector<int, 8> Mask;
4504 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4505 Mask.push_back(i + Half);
4506 Mask.push_back(i + NumElems + Half);
4508 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4511 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4512 // a generic shuffle instruction because the target has no such instructions.
4513 // Generate shuffles which repeat i16 and i8 several times until they can be
4514 // represented by v4f32 and then be manipulated by target suported shuffles.
4515 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4516 EVT VT = V.getValueType();
4517 int NumElems = VT.getVectorNumElements();
4518 DebugLoc dl = V.getDebugLoc();
4520 while (NumElems > 4) {
4521 if (EltNo < NumElems/2) {
4522 V = getUnpackl(DAG, dl, VT, V, V);
4524 V = getUnpackh(DAG, dl, VT, V, V);
4525 EltNo -= NumElems/2;
4532 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4533 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4534 EVT VT = V.getValueType();
4535 DebugLoc dl = V.getDebugLoc();
4537 if (VT.is128BitVector()) {
4538 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4539 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4540 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4542 } else if (VT.is256BitVector()) {
4543 // To use VPERMILPS to splat scalars, the second half of indicies must
4544 // refer to the higher part, which is a duplication of the lower one,
4545 // because VPERMILPS can only handle in-lane permutations.
4546 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4547 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4549 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4550 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4553 llvm_unreachable("Vector size not supported");
4555 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4558 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4559 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4560 EVT SrcVT = SV->getValueType(0);
4561 SDValue V1 = SV->getOperand(0);
4562 DebugLoc dl = SV->getDebugLoc();
4564 int EltNo = SV->getSplatIndex();
4565 int NumElems = SrcVT.getVectorNumElements();
4566 bool Is256BitVec = SrcVT.is256BitVector();
4568 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4569 "Unknown how to promote splat for type");
4571 // Extract the 128-bit part containing the splat element and update
4572 // the splat element index when it refers to the higher register.
4574 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4575 if (EltNo >= NumElems/2)
4576 EltNo -= NumElems/2;
4579 // All i16 and i8 vector types can't be used directly by a generic shuffle
4580 // instruction because the target has no such instruction. Generate shuffles
4581 // which repeat i16 and i8 several times until they fit in i32, and then can
4582 // be manipulated by target suported shuffles.
4583 EVT EltVT = SrcVT.getVectorElementType();
4584 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4585 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4587 // Recreate the 256-bit vector and place the same 128-bit vector
4588 // into the low and high part. This is necessary because we want
4589 // to use VPERM* to shuffle the vectors
4591 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4594 return getLegalSplat(DAG, V1, EltNo);
4597 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4598 /// vector of zero or undef vector. This produces a shuffle where the low
4599 /// element of V2 is swizzled into the zero/undef vector, landing at element
4600 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4601 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4603 const X86Subtarget *Subtarget,
4604 SelectionDAG &DAG) {
4605 EVT VT = V2.getValueType();
4607 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4608 unsigned NumElems = VT.getVectorNumElements();
4609 SmallVector<int, 16> MaskVec;
4610 for (unsigned i = 0; i != NumElems; ++i)
4611 // If this is the insertion idx, put the low elt of V2 here.
4612 MaskVec.push_back(i == Idx ? NumElems : i);
4613 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4616 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4617 /// target specific opcode. Returns true if the Mask could be calculated.
4618 /// Sets IsUnary to true if only uses one source.
4619 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4620 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4621 unsigned NumElems = VT.getVectorNumElements();
4625 switch(N->getOpcode()) {
4627 ImmN = N->getOperand(N->getNumOperands()-1);
4628 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4630 case X86ISD::UNPCKH:
4631 DecodeUNPCKHMask(VT, Mask);
4633 case X86ISD::UNPCKL:
4634 DecodeUNPCKLMask(VT, Mask);
4636 case X86ISD::MOVHLPS:
4637 DecodeMOVHLPSMask(NumElems, Mask);
4639 case X86ISD::MOVLHPS:
4640 DecodeMOVLHPSMask(NumElems, Mask);
4642 case X86ISD::PALIGNR:
4643 ImmN = N->getOperand(N->getNumOperands()-1);
4644 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4646 case X86ISD::PSHUFD:
4647 case X86ISD::VPERMILP:
4648 ImmN = N->getOperand(N->getNumOperands()-1);
4649 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4652 case X86ISD::PSHUFHW:
4653 ImmN = N->getOperand(N->getNumOperands()-1);
4654 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4657 case X86ISD::PSHUFLW:
4658 ImmN = N->getOperand(N->getNumOperands()-1);
4659 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4662 case X86ISD::VPERMI:
4663 ImmN = N->getOperand(N->getNumOperands()-1);
4664 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4668 case X86ISD::MOVSD: {
4669 // The index 0 always comes from the first element of the second source,
4670 // this is why MOVSS and MOVSD are used in the first place. The other
4671 // elements come from the other positions of the first source vector
4672 Mask.push_back(NumElems);
4673 for (unsigned i = 1; i != NumElems; ++i) {
4678 case X86ISD::VPERM2X128:
4679 ImmN = N->getOperand(N->getNumOperands()-1);
4680 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4681 if (Mask.empty()) return false;
4683 case X86ISD::MOVDDUP:
4684 case X86ISD::MOVLHPD:
4685 case X86ISD::MOVLPD:
4686 case X86ISD::MOVLPS:
4687 case X86ISD::MOVSHDUP:
4688 case X86ISD::MOVSLDUP:
4689 // Not yet implemented
4691 default: llvm_unreachable("unknown target shuffle node");
4697 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4698 /// element of the result of the vector shuffle.
4699 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4702 return SDValue(); // Limit search depth.
4704 SDValue V = SDValue(N, 0);
4705 EVT VT = V.getValueType();
4706 unsigned Opcode = V.getOpcode();
4708 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4709 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4710 int Elt = SV->getMaskElt(Index);
4713 return DAG.getUNDEF(VT.getVectorElementType());
4715 unsigned NumElems = VT.getVectorNumElements();
4716 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4717 : SV->getOperand(1);
4718 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4721 // Recurse into target specific vector shuffles to find scalars.
4722 if (isTargetShuffle(Opcode)) {
4723 MVT ShufVT = V.getValueType().getSimpleVT();
4724 unsigned NumElems = ShufVT.getVectorNumElements();
4725 SmallVector<int, 16> ShuffleMask;
4728 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4731 int Elt = ShuffleMask[Index];
4733 return DAG.getUNDEF(ShufVT.getVectorElementType());
4735 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4737 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4741 // Actual nodes that may contain scalar elements
4742 if (Opcode == ISD::BITCAST) {
4743 V = V.getOperand(0);
4744 EVT SrcVT = V.getValueType();
4745 unsigned NumElems = VT.getVectorNumElements();
4747 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4751 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4752 return (Index == 0) ? V.getOperand(0)
4753 : DAG.getUNDEF(VT.getVectorElementType());
4755 if (V.getOpcode() == ISD::BUILD_VECTOR)
4756 return V.getOperand(Index);
4761 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4762 /// shuffle operation which come from a consecutively from a zero. The
4763 /// search can start in two different directions, from left or right.
4765 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4766 bool ZerosFromLeft, SelectionDAG &DAG) {
4768 for (i = 0; i != NumElems; ++i) {
4769 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4770 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4771 if (!(Elt.getNode() &&
4772 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4779 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4780 /// correspond consecutively to elements from one of the vector operands,
4781 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4783 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4784 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4785 unsigned NumElems, unsigned &OpNum) {
4786 bool SeenV1 = false;
4787 bool SeenV2 = false;
4789 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4790 int Idx = SVOp->getMaskElt(i);
4791 // Ignore undef indicies
4795 if (Idx < (int)NumElems)
4800 // Only accept consecutive elements from the same vector
4801 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4805 OpNum = SeenV1 ? 0 : 1;
4809 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4810 /// logical left shift of a vector.
4811 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4812 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4813 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4814 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4815 false /* check zeros from right */, DAG);
4821 // Considering the elements in the mask that are not consecutive zeros,
4822 // check if they consecutively come from only one of the source vectors.
4824 // V1 = {X, A, B, C} 0
4826 // vector_shuffle V1, V2 <1, 2, 3, X>
4828 if (!isShuffleMaskConsecutive(SVOp,
4829 0, // Mask Start Index
4830 NumElems-NumZeros, // Mask End Index(exclusive)
4831 NumZeros, // Where to start looking in the src vector
4832 NumElems, // Number of elements in vector
4833 OpSrc)) // Which source operand ?
4838 ShVal = SVOp->getOperand(OpSrc);
4842 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4843 /// logical left shift of a vector.
4844 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4845 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4846 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4847 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4848 true /* check zeros from left */, DAG);
4854 // Considering the elements in the mask that are not consecutive zeros,
4855 // check if they consecutively come from only one of the source vectors.
4857 // 0 { A, B, X, X } = V2
4859 // vector_shuffle V1, V2 <X, X, 4, 5>
4861 if (!isShuffleMaskConsecutive(SVOp,
4862 NumZeros, // Mask Start Index
4863 NumElems, // Mask End Index(exclusive)
4864 0, // Where to start looking in the src vector
4865 NumElems, // Number of elements in vector
4866 OpSrc)) // Which source operand ?
4871 ShVal = SVOp->getOperand(OpSrc);
4875 /// isVectorShift - Returns true if the shuffle can be implemented as a
4876 /// logical left or right shift of a vector.
4877 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4878 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4879 // Although the logic below support any bitwidth size, there are no
4880 // shift instructions which handle more than 128-bit vectors.
4881 if (!SVOp->getValueType(0).is128BitVector())
4884 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4885 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4891 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4893 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4894 unsigned NumNonZero, unsigned NumZero,
4896 const X86Subtarget* Subtarget,
4897 const TargetLowering &TLI) {
4901 DebugLoc dl = Op.getDebugLoc();
4904 for (unsigned i = 0; i < 16; ++i) {
4905 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4906 if (ThisIsNonZero && First) {
4908 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4910 V = DAG.getUNDEF(MVT::v8i16);
4915 SDValue ThisElt(0, 0), LastElt(0, 0);
4916 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4917 if (LastIsNonZero) {
4918 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4919 MVT::i16, Op.getOperand(i-1));
4921 if (ThisIsNonZero) {
4922 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4923 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4924 ThisElt, DAG.getConstant(8, MVT::i8));
4926 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4930 if (ThisElt.getNode())
4931 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4932 DAG.getIntPtrConstant(i/2));
4936 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4939 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4941 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4942 unsigned NumNonZero, unsigned NumZero,
4944 const X86Subtarget* Subtarget,
4945 const TargetLowering &TLI) {
4949 DebugLoc dl = Op.getDebugLoc();
4952 for (unsigned i = 0; i < 8; ++i) {
4953 bool isNonZero = (NonZeros & (1 << i)) != 0;
4957 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4959 V = DAG.getUNDEF(MVT::v8i16);
4962 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4963 MVT::v8i16, V, Op.getOperand(i),
4964 DAG.getIntPtrConstant(i));
4971 /// getVShift - Return a vector logical shift node.
4973 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4974 unsigned NumBits, SelectionDAG &DAG,
4975 const TargetLowering &TLI, DebugLoc dl) {
4976 assert(VT.is128BitVector() && "Unknown type for VShift");
4977 EVT ShVT = MVT::v2i64;
4978 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4979 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4980 return DAG.getNode(ISD::BITCAST, dl, VT,
4981 DAG.getNode(Opc, dl, ShVT, SrcOp,
4982 DAG.getConstant(NumBits,
4983 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4987 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4988 SelectionDAG &DAG) const {
4990 // Check if the scalar load can be widened into a vector load. And if
4991 // the address is "base + cst" see if the cst can be "absorbed" into
4992 // the shuffle mask.
4993 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4994 SDValue Ptr = LD->getBasePtr();
4995 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4997 EVT PVT = LD->getValueType(0);
4998 if (PVT != MVT::i32 && PVT != MVT::f32)
5003 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5004 FI = FINode->getIndex();
5006 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5007 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5008 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5009 Offset = Ptr.getConstantOperandVal(1);
5010 Ptr = Ptr.getOperand(0);
5015 // FIXME: 256-bit vector instructions don't require a strict alignment,
5016 // improve this code to support it better.
5017 unsigned RequiredAlign = VT.getSizeInBits()/8;
5018 SDValue Chain = LD->getChain();
5019 // Make sure the stack object alignment is at least 16 or 32.
5020 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5021 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5022 if (MFI->isFixedObjectIndex(FI)) {
5023 // Can't change the alignment. FIXME: It's possible to compute
5024 // the exact stack offset and reference FI + adjust offset instead.
5025 // If someone *really* cares about this. That's the way to implement it.
5028 MFI->setObjectAlignment(FI, RequiredAlign);
5032 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5033 // Ptr + (Offset & ~15).
5036 if ((Offset % RequiredAlign) & 3)
5038 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5040 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5041 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5043 int EltNo = (Offset - StartOffset) >> 2;
5044 unsigned NumElems = VT.getVectorNumElements();
5046 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5047 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5048 LD->getPointerInfo().getWithOffset(StartOffset),
5049 false, false, false, 0);
5051 SmallVector<int, 8> Mask;
5052 for (unsigned i = 0; i != NumElems; ++i)
5053 Mask.push_back(EltNo);
5055 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5061 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5062 /// vector of type 'VT', see if the elements can be replaced by a single large
5063 /// load which has the same value as a build_vector whose operands are 'elts'.
5065 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5067 /// FIXME: we'd also like to handle the case where the last elements are zero
5068 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5069 /// There's even a handy isZeroNode for that purpose.
5070 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5071 DebugLoc &DL, SelectionDAG &DAG) {
5072 EVT EltVT = VT.getVectorElementType();
5073 unsigned NumElems = Elts.size();
5075 LoadSDNode *LDBase = NULL;
5076 unsigned LastLoadedElt = -1U;
5078 // For each element in the initializer, see if we've found a load or an undef.
5079 // If we don't find an initial load element, or later load elements are
5080 // non-consecutive, bail out.
5081 for (unsigned i = 0; i < NumElems; ++i) {
5082 SDValue Elt = Elts[i];
5084 if (!Elt.getNode() ||
5085 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5088 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5090 LDBase = cast<LoadSDNode>(Elt.getNode());
5094 if (Elt.getOpcode() == ISD::UNDEF)
5097 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5098 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5103 // If we have found an entire vector of loads and undefs, then return a large
5104 // load of the entire vector width starting at the base pointer. If we found
5105 // consecutive loads for the low half, generate a vzext_load node.
5106 if (LastLoadedElt == NumElems - 1) {
5107 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5108 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5109 LDBase->getPointerInfo(),
5110 LDBase->isVolatile(), LDBase->isNonTemporal(),
5111 LDBase->isInvariant(), 0);
5112 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5113 LDBase->getPointerInfo(),
5114 LDBase->isVolatile(), LDBase->isNonTemporal(),
5115 LDBase->isInvariant(), LDBase->getAlignment());
5117 if (NumElems == 4 && LastLoadedElt == 1 &&
5118 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5119 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5120 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5122 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5123 LDBase->getPointerInfo(),
5124 LDBase->getAlignment(),
5125 false/*isVolatile*/, true/*ReadMem*/,
5128 // Make sure the newly-created LOAD is in the same position as LDBase in
5129 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5130 // update uses of LDBase's output chain to use the TokenFactor.
5131 if (LDBase->hasAnyUseOfValue(1)) {
5132 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5133 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5134 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5135 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5136 SDValue(ResNode.getNode(), 1));
5139 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5144 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5145 /// to generate a splat value for the following cases:
5146 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5147 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5148 /// a scalar load, or a constant.
5149 /// The VBROADCAST node is returned when a pattern is found,
5150 /// or SDValue() otherwise.
5152 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5153 if (!Subtarget->hasFp256())
5156 MVT VT = Op.getValueType().getSimpleVT();
5157 DebugLoc dl = Op.getDebugLoc();
5159 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5160 "Unsupported vector type for broadcast.");
5165 switch (Op.getOpcode()) {
5167 // Unknown pattern found.
5170 case ISD::BUILD_VECTOR: {
5171 // The BUILD_VECTOR node must be a splat.
5172 if (!isSplatVector(Op.getNode()))
5175 Ld = Op.getOperand(0);
5176 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5177 Ld.getOpcode() == ISD::ConstantFP);
5179 // The suspected load node has several users. Make sure that all
5180 // of its users are from the BUILD_VECTOR node.
5181 // Constants may have multiple users.
5182 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5187 case ISD::VECTOR_SHUFFLE: {
5188 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5190 // Shuffles must have a splat mask where the first element is
5192 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5195 SDValue Sc = Op.getOperand(0);
5196 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5197 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5199 if (!Subtarget->hasInt256())
5202 // Use the register form of the broadcast instruction available on AVX2.
5203 if (VT.is256BitVector())
5204 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5205 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5208 Ld = Sc.getOperand(0);
5209 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5210 Ld.getOpcode() == ISD::ConstantFP);
5212 // The scalar_to_vector node and the suspected
5213 // load node must have exactly one user.
5214 // Constants may have multiple users.
5215 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5221 bool Is256 = VT.is256BitVector();
5223 // Handle the broadcasting a single constant scalar from the constant pool
5224 // into a vector. On Sandybridge it is still better to load a constant vector
5225 // from the constant pool and not to broadcast it from a scalar.
5226 if (ConstSplatVal && Subtarget->hasInt256()) {
5227 EVT CVT = Ld.getValueType();
5228 assert(!CVT.isVector() && "Must not broadcast a vector type");
5229 unsigned ScalarSize = CVT.getSizeInBits();
5231 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5232 const Constant *C = 0;
5233 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5234 C = CI->getConstantIntValue();
5235 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5236 C = CF->getConstantFPValue();
5238 assert(C && "Invalid constant type");
5240 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5241 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5242 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5243 MachinePointerInfo::getConstantPool(),
5244 false, false, false, Alignment);
5246 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5250 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5251 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5253 // Handle AVX2 in-register broadcasts.
5254 if (!IsLoad && Subtarget->hasInt256() &&
5255 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5256 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5258 // The scalar source must be a normal load.
5262 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5263 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5265 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5266 // double since there is no vbroadcastsd xmm
5267 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5268 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5269 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5272 // Unsupported broadcast.
5277 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5278 EVT VT = Op.getValueType();
5280 // Skip if insert_vec_elt is not supported.
5281 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5284 DebugLoc DL = Op.getDebugLoc();
5285 unsigned NumElems = Op.getNumOperands();
5289 SmallVector<unsigned, 4> InsertIndices;
5290 SmallVector<int, 8> Mask(NumElems, -1);
5292 for (unsigned i = 0; i != NumElems; ++i) {
5293 unsigned Opc = Op.getOperand(i).getOpcode();
5295 if (Opc == ISD::UNDEF)
5298 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5299 // Quit if more than 1 elements need inserting.
5300 if (InsertIndices.size() > 1)
5303 InsertIndices.push_back(i);
5307 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5308 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5310 // Quit if extracted from vector of different type.
5311 if (ExtractedFromVec.getValueType() != VT)
5314 // Quit if non-constant index.
5315 if (!isa<ConstantSDNode>(ExtIdx))
5318 if (VecIn1.getNode() == 0)
5319 VecIn1 = ExtractedFromVec;
5320 else if (VecIn1 != ExtractedFromVec) {
5321 if (VecIn2.getNode() == 0)
5322 VecIn2 = ExtractedFromVec;
5323 else if (VecIn2 != ExtractedFromVec)
5324 // Quit if more than 2 vectors to shuffle
5328 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5330 if (ExtractedFromVec == VecIn1)
5332 else if (ExtractedFromVec == VecIn2)
5333 Mask[i] = Idx + NumElems;
5336 if (VecIn1.getNode() == 0)
5339 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5340 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5341 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5342 unsigned Idx = InsertIndices[i];
5343 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5344 DAG.getIntPtrConstant(Idx));
5351 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5352 DebugLoc dl = Op.getDebugLoc();
5354 MVT VT = Op.getValueType().getSimpleVT();
5355 MVT ExtVT = VT.getVectorElementType();
5356 unsigned NumElems = Op.getNumOperands();
5358 // Vectors containing all zeros can be matched by pxor and xorps later
5359 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5360 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5361 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5362 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5365 return getZeroVector(VT, Subtarget, DAG, dl);
5368 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5369 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5370 // vpcmpeqd on 256-bit vectors.
5371 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5372 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5375 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5378 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5379 if (Broadcast.getNode())
5382 unsigned EVTBits = ExtVT.getSizeInBits();
5384 unsigned NumZero = 0;
5385 unsigned NumNonZero = 0;
5386 unsigned NonZeros = 0;
5387 bool IsAllConstants = true;
5388 SmallSet<SDValue, 8> Values;
5389 for (unsigned i = 0; i < NumElems; ++i) {
5390 SDValue Elt = Op.getOperand(i);
5391 if (Elt.getOpcode() == ISD::UNDEF)
5394 if (Elt.getOpcode() != ISD::Constant &&
5395 Elt.getOpcode() != ISD::ConstantFP)
5396 IsAllConstants = false;
5397 if (X86::isZeroNode(Elt))
5400 NonZeros |= (1 << i);
5405 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5406 if (NumNonZero == 0)
5407 return DAG.getUNDEF(VT);
5409 // Special case for single non-zero, non-undef, element.
5410 if (NumNonZero == 1) {
5411 unsigned Idx = CountTrailingZeros_32(NonZeros);
5412 SDValue Item = Op.getOperand(Idx);
5414 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5415 // the value are obviously zero, truncate the value to i32 and do the
5416 // insertion that way. Only do this if the value is non-constant or if the
5417 // value is a constant being inserted into element 0. It is cheaper to do
5418 // a constant pool load than it is to do a movd + shuffle.
5419 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5420 (!IsAllConstants || Idx == 0)) {
5421 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5423 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5424 EVT VecVT = MVT::v4i32;
5425 unsigned VecElts = 4;
5427 // Truncate the value (which may itself be a constant) to i32, and
5428 // convert it to a vector with movd (S2V+shuffle to zero extend).
5429 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5430 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5431 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5433 // Now we have our 32-bit value zero extended in the low element of
5434 // a vector. If Idx != 0, swizzle it into place.
5436 SmallVector<int, 4> Mask;
5437 Mask.push_back(Idx);
5438 for (unsigned i = 1; i != VecElts; ++i)
5440 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5443 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5447 // If we have a constant or non-constant insertion into the low element of
5448 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5449 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5450 // depending on what the source datatype is.
5453 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5455 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5456 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5457 if (VT.is256BitVector()) {
5458 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5459 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5460 Item, DAG.getIntPtrConstant(0));
5462 assert(VT.is128BitVector() && "Expected an SSE value type!");
5463 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5464 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5465 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5468 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5469 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5470 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5471 if (VT.is256BitVector()) {
5472 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5473 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5475 assert(VT.is128BitVector() && "Expected an SSE value type!");
5476 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5478 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5482 // Is it a vector logical left shift?
5483 if (NumElems == 2 && Idx == 1 &&
5484 X86::isZeroNode(Op.getOperand(0)) &&
5485 !X86::isZeroNode(Op.getOperand(1))) {
5486 unsigned NumBits = VT.getSizeInBits();
5487 return getVShift(true, VT,
5488 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5489 VT, Op.getOperand(1)),
5490 NumBits/2, DAG, *this, dl);
5493 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5496 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5497 // is a non-constant being inserted into an element other than the low one,
5498 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5499 // movd/movss) to move this into the low element, then shuffle it into
5501 if (EVTBits == 32) {
5502 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5504 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5505 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5506 SmallVector<int, 8> MaskVec;
5507 for (unsigned i = 0; i != NumElems; ++i)
5508 MaskVec.push_back(i == Idx ? 0 : 1);
5509 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5513 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5514 if (Values.size() == 1) {
5515 if (EVTBits == 32) {
5516 // Instead of a shuffle like this:
5517 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5518 // Check if it's possible to issue this instead.
5519 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5520 unsigned Idx = CountTrailingZeros_32(NonZeros);
5521 SDValue Item = Op.getOperand(Idx);
5522 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5523 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5528 // A vector full of immediates; various special cases are already
5529 // handled, so this is best done with a single constant-pool load.
5533 // For AVX-length vectors, build the individual 128-bit pieces and use
5534 // shuffles to put them in place.
5535 if (VT.is256BitVector()) {
5536 SmallVector<SDValue, 32> V;
5537 for (unsigned i = 0; i != NumElems; ++i)
5538 V.push_back(Op.getOperand(i));
5540 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5542 // Build both the lower and upper subvector.
5543 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5544 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5547 // Recreate the wider vector with the lower and upper part.
5548 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5551 // Let legalizer expand 2-wide build_vectors.
5552 if (EVTBits == 64) {
5553 if (NumNonZero == 1) {
5554 // One half is zero or undef.
5555 unsigned Idx = CountTrailingZeros_32(NonZeros);
5556 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5557 Op.getOperand(Idx));
5558 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5563 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5564 if (EVTBits == 8 && NumElems == 16) {
5565 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5567 if (V.getNode()) return V;
5570 if (EVTBits == 16 && NumElems == 8) {
5571 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5573 if (V.getNode()) return V;
5576 // If element VT is == 32 bits, turn it into a number of shuffles.
5577 SmallVector<SDValue, 8> V(NumElems);
5578 if (NumElems == 4 && NumZero > 0) {
5579 for (unsigned i = 0; i < 4; ++i) {
5580 bool isZero = !(NonZeros & (1 << i));
5582 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5584 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5587 for (unsigned i = 0; i < 2; ++i) {
5588 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5591 V[i] = V[i*2]; // Must be a zero vector.
5594 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5597 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5600 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5605 bool Reverse1 = (NonZeros & 0x3) == 2;
5606 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5610 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5611 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5613 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5616 if (Values.size() > 1 && VT.is128BitVector()) {
5617 // Check for a build vector of consecutive loads.
5618 for (unsigned i = 0; i < NumElems; ++i)
5619 V[i] = Op.getOperand(i);
5621 // Check for elements which are consecutive loads.
5622 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5626 // Check for a build vector from mostly shuffle plus few inserting.
5627 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5631 // For SSE 4.1, use insertps to put the high elements into the low element.
5632 if (getSubtarget()->hasSSE41()) {
5634 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5635 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5637 Result = DAG.getUNDEF(VT);
5639 for (unsigned i = 1; i < NumElems; ++i) {
5640 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5641 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5642 Op.getOperand(i), DAG.getIntPtrConstant(i));
5647 // Otherwise, expand into a number of unpckl*, start by extending each of
5648 // our (non-undef) elements to the full vector width with the element in the
5649 // bottom slot of the vector (which generates no code for SSE).
5650 for (unsigned i = 0; i < NumElems; ++i) {
5651 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5652 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5654 V[i] = DAG.getUNDEF(VT);
5657 // Next, we iteratively mix elements, e.g. for v4f32:
5658 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5659 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5660 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5661 unsigned EltStride = NumElems >> 1;
5662 while (EltStride != 0) {
5663 for (unsigned i = 0; i < EltStride; ++i) {
5664 // If V[i+EltStride] is undef and this is the first round of mixing,
5665 // then it is safe to just drop this shuffle: V[i] is already in the
5666 // right place, the one element (since it's the first round) being
5667 // inserted as undef can be dropped. This isn't safe for successive
5668 // rounds because they will permute elements within both vectors.
5669 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5670 EltStride == NumElems/2)
5673 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5682 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5683 // to create 256-bit vectors from two other 128-bit ones.
5684 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5685 DebugLoc dl = Op.getDebugLoc();
5686 MVT ResVT = Op.getValueType().getSimpleVT();
5688 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5690 SDValue V1 = Op.getOperand(0);
5691 SDValue V2 = Op.getOperand(1);
5692 unsigned NumElems = ResVT.getVectorNumElements();
5694 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5697 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5698 assert(Op.getNumOperands() == 2);
5700 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5701 // from two other 128-bit ones.
5702 return LowerAVXCONCAT_VECTORS(Op, DAG);
5705 // Try to lower a shuffle node into a simple blend instruction.
5707 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5708 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5709 SDValue V1 = SVOp->getOperand(0);
5710 SDValue V2 = SVOp->getOperand(1);
5711 DebugLoc dl = SVOp->getDebugLoc();
5712 MVT VT = SVOp->getValueType(0).getSimpleVT();
5713 MVT EltVT = VT.getVectorElementType();
5714 unsigned NumElems = VT.getVectorNumElements();
5716 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5718 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5721 // Check the mask for BLEND and build the value.
5722 unsigned MaskValue = 0;
5723 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5724 unsigned NumLanes = (NumElems-1)/8 + 1;
5725 unsigned NumElemsInLane = NumElems / NumLanes;
5727 // Blend for v16i16 should be symetric for the both lanes.
5728 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5730 int SndLaneEltIdx = (NumLanes == 2) ?
5731 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5732 int EltIdx = SVOp->getMaskElt(i);
5734 if ((EltIdx < 0 || EltIdx == (int)i) &&
5735 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5738 if (((unsigned)EltIdx == (i + NumElems)) &&
5739 (SndLaneEltIdx < 0 ||
5740 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5741 MaskValue |= (1<<i);
5746 // Convert i32 vectors to floating point if it is not AVX2.
5747 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5749 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5750 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5752 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5753 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5756 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5757 DAG.getConstant(MaskValue, MVT::i32));
5758 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5761 // v8i16 shuffles - Prefer shuffles in the following order:
5762 // 1. [all] pshuflw, pshufhw, optional move
5763 // 2. [ssse3] 1 x pshufb
5764 // 3. [ssse3] 2 x pshufb + 1 x por
5765 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5767 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5768 SelectionDAG &DAG) {
5769 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5770 SDValue V1 = SVOp->getOperand(0);
5771 SDValue V2 = SVOp->getOperand(1);
5772 DebugLoc dl = SVOp->getDebugLoc();
5773 SmallVector<int, 8> MaskVals;
5775 // Determine if more than 1 of the words in each of the low and high quadwords
5776 // of the result come from the same quadword of one of the two inputs. Undef
5777 // mask values count as coming from any quadword, for better codegen.
5778 unsigned LoQuad[] = { 0, 0, 0, 0 };
5779 unsigned HiQuad[] = { 0, 0, 0, 0 };
5780 std::bitset<4> InputQuads;
5781 for (unsigned i = 0; i < 8; ++i) {
5782 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5783 int EltIdx = SVOp->getMaskElt(i);
5784 MaskVals.push_back(EltIdx);
5793 InputQuads.set(EltIdx / 4);
5796 int BestLoQuad = -1;
5797 unsigned MaxQuad = 1;
5798 for (unsigned i = 0; i < 4; ++i) {
5799 if (LoQuad[i] > MaxQuad) {
5801 MaxQuad = LoQuad[i];
5805 int BestHiQuad = -1;
5807 for (unsigned i = 0; i < 4; ++i) {
5808 if (HiQuad[i] > MaxQuad) {
5810 MaxQuad = HiQuad[i];
5814 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5815 // of the two input vectors, shuffle them into one input vector so only a
5816 // single pshufb instruction is necessary. If There are more than 2 input
5817 // quads, disable the next transformation since it does not help SSSE3.
5818 bool V1Used = InputQuads[0] || InputQuads[1];
5819 bool V2Used = InputQuads[2] || InputQuads[3];
5820 if (Subtarget->hasSSSE3()) {
5821 if (InputQuads.count() == 2 && V1Used && V2Used) {
5822 BestLoQuad = InputQuads[0] ? 0 : 1;
5823 BestHiQuad = InputQuads[2] ? 2 : 3;
5825 if (InputQuads.count() > 2) {
5831 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5832 // the shuffle mask. If a quad is scored as -1, that means that it contains
5833 // words from all 4 input quadwords.
5835 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5837 BestLoQuad < 0 ? 0 : BestLoQuad,
5838 BestHiQuad < 0 ? 1 : BestHiQuad
5840 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5841 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5842 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5843 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5845 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5846 // source words for the shuffle, to aid later transformations.
5847 bool AllWordsInNewV = true;
5848 bool InOrder[2] = { true, true };
5849 for (unsigned i = 0; i != 8; ++i) {
5850 int idx = MaskVals[i];
5852 InOrder[i/4] = false;
5853 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5855 AllWordsInNewV = false;
5859 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5860 if (AllWordsInNewV) {
5861 for (int i = 0; i != 8; ++i) {
5862 int idx = MaskVals[i];
5865 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5866 if ((idx != i) && idx < 4)
5868 if ((idx != i) && idx > 3)
5877 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5878 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5879 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5880 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5881 unsigned TargetMask = 0;
5882 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5883 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5884 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5885 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5886 getShufflePSHUFLWImmediate(SVOp);
5887 V1 = NewV.getOperand(0);
5888 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5892 // Promote splats to a larger type which usually leads to more efficient code.
5893 // FIXME: Is this true if pshufb is available?
5894 if (SVOp->isSplat())
5895 return PromoteSplat(SVOp, DAG);
5897 // If we have SSSE3, and all words of the result are from 1 input vector,
5898 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5899 // is present, fall back to case 4.
5900 if (Subtarget->hasSSSE3()) {
5901 SmallVector<SDValue,16> pshufbMask;
5903 // If we have elements from both input vectors, set the high bit of the
5904 // shuffle mask element to zero out elements that come from V2 in the V1
5905 // mask, and elements that come from V1 in the V2 mask, so that the two
5906 // results can be OR'd together.
5907 bool TwoInputs = V1Used && V2Used;
5908 for (unsigned i = 0; i != 8; ++i) {
5909 int EltIdx = MaskVals[i] * 2;
5910 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5911 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5912 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5913 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5915 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5916 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5917 DAG.getNode(ISD::BUILD_VECTOR, dl,
5918 MVT::v16i8, &pshufbMask[0], 16));
5920 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5922 // Calculate the shuffle mask for the second input, shuffle it, and
5923 // OR it with the first shuffled input.
5925 for (unsigned i = 0; i != 8; ++i) {
5926 int EltIdx = MaskVals[i] * 2;
5927 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5928 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5929 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5930 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5932 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5933 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5934 DAG.getNode(ISD::BUILD_VECTOR, dl,
5935 MVT::v16i8, &pshufbMask[0], 16));
5936 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5937 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5940 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5941 // and update MaskVals with new element order.
5942 std::bitset<8> InOrder;
5943 if (BestLoQuad >= 0) {
5944 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5945 for (int i = 0; i != 4; ++i) {
5946 int idx = MaskVals[i];
5949 } else if ((idx / 4) == BestLoQuad) {
5954 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5957 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5958 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5959 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5961 getShufflePSHUFLWImmediate(SVOp), DAG);
5965 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5966 // and update MaskVals with the new element order.
5967 if (BestHiQuad >= 0) {
5968 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5969 for (unsigned i = 4; i != 8; ++i) {
5970 int idx = MaskVals[i];
5973 } else if ((idx / 4) == BestHiQuad) {
5974 MaskV[i] = (idx & 3) + 4;
5978 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5981 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5982 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5983 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5985 getShufflePSHUFHWImmediate(SVOp), DAG);
5989 // In case BestHi & BestLo were both -1, which means each quadword has a word
5990 // from each of the four input quadwords, calculate the InOrder bitvector now
5991 // before falling through to the insert/extract cleanup.
5992 if (BestLoQuad == -1 && BestHiQuad == -1) {
5994 for (int i = 0; i != 8; ++i)
5995 if (MaskVals[i] < 0 || MaskVals[i] == i)
5999 // The other elements are put in the right place using pextrw and pinsrw.
6000 for (unsigned i = 0; i != 8; ++i) {
6003 int EltIdx = MaskVals[i];
6006 SDValue ExtOp = (EltIdx < 8) ?
6007 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6008 DAG.getIntPtrConstant(EltIdx)) :
6009 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6010 DAG.getIntPtrConstant(EltIdx - 8));
6011 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6012 DAG.getIntPtrConstant(i));
6017 // v16i8 shuffles - Prefer shuffles in the following order:
6018 // 1. [ssse3] 1 x pshufb
6019 // 2. [ssse3] 2 x pshufb + 1 x por
6020 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6022 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6024 const X86TargetLowering &TLI) {
6025 SDValue V1 = SVOp->getOperand(0);
6026 SDValue V2 = SVOp->getOperand(1);
6027 DebugLoc dl = SVOp->getDebugLoc();
6028 ArrayRef<int> MaskVals = SVOp->getMask();
6030 // Promote splats to a larger type which usually leads to more efficient code.
6031 // FIXME: Is this true if pshufb is available?
6032 if (SVOp->isSplat())
6033 return PromoteSplat(SVOp, DAG);
6035 // If we have SSSE3, case 1 is generated when all result bytes come from
6036 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6037 // present, fall back to case 3.
6039 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6040 if (TLI.getSubtarget()->hasSSSE3()) {
6041 SmallVector<SDValue,16> pshufbMask;
6043 // If all result elements are from one input vector, then only translate
6044 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6046 // Otherwise, we have elements from both input vectors, and must zero out
6047 // elements that come from V2 in the first mask, and V1 in the second mask
6048 // so that we can OR them together.
6049 for (unsigned i = 0; i != 16; ++i) {
6050 int EltIdx = MaskVals[i];
6051 if (EltIdx < 0 || EltIdx >= 16)
6053 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6055 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6056 DAG.getNode(ISD::BUILD_VECTOR, dl,
6057 MVT::v16i8, &pshufbMask[0], 16));
6059 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6060 // the 2nd operand if it's undefined or zero.
6061 if (V2.getOpcode() == ISD::UNDEF ||
6062 ISD::isBuildVectorAllZeros(V2.getNode()))
6065 // Calculate the shuffle mask for the second input, shuffle it, and
6066 // OR it with the first shuffled input.
6068 for (unsigned i = 0; i != 16; ++i) {
6069 int EltIdx = MaskVals[i];
6070 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6071 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6073 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6074 DAG.getNode(ISD::BUILD_VECTOR, dl,
6075 MVT::v16i8, &pshufbMask[0], 16));
6076 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6079 // No SSSE3 - Calculate in place words and then fix all out of place words
6080 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6081 // the 16 different words that comprise the two doublequadword input vectors.
6082 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6083 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6085 for (int i = 0; i != 8; ++i) {
6086 int Elt0 = MaskVals[i*2];
6087 int Elt1 = MaskVals[i*2+1];
6089 // This word of the result is all undef, skip it.
6090 if (Elt0 < 0 && Elt1 < 0)
6093 // This word of the result is already in the correct place, skip it.
6094 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6097 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6098 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6101 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6102 // using a single extract together, load it and store it.
6103 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6104 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6105 DAG.getIntPtrConstant(Elt1 / 2));
6106 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6107 DAG.getIntPtrConstant(i));
6111 // If Elt1 is defined, extract it from the appropriate source. If the
6112 // source byte is not also odd, shift the extracted word left 8 bits
6113 // otherwise clear the bottom 8 bits if we need to do an or.
6115 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6116 DAG.getIntPtrConstant(Elt1 / 2));
6117 if ((Elt1 & 1) == 0)
6118 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6120 TLI.getShiftAmountTy(InsElt.getValueType())));
6122 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6123 DAG.getConstant(0xFF00, MVT::i16));
6125 // If Elt0 is defined, extract it from the appropriate source. If the
6126 // source byte is not also even, shift the extracted word right 8 bits. If
6127 // Elt1 was also defined, OR the extracted values together before
6128 // inserting them in the result.
6130 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6131 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6132 if ((Elt0 & 1) != 0)
6133 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6135 TLI.getShiftAmountTy(InsElt0.getValueType())));
6137 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6138 DAG.getConstant(0x00FF, MVT::i16));
6139 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6142 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6143 DAG.getIntPtrConstant(i));
6145 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6148 // v32i8 shuffles - Translate to VPSHUFB if possible.
6150 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6151 const X86Subtarget *Subtarget,
6152 SelectionDAG &DAG) {
6153 MVT VT = SVOp->getValueType(0).getSimpleVT();
6154 SDValue V1 = SVOp->getOperand(0);
6155 SDValue V2 = SVOp->getOperand(1);
6156 DebugLoc dl = SVOp->getDebugLoc();
6157 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6159 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6160 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6161 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6163 // VPSHUFB may be generated if
6164 // (1) one of input vector is undefined or zeroinitializer.
6165 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6166 // And (2) the mask indexes don't cross the 128-bit lane.
6167 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6168 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6171 if (V1IsAllZero && !V2IsAllZero) {
6172 CommuteVectorShuffleMask(MaskVals, 32);
6175 SmallVector<SDValue, 32> pshufbMask;
6176 for (unsigned i = 0; i != 32; i++) {
6177 int EltIdx = MaskVals[i];
6178 if (EltIdx < 0 || EltIdx >= 32)
6181 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6182 // Cross lane is not allowed.
6186 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6188 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6189 DAG.getNode(ISD::BUILD_VECTOR, dl,
6190 MVT::v32i8, &pshufbMask[0], 32));
6193 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6194 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6195 /// done when every pair / quad of shuffle mask elements point to elements in
6196 /// the right sequence. e.g.
6197 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6199 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6200 SelectionDAG &DAG) {
6201 MVT VT = SVOp->getValueType(0).getSimpleVT();
6202 DebugLoc dl = SVOp->getDebugLoc();
6203 unsigned NumElems = VT.getVectorNumElements();
6206 switch (VT.SimpleTy) {
6207 default: llvm_unreachable("Unexpected!");
6208 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6209 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6210 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6211 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6212 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6213 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6216 SmallVector<int, 8> MaskVec;
6217 for (unsigned i = 0; i != NumElems; i += Scale) {
6219 for (unsigned j = 0; j != Scale; ++j) {
6220 int EltIdx = SVOp->getMaskElt(i+j);
6224 StartIdx = (EltIdx / Scale);
6225 if (EltIdx != (int)(StartIdx*Scale + j))
6228 MaskVec.push_back(StartIdx);
6231 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6232 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6233 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6236 /// getVZextMovL - Return a zero-extending vector move low node.
6238 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6239 SDValue SrcOp, SelectionDAG &DAG,
6240 const X86Subtarget *Subtarget, DebugLoc dl) {
6241 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6242 LoadSDNode *LD = NULL;
6243 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6244 LD = dyn_cast<LoadSDNode>(SrcOp);
6246 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6248 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6249 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6250 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6251 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6252 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6254 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6255 return DAG.getNode(ISD::BITCAST, dl, VT,
6256 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6257 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6265 return DAG.getNode(ISD::BITCAST, dl, VT,
6266 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6267 DAG.getNode(ISD::BITCAST, dl,
6271 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6272 /// which could not be matched by any known target speficic shuffle
6274 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6276 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6277 if (NewOp.getNode())
6280 MVT VT = SVOp->getValueType(0).getSimpleVT();
6282 unsigned NumElems = VT.getVectorNumElements();
6283 unsigned NumLaneElems = NumElems / 2;
6285 DebugLoc dl = SVOp->getDebugLoc();
6286 MVT EltVT = VT.getVectorElementType();
6287 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6290 SmallVector<int, 16> Mask;
6291 for (unsigned l = 0; l < 2; ++l) {
6292 // Build a shuffle mask for the output, discovering on the fly which
6293 // input vectors to use as shuffle operands (recorded in InputUsed).
6294 // If building a suitable shuffle vector proves too hard, then bail
6295 // out with UseBuildVector set.
6296 bool UseBuildVector = false;
6297 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6298 unsigned LaneStart = l * NumLaneElems;
6299 for (unsigned i = 0; i != NumLaneElems; ++i) {
6300 // The mask element. This indexes into the input.
6301 int Idx = SVOp->getMaskElt(i+LaneStart);
6303 // the mask element does not index into any input vector.
6308 // The input vector this mask element indexes into.
6309 int Input = Idx / NumLaneElems;
6311 // Turn the index into an offset from the start of the input vector.
6312 Idx -= Input * NumLaneElems;
6314 // Find or create a shuffle vector operand to hold this input.
6316 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6317 if (InputUsed[OpNo] == Input)
6318 // This input vector is already an operand.
6320 if (InputUsed[OpNo] < 0) {
6321 // Create a new operand for this input vector.
6322 InputUsed[OpNo] = Input;
6327 if (OpNo >= array_lengthof(InputUsed)) {
6328 // More than two input vectors used! Give up on trying to create a
6329 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6330 UseBuildVector = true;
6334 // Add the mask index for the new shuffle vector.
6335 Mask.push_back(Idx + OpNo * NumLaneElems);
6338 if (UseBuildVector) {
6339 SmallVector<SDValue, 16> SVOps;
6340 for (unsigned i = 0; i != NumLaneElems; ++i) {
6341 // The mask element. This indexes into the input.
6342 int Idx = SVOp->getMaskElt(i+LaneStart);
6344 SVOps.push_back(DAG.getUNDEF(EltVT));
6348 // The input vector this mask element indexes into.
6349 int Input = Idx / NumElems;
6351 // Turn the index into an offset from the start of the input vector.
6352 Idx -= Input * NumElems;
6354 // Extract the vector element by hand.
6355 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6356 SVOp->getOperand(Input),
6357 DAG.getIntPtrConstant(Idx)));
6360 // Construct the output using a BUILD_VECTOR.
6361 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6363 } else if (InputUsed[0] < 0) {
6364 // No input vectors were used! The result is undefined.
6365 Output[l] = DAG.getUNDEF(NVT);
6367 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6368 (InputUsed[0] % 2) * NumLaneElems,
6370 // If only one input was used, use an undefined vector for the other.
6371 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6372 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6373 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6374 // At least one input vector was used. Create a new shuffle vector.
6375 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6381 // Concatenate the result back
6382 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6385 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6386 /// 4 elements, and match them with several different shuffle types.
6388 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6389 SDValue V1 = SVOp->getOperand(0);
6390 SDValue V2 = SVOp->getOperand(1);
6391 DebugLoc dl = SVOp->getDebugLoc();
6392 MVT VT = SVOp->getValueType(0).getSimpleVT();
6394 assert(VT.is128BitVector() && "Unsupported vector size");
6396 std::pair<int, int> Locs[4];
6397 int Mask1[] = { -1, -1, -1, -1 };
6398 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6402 for (unsigned i = 0; i != 4; ++i) {
6403 int Idx = PermMask[i];
6405 Locs[i] = std::make_pair(-1, -1);
6407 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6409 Locs[i] = std::make_pair(0, NumLo);
6413 Locs[i] = std::make_pair(1, NumHi);
6415 Mask1[2+NumHi] = Idx;
6421 if (NumLo <= 2 && NumHi <= 2) {
6422 // If no more than two elements come from either vector. This can be
6423 // implemented with two shuffles. First shuffle gather the elements.
6424 // The second shuffle, which takes the first shuffle as both of its
6425 // vector operands, put the elements into the right order.
6426 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6428 int Mask2[] = { -1, -1, -1, -1 };
6430 for (unsigned i = 0; i != 4; ++i)
6431 if (Locs[i].first != -1) {
6432 unsigned Idx = (i < 2) ? 0 : 4;
6433 Idx += Locs[i].first * 2 + Locs[i].second;
6437 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6440 if (NumLo == 3 || NumHi == 3) {
6441 // Otherwise, we must have three elements from one vector, call it X, and
6442 // one element from the other, call it Y. First, use a shufps to build an
6443 // intermediate vector with the one element from Y and the element from X
6444 // that will be in the same half in the final destination (the indexes don't
6445 // matter). Then, use a shufps to build the final vector, taking the half
6446 // containing the element from Y from the intermediate, and the other half
6449 // Normalize it so the 3 elements come from V1.
6450 CommuteVectorShuffleMask(PermMask, 4);
6454 // Find the element from V2.
6456 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6457 int Val = PermMask[HiIndex];
6464 Mask1[0] = PermMask[HiIndex];
6466 Mask1[2] = PermMask[HiIndex^1];
6468 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6471 Mask1[0] = PermMask[0];
6472 Mask1[1] = PermMask[1];
6473 Mask1[2] = HiIndex & 1 ? 6 : 4;
6474 Mask1[3] = HiIndex & 1 ? 4 : 6;
6475 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6478 Mask1[0] = HiIndex & 1 ? 2 : 0;
6479 Mask1[1] = HiIndex & 1 ? 0 : 2;
6480 Mask1[2] = PermMask[2];
6481 Mask1[3] = PermMask[3];
6486 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6489 // Break it into (shuffle shuffle_hi, shuffle_lo).
6490 int LoMask[] = { -1, -1, -1, -1 };
6491 int HiMask[] = { -1, -1, -1, -1 };
6493 int *MaskPtr = LoMask;
6494 unsigned MaskIdx = 0;
6497 for (unsigned i = 0; i != 4; ++i) {
6504 int Idx = PermMask[i];
6506 Locs[i] = std::make_pair(-1, -1);
6507 } else if (Idx < 4) {
6508 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6509 MaskPtr[LoIdx] = Idx;
6512 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6513 MaskPtr[HiIdx] = Idx;
6518 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6519 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6520 int MaskOps[] = { -1, -1, -1, -1 };
6521 for (unsigned i = 0; i != 4; ++i)
6522 if (Locs[i].first != -1)
6523 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6524 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6527 static bool MayFoldVectorLoad(SDValue V) {
6528 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6529 V = V.getOperand(0);
6531 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6532 V = V.getOperand(0);
6533 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6534 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6535 // BUILD_VECTOR (load), undef
6536 V = V.getOperand(0);
6538 return MayFoldLoad(V);
6542 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6543 EVT VT = Op.getValueType();
6545 // Canonizalize to v2f64.
6546 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6547 return DAG.getNode(ISD::BITCAST, dl, VT,
6548 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6553 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6555 SDValue V1 = Op.getOperand(0);
6556 SDValue V2 = Op.getOperand(1);
6557 EVT VT = Op.getValueType();
6559 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6561 if (HasSSE2 && VT == MVT::v2f64)
6562 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6564 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6565 return DAG.getNode(ISD::BITCAST, dl, VT,
6566 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6567 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6568 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6572 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6573 SDValue V1 = Op.getOperand(0);
6574 SDValue V2 = Op.getOperand(1);
6575 EVT VT = Op.getValueType();
6577 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6578 "unsupported shuffle type");
6580 if (V2.getOpcode() == ISD::UNDEF)
6584 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6588 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6589 SDValue V1 = Op.getOperand(0);
6590 SDValue V2 = Op.getOperand(1);
6591 EVT VT = Op.getValueType();
6592 unsigned NumElems = VT.getVectorNumElements();
6594 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6595 // operand of these instructions is only memory, so check if there's a
6596 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6598 bool CanFoldLoad = false;
6600 // Trivial case, when V2 comes from a load.
6601 if (MayFoldVectorLoad(V2))
6604 // When V1 is a load, it can be folded later into a store in isel, example:
6605 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6607 // (MOVLPSmr addr:$src1, VR128:$src2)
6608 // So, recognize this potential and also use MOVLPS or MOVLPD
6609 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6612 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6614 if (HasSSE2 && NumElems == 2)
6615 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6618 // If we don't care about the second element, proceed to use movss.
6619 if (SVOp->getMaskElt(1) != -1)
6620 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6623 // movl and movlp will both match v2i64, but v2i64 is never matched by
6624 // movl earlier because we make it strict to avoid messing with the movlp load
6625 // folding logic (see the code above getMOVLP call). Match it here then,
6626 // this is horrible, but will stay like this until we move all shuffle
6627 // matching to x86 specific nodes. Note that for the 1st condition all
6628 // types are matched with movsd.
6630 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6631 // as to remove this logic from here, as much as possible
6632 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6633 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6634 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6637 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6639 // Invert the operand order and use SHUFPS to match it.
6640 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6641 getShuffleSHUFImmediate(SVOp), DAG);
6644 // Reduce a vector shuffle to zext.
6646 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6647 // PMOVZX is only available from SSE41.
6648 if (!Subtarget->hasSSE41())
6651 EVT VT = Op.getValueType();
6653 // Only AVX2 support 256-bit vector integer extending.
6654 if (!Subtarget->hasInt256() && VT.is256BitVector())
6657 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6658 DebugLoc DL = Op.getDebugLoc();
6659 SDValue V1 = Op.getOperand(0);
6660 SDValue V2 = Op.getOperand(1);
6661 unsigned NumElems = VT.getVectorNumElements();
6663 // Extending is an unary operation and the element type of the source vector
6664 // won't be equal to or larger than i64.
6665 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6666 VT.getVectorElementType() == MVT::i64)
6669 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6670 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6671 while ((1U << Shift) < NumElems) {
6672 if (SVOp->getMaskElt(1U << Shift) == 1)
6675 // The maximal ratio is 8, i.e. from i8 to i64.
6680 // Check the shuffle mask.
6681 unsigned Mask = (1U << Shift) - 1;
6682 for (unsigned i = 0; i != NumElems; ++i) {
6683 int EltIdx = SVOp->getMaskElt(i);
6684 if ((i & Mask) != 0 && EltIdx != -1)
6686 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6690 LLVMContext *Context = DAG.getContext();
6691 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6692 EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6693 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6695 if (!isTypeLegal(NVT))
6698 // Simplify the operand as it's prepared to be fed into shuffle.
6699 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6700 if (V1.getOpcode() == ISD::BITCAST &&
6701 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6702 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6704 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6705 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6706 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6707 ConstantSDNode *CIdx =
6708 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6709 // If it's foldable, i.e. normal load with single use, we will let code
6710 // selection to fold it. Otherwise, we will short the conversion sequence.
6711 if (CIdx && CIdx->getZExtValue() == 0 &&
6712 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6713 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6714 // The "ext_vec_elt" node is wider than the result node.
6715 // In this case we should extract subvector from V.
6716 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6717 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6718 EVT FullVT = V.getValueType();
6719 EVT SubVecVT = EVT::getVectorVT(*Context,
6720 FullVT.getVectorElementType(),
6721 FullVT.getVectorNumElements()/Ratio);
6722 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6723 DAG.getIntPtrConstant(0));
6725 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6729 return DAG.getNode(ISD::BITCAST, DL, VT,
6730 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6734 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6735 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6736 MVT VT = Op.getValueType().getSimpleVT();
6737 DebugLoc dl = Op.getDebugLoc();
6738 SDValue V1 = Op.getOperand(0);
6739 SDValue V2 = Op.getOperand(1);
6741 if (isZeroShuffle(SVOp))
6742 return getZeroVector(VT, Subtarget, DAG, dl);
6744 // Handle splat operations
6745 if (SVOp->isSplat()) {
6746 // Use vbroadcast whenever the splat comes from a foldable load
6747 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6748 if (Broadcast.getNode())
6752 // Check integer expanding shuffles.
6753 SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6754 if (NewOp.getNode())
6757 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6759 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6760 VT == MVT::v16i16 || VT == MVT::v32i8) {
6761 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6762 if (NewOp.getNode())
6763 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6764 } else if ((VT == MVT::v4i32 ||
6765 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6766 // FIXME: Figure out a cleaner way to do this.
6767 // Try to make use of movq to zero out the top part.
6768 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6769 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6770 if (NewOp.getNode()) {
6771 MVT NewVT = NewOp.getValueType().getSimpleVT();
6772 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6773 NewVT, true, false))
6774 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6775 DAG, Subtarget, dl);
6777 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6778 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6779 if (NewOp.getNode()) {
6780 MVT NewVT = NewOp.getValueType().getSimpleVT();
6781 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6782 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6783 DAG, Subtarget, dl);
6791 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6792 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6793 SDValue V1 = Op.getOperand(0);
6794 SDValue V2 = Op.getOperand(1);
6795 MVT VT = Op.getValueType().getSimpleVT();
6796 DebugLoc dl = Op.getDebugLoc();
6797 unsigned NumElems = VT.getVectorNumElements();
6798 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6799 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6800 bool V1IsSplat = false;
6801 bool V2IsSplat = false;
6802 bool HasSSE2 = Subtarget->hasSSE2();
6803 bool HasFp256 = Subtarget->hasFp256();
6804 bool HasInt256 = Subtarget->hasInt256();
6805 MachineFunction &MF = DAG.getMachineFunction();
6806 bool OptForSize = MF.getFunction()->getAttributes().
6807 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6809 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6811 if (V1IsUndef && V2IsUndef)
6812 return DAG.getUNDEF(VT);
6814 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6816 // Vector shuffle lowering takes 3 steps:
6818 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6819 // narrowing and commutation of operands should be handled.
6820 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6822 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6823 // so the shuffle can be broken into other shuffles and the legalizer can
6824 // try the lowering again.
6826 // The general idea is that no vector_shuffle operation should be left to
6827 // be matched during isel, all of them must be converted to a target specific
6830 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6831 // narrowing and commutation of operands should be handled. The actual code
6832 // doesn't include all of those, work in progress...
6833 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6834 if (NewOp.getNode())
6837 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6839 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6840 // unpckh_undef). Only use pshufd if speed is more important than size.
6841 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6842 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6843 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6844 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6846 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6847 V2IsUndef && MayFoldVectorLoad(V1))
6848 return getMOVDDup(Op, dl, V1, DAG);
6850 if (isMOVHLPS_v_undef_Mask(M, VT))
6851 return getMOVHighToLow(Op, dl, DAG);
6853 // Use to match splats
6854 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6855 (VT == MVT::v2f64 || VT == MVT::v2i64))
6856 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6858 if (isPSHUFDMask(M, VT)) {
6859 // The actual implementation will match the mask in the if above and then
6860 // during isel it can match several different instructions, not only pshufd
6861 // as its name says, sad but true, emulate the behavior for now...
6862 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6863 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6865 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6867 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6868 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6870 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6871 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6874 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6878 // Check if this can be converted into a logical shift.
6879 bool isLeft = false;
6882 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6883 if (isShift && ShVal.hasOneUse()) {
6884 // If the shifted value has multiple uses, it may be cheaper to use
6885 // v_set0 + movlhps or movhlps, etc.
6886 MVT EltVT = VT.getVectorElementType();
6887 ShAmt *= EltVT.getSizeInBits();
6888 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6891 if (isMOVLMask(M, VT)) {
6892 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6893 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6894 if (!isMOVLPMask(M, VT)) {
6895 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6896 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6898 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6899 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6903 // FIXME: fold these into legal mask.
6904 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6905 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6907 if (isMOVHLPSMask(M, VT))
6908 return getMOVHighToLow(Op, dl, DAG);
6910 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6911 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6913 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6914 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6916 if (isMOVLPMask(M, VT))
6917 return getMOVLP(Op, dl, DAG, HasSSE2);
6919 if (ShouldXformToMOVHLPS(M, VT) ||
6920 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6921 return CommuteVectorShuffle(SVOp, DAG);
6924 // No better options. Use a vshldq / vsrldq.
6925 MVT EltVT = VT.getVectorElementType();
6926 ShAmt *= EltVT.getSizeInBits();
6927 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6930 bool Commuted = false;
6931 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6932 // 1,1,1,1 -> v8i16 though.
6933 V1IsSplat = isSplatVector(V1.getNode());
6934 V2IsSplat = isSplatVector(V2.getNode());
6936 // Canonicalize the splat or undef, if present, to be on the RHS.
6937 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6938 CommuteVectorShuffleMask(M, NumElems);
6940 std::swap(V1IsSplat, V2IsSplat);
6944 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6945 // Shuffling low element of v1 into undef, just return v1.
6948 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6949 // the instruction selector will not match, so get a canonical MOVL with
6950 // swapped operands to undo the commute.
6951 return getMOVL(DAG, dl, VT, V2, V1);
6954 if (isUNPCKLMask(M, VT, HasInt256))
6955 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6957 if (isUNPCKHMask(M, VT, HasInt256))
6958 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6961 // Normalize mask so all entries that point to V2 points to its first
6962 // element then try to match unpck{h|l} again. If match, return a
6963 // new vector_shuffle with the corrected mask.p
6964 SmallVector<int, 8> NewMask(M.begin(), M.end());
6965 NormalizeMask(NewMask, NumElems);
6966 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6967 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6968 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6969 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6973 // Commute is back and try unpck* again.
6974 // FIXME: this seems wrong.
6975 CommuteVectorShuffleMask(M, NumElems);
6977 std::swap(V1IsSplat, V2IsSplat);
6980 if (isUNPCKLMask(M, VT, HasInt256))
6981 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6983 if (isUNPCKHMask(M, VT, HasInt256))
6984 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6987 // Normalize the node to match x86 shuffle ops if needed
6988 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6989 return CommuteVectorShuffle(SVOp, DAG);
6991 // The checks below are all present in isShuffleMaskLegal, but they are
6992 // inlined here right now to enable us to directly emit target specific
6993 // nodes, and remove one by one until they don't return Op anymore.
6995 if (isPALIGNRMask(M, VT, Subtarget))
6996 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6997 getShufflePALIGNRImmediate(SVOp),
7000 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7001 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7002 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7003 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7006 if (isPSHUFHWMask(M, VT, HasInt256))
7007 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7008 getShufflePSHUFHWImmediate(SVOp),
7011 if (isPSHUFLWMask(M, VT, HasInt256))
7012 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7013 getShufflePSHUFLWImmediate(SVOp),
7016 if (isSHUFPMask(M, VT, HasFp256))
7017 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7018 getShuffleSHUFImmediate(SVOp), DAG);
7020 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7021 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7022 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7023 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7025 //===--------------------------------------------------------------------===//
7026 // Generate target specific nodes for 128 or 256-bit shuffles only
7027 // supported in the AVX instruction set.
7030 // Handle VMOVDDUPY permutations
7031 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7032 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7034 // Handle VPERMILPS/D* permutations
7035 if (isVPERMILPMask(M, VT, HasFp256)) {
7036 if (HasInt256 && VT == MVT::v8i32)
7037 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7038 getShuffleSHUFImmediate(SVOp), DAG);
7039 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7040 getShuffleSHUFImmediate(SVOp), DAG);
7043 // Handle VPERM2F128/VPERM2I128 permutations
7044 if (isVPERM2X128Mask(M, VT, HasFp256))
7045 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7046 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7048 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7049 if (BlendOp.getNode())
7052 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7053 SmallVector<SDValue, 8> permclMask;
7054 for (unsigned i = 0; i != 8; ++i) {
7055 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7057 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7059 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7060 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7061 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7064 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7065 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7066 getShuffleCLImmediate(SVOp), DAG);
7068 //===--------------------------------------------------------------------===//
7069 // Since no target specific shuffle was selected for this generic one,
7070 // lower it into other known shuffles. FIXME: this isn't true yet, but
7071 // this is the plan.
7074 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7075 if (VT == MVT::v8i16) {
7076 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7077 if (NewOp.getNode())
7081 if (VT == MVT::v16i8) {
7082 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7083 if (NewOp.getNode())
7087 if (VT == MVT::v32i8) {
7088 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7089 if (NewOp.getNode())
7093 // Handle all 128-bit wide vectors with 4 elements, and match them with
7094 // several different shuffle types.
7095 if (NumElems == 4 && VT.is128BitVector())
7096 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7098 // Handle general 256-bit shuffles
7099 if (VT.is256BitVector())
7100 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7105 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7106 MVT VT = Op.getValueType().getSimpleVT();
7107 DebugLoc dl = Op.getDebugLoc();
7109 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7112 if (VT.getSizeInBits() == 8) {
7113 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7114 Op.getOperand(0), Op.getOperand(1));
7115 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7116 DAG.getValueType(VT));
7117 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7120 if (VT.getSizeInBits() == 16) {
7121 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7122 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7124 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7125 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7126 DAG.getNode(ISD::BITCAST, dl,
7130 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7131 Op.getOperand(0), Op.getOperand(1));
7132 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7133 DAG.getValueType(VT));
7134 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7137 if (VT == MVT::f32) {
7138 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7139 // the result back to FR32 register. It's only worth matching if the
7140 // result has a single use which is a store or a bitcast to i32. And in
7141 // the case of a store, it's not worth it if the index is a constant 0,
7142 // because a MOVSSmr can be used instead, which is smaller and faster.
7143 if (!Op.hasOneUse())
7145 SDNode *User = *Op.getNode()->use_begin();
7146 if ((User->getOpcode() != ISD::STORE ||
7147 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7148 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7149 (User->getOpcode() != ISD::BITCAST ||
7150 User->getValueType(0) != MVT::i32))
7152 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7153 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7156 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7159 if (VT == MVT::i32 || VT == MVT::i64) {
7160 // ExtractPS/pextrq works with constant index.
7161 if (isa<ConstantSDNode>(Op.getOperand(1)))
7168 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7169 SelectionDAG &DAG) const {
7170 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7173 SDValue Vec = Op.getOperand(0);
7174 MVT VecVT = Vec.getValueType().getSimpleVT();
7176 // If this is a 256-bit vector result, first extract the 128-bit vector and
7177 // then extract the element from the 128-bit vector.
7178 if (VecVT.is256BitVector()) {
7179 DebugLoc dl = Op.getNode()->getDebugLoc();
7180 unsigned NumElems = VecVT.getVectorNumElements();
7181 SDValue Idx = Op.getOperand(1);
7182 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7184 // Get the 128-bit vector.
7185 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7187 if (IdxVal >= NumElems/2)
7188 IdxVal -= NumElems/2;
7189 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7190 DAG.getConstant(IdxVal, MVT::i32));
7193 assert(VecVT.is128BitVector() && "Unexpected vector length");
7195 if (Subtarget->hasSSE41()) {
7196 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7201 MVT VT = Op.getValueType().getSimpleVT();
7202 DebugLoc dl = Op.getDebugLoc();
7203 // TODO: handle v16i8.
7204 if (VT.getSizeInBits() == 16) {
7205 SDValue Vec = Op.getOperand(0);
7206 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7208 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7209 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7210 DAG.getNode(ISD::BITCAST, dl,
7213 // Transform it so it match pextrw which produces a 32-bit result.
7214 MVT EltVT = MVT::i32;
7215 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7216 Op.getOperand(0), Op.getOperand(1));
7217 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7218 DAG.getValueType(VT));
7219 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7222 if (VT.getSizeInBits() == 32) {
7223 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7227 // SHUFPS the element to the lowest double word, then movss.
7228 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7229 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7230 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7231 DAG.getUNDEF(VVT), Mask);
7232 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7233 DAG.getIntPtrConstant(0));
7236 if (VT.getSizeInBits() == 64) {
7237 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7238 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7239 // to match extract_elt for f64.
7240 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7244 // UNPCKHPD the element to the lowest double word, then movsd.
7245 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7246 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7247 int Mask[2] = { 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));
7258 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7259 MVT VT = Op.getValueType().getSimpleVT();
7260 MVT EltVT = VT.getVectorElementType();
7261 DebugLoc dl = Op.getDebugLoc();
7263 SDValue N0 = Op.getOperand(0);
7264 SDValue N1 = Op.getOperand(1);
7265 SDValue N2 = Op.getOperand(2);
7267 if (!VT.is128BitVector())
7270 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7271 isa<ConstantSDNode>(N2)) {
7273 if (VT == MVT::v8i16)
7274 Opc = X86ISD::PINSRW;
7275 else if (VT == MVT::v16i8)
7276 Opc = X86ISD::PINSRB;
7278 Opc = X86ISD::PINSRB;
7280 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7282 if (N1.getValueType() != MVT::i32)
7283 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7284 if (N2.getValueType() != MVT::i32)
7285 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7286 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7289 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7290 // Bits [7:6] of the constant are the source select. This will always be
7291 // zero here. The DAG Combiner may combine an extract_elt index into these
7292 // bits. For example (insert (extract, 3), 2) could be matched by putting
7293 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7294 // Bits [5:4] of the constant are the destination select. This is the
7295 // value of the incoming immediate.
7296 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7297 // combine either bitwise AND or insert of float 0.0 to set these bits.
7298 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7299 // Create this as a scalar to vector..
7300 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7301 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7304 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7305 // PINSR* works with constant index.
7312 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7313 MVT VT = Op.getValueType().getSimpleVT();
7314 MVT EltVT = VT.getVectorElementType();
7316 DebugLoc dl = Op.getDebugLoc();
7317 SDValue N0 = Op.getOperand(0);
7318 SDValue N1 = Op.getOperand(1);
7319 SDValue N2 = Op.getOperand(2);
7321 // If this is a 256-bit vector result, first extract the 128-bit vector,
7322 // insert the element into the extracted half and then place it back.
7323 if (VT.is256BitVector()) {
7324 if (!isa<ConstantSDNode>(N2))
7327 // Get the desired 128-bit vector half.
7328 unsigned NumElems = VT.getVectorNumElements();
7329 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7330 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7332 // Insert the element into the desired half.
7333 bool Upper = IdxVal >= NumElems/2;
7334 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7335 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7337 // Insert the changed part back to the 256-bit vector
7338 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7341 if (Subtarget->hasSSE41())
7342 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7344 if (EltVT == MVT::i8)
7347 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7348 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7349 // as its second argument.
7350 if (N1.getValueType() != MVT::i32)
7351 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7352 if (N2.getValueType() != MVT::i32)
7353 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7354 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7359 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7360 LLVMContext *Context = DAG.getContext();
7361 DebugLoc dl = Op.getDebugLoc();
7362 MVT OpVT = Op.getValueType().getSimpleVT();
7364 // If this is a 256-bit vector result, first insert into a 128-bit
7365 // vector and then insert into the 256-bit vector.
7366 if (!OpVT.is128BitVector()) {
7367 // Insert into a 128-bit vector.
7368 EVT VT128 = EVT::getVectorVT(*Context,
7369 OpVT.getVectorElementType(),
7370 OpVT.getVectorNumElements() / 2);
7372 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7374 // Insert the 128-bit vector.
7375 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7378 if (OpVT == MVT::v1i64 &&
7379 Op.getOperand(0).getValueType() == MVT::i64)
7380 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7382 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7383 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7384 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7385 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7388 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7389 // a simple subregister reference or explicit instructions to grab
7390 // upper bits of a vector.
7391 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7392 SelectionDAG &DAG) {
7393 if (Subtarget->hasFp256()) {
7394 DebugLoc dl = Op.getNode()->getDebugLoc();
7395 SDValue Vec = Op.getNode()->getOperand(0);
7396 SDValue Idx = Op.getNode()->getOperand(1);
7398 if (Op.getNode()->getValueType(0).is128BitVector() &&
7399 Vec.getNode()->getValueType(0).is256BitVector() &&
7400 isa<ConstantSDNode>(Idx)) {
7401 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7402 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7408 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7409 // simple superregister reference or explicit instructions to insert
7410 // the upper bits of a vector.
7411 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7412 SelectionDAG &DAG) {
7413 if (Subtarget->hasFp256()) {
7414 DebugLoc dl = Op.getNode()->getDebugLoc();
7415 SDValue Vec = Op.getNode()->getOperand(0);
7416 SDValue SubVec = Op.getNode()->getOperand(1);
7417 SDValue Idx = Op.getNode()->getOperand(2);
7419 if (Op.getNode()->getValueType(0).is256BitVector() &&
7420 SubVec.getNode()->getValueType(0).is128BitVector() &&
7421 isa<ConstantSDNode>(Idx)) {
7422 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7423 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7429 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7430 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7431 // one of the above mentioned nodes. It has to be wrapped because otherwise
7432 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7433 // be used to form addressing mode. These wrapped nodes will be selected
7436 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7437 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7439 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7441 unsigned char OpFlag = 0;
7442 unsigned WrapperKind = X86ISD::Wrapper;
7443 CodeModel::Model M = getTargetMachine().getCodeModel();
7445 if (Subtarget->isPICStyleRIPRel() &&
7446 (M == CodeModel::Small || M == CodeModel::Kernel))
7447 WrapperKind = X86ISD::WrapperRIP;
7448 else if (Subtarget->isPICStyleGOT())
7449 OpFlag = X86II::MO_GOTOFF;
7450 else if (Subtarget->isPICStyleStubPIC())
7451 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7453 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7455 CP->getOffset(), OpFlag);
7456 DebugLoc DL = CP->getDebugLoc();
7457 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7458 // With PIC, the address is actually $g + Offset.
7460 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7461 DAG.getNode(X86ISD::GlobalBaseReg,
7462 DebugLoc(), getPointerTy()),
7469 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7470 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7472 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7474 unsigned char OpFlag = 0;
7475 unsigned WrapperKind = X86ISD::Wrapper;
7476 CodeModel::Model M = getTargetMachine().getCodeModel();
7478 if (Subtarget->isPICStyleRIPRel() &&
7479 (M == CodeModel::Small || M == CodeModel::Kernel))
7480 WrapperKind = X86ISD::WrapperRIP;
7481 else if (Subtarget->isPICStyleGOT())
7482 OpFlag = X86II::MO_GOTOFF;
7483 else if (Subtarget->isPICStyleStubPIC())
7484 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7486 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7488 DebugLoc DL = JT->getDebugLoc();
7489 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7491 // With PIC, the address is actually $g + Offset.
7493 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7494 DAG.getNode(X86ISD::GlobalBaseReg,
7495 DebugLoc(), getPointerTy()),
7502 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7503 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7505 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7507 unsigned char OpFlag = 0;
7508 unsigned WrapperKind = X86ISD::Wrapper;
7509 CodeModel::Model M = getTargetMachine().getCodeModel();
7511 if (Subtarget->isPICStyleRIPRel() &&
7512 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7513 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7514 OpFlag = X86II::MO_GOTPCREL;
7515 WrapperKind = X86ISD::WrapperRIP;
7516 } else if (Subtarget->isPICStyleGOT()) {
7517 OpFlag = X86II::MO_GOT;
7518 } else if (Subtarget->isPICStyleStubPIC()) {
7519 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7520 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7521 OpFlag = X86II::MO_DARWIN_NONLAZY;
7524 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7526 DebugLoc DL = Op.getDebugLoc();
7527 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7529 // With PIC, the address is actually $g + Offset.
7530 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7531 !Subtarget->is64Bit()) {
7532 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7533 DAG.getNode(X86ISD::GlobalBaseReg,
7534 DebugLoc(), getPointerTy()),
7538 // For symbols that require a load from a stub to get the address, emit the
7540 if (isGlobalStubReference(OpFlag))
7541 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7542 MachinePointerInfo::getGOT(), false, false, false, 0);
7548 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7549 // Create the TargetBlockAddressAddress node.
7550 unsigned char OpFlags =
7551 Subtarget->ClassifyBlockAddressReference();
7552 CodeModel::Model M = getTargetMachine().getCodeModel();
7553 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7554 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7555 DebugLoc dl = Op.getDebugLoc();
7556 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7559 if (Subtarget->isPICStyleRIPRel() &&
7560 (M == CodeModel::Small || M == CodeModel::Kernel))
7561 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7563 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7565 // With PIC, the address is actually $g + Offset.
7566 if (isGlobalRelativeToPICBase(OpFlags)) {
7567 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7568 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7576 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7577 int64_t Offset, SelectionDAG &DAG) const {
7578 // Create the TargetGlobalAddress node, folding in the constant
7579 // offset if it is legal.
7580 unsigned char OpFlags =
7581 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7582 CodeModel::Model M = getTargetMachine().getCodeModel();
7584 if (OpFlags == X86II::MO_NO_FLAG &&
7585 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7586 // A direct static reference to a global.
7587 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7590 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7593 if (Subtarget->isPICStyleRIPRel() &&
7594 (M == CodeModel::Small || M == CodeModel::Kernel))
7595 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7597 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7599 // With PIC, the address is actually $g + Offset.
7600 if (isGlobalRelativeToPICBase(OpFlags)) {
7601 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7602 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7606 // For globals that require a load from a stub to get the address, emit the
7608 if (isGlobalStubReference(OpFlags))
7609 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7610 MachinePointerInfo::getGOT(), false, false, false, 0);
7612 // If there was a non-zero offset that we didn't fold, create an explicit
7615 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7616 DAG.getConstant(Offset, getPointerTy()));
7622 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7623 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7624 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7625 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7629 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7630 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7631 unsigned char OperandFlags, bool LocalDynamic = false) {
7632 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7633 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7634 DebugLoc dl = GA->getDebugLoc();
7635 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7636 GA->getValueType(0),
7640 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7644 SDValue Ops[] = { Chain, TGA, *InFlag };
7645 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7647 SDValue Ops[] = { Chain, TGA };
7648 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7651 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7652 MFI->setAdjustsStack(true);
7654 SDValue Flag = Chain.getValue(1);
7655 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7658 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7660 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7663 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7664 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7665 DAG.getNode(X86ISD::GlobalBaseReg,
7666 DebugLoc(), PtrVT), InFlag);
7667 InFlag = Chain.getValue(1);
7669 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7672 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7674 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7676 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7677 X86::RAX, X86II::MO_TLSGD);
7680 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7684 DebugLoc dl = GA->getDebugLoc();
7686 // Get the start address of the TLS block for this module.
7687 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7688 .getInfo<X86MachineFunctionInfo>();
7689 MFI->incNumLocalDynamicTLSAccesses();
7693 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7694 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7697 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7698 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7699 InFlag = Chain.getValue(1);
7700 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7701 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7704 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7708 unsigned char OperandFlags = X86II::MO_DTPOFF;
7709 unsigned WrapperKind = X86ISD::Wrapper;
7710 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7711 GA->getValueType(0),
7712 GA->getOffset(), OperandFlags);
7713 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7715 // Add x@dtpoff with the base.
7716 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7719 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7720 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7721 const EVT PtrVT, TLSModel::Model model,
7722 bool is64Bit, bool isPIC) {
7723 DebugLoc dl = GA->getDebugLoc();
7725 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7726 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7727 is64Bit ? 257 : 256));
7729 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7730 DAG.getIntPtrConstant(0),
7731 MachinePointerInfo(Ptr),
7732 false, false, false, 0);
7734 unsigned char OperandFlags = 0;
7735 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7737 unsigned WrapperKind = X86ISD::Wrapper;
7738 if (model == TLSModel::LocalExec) {
7739 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7740 } else if (model == TLSModel::InitialExec) {
7742 OperandFlags = X86II::MO_GOTTPOFF;
7743 WrapperKind = X86ISD::WrapperRIP;
7745 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7748 llvm_unreachable("Unexpected model");
7751 // emit "addl x@ntpoff,%eax" (local exec)
7752 // or "addl x@indntpoff,%eax" (initial exec)
7753 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7754 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7755 GA->getValueType(0),
7756 GA->getOffset(), OperandFlags);
7757 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7759 if (model == TLSModel::InitialExec) {
7760 if (isPIC && !is64Bit) {
7761 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7762 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7766 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7767 MachinePointerInfo::getGOT(), false, false, false,
7771 // The address of the thread local variable is the add of the thread
7772 // pointer with the offset of the variable.
7773 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7777 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7779 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7780 const GlobalValue *GV = GA->getGlobal();
7782 if (Subtarget->isTargetELF()) {
7783 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7786 case TLSModel::GeneralDynamic:
7787 if (Subtarget->is64Bit())
7788 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7789 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7790 case TLSModel::LocalDynamic:
7791 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7792 Subtarget->is64Bit());
7793 case TLSModel::InitialExec:
7794 case TLSModel::LocalExec:
7795 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7796 Subtarget->is64Bit(),
7797 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7799 llvm_unreachable("Unknown TLS model.");
7802 if (Subtarget->isTargetDarwin()) {
7803 // Darwin only has one model of TLS. Lower to that.
7804 unsigned char OpFlag = 0;
7805 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7806 X86ISD::WrapperRIP : X86ISD::Wrapper;
7808 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7810 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7811 !Subtarget->is64Bit();
7813 OpFlag = X86II::MO_TLVP_PIC_BASE;
7815 OpFlag = X86II::MO_TLVP;
7816 DebugLoc DL = Op.getDebugLoc();
7817 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7818 GA->getValueType(0),
7819 GA->getOffset(), OpFlag);
7820 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7822 // With PIC32, the address is actually $g + Offset.
7824 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7825 DAG.getNode(X86ISD::GlobalBaseReg,
7826 DebugLoc(), getPointerTy()),
7829 // Lowering the machine isd will make sure everything is in the right
7831 SDValue Chain = DAG.getEntryNode();
7832 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7833 SDValue Args[] = { Chain, Offset };
7834 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7836 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7837 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7838 MFI->setAdjustsStack(true);
7840 // And our return value (tls address) is in the standard call return value
7842 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7843 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7847 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7848 // Just use the implicit TLS architecture
7849 // Need to generate someting similar to:
7850 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7852 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7853 // mov rcx, qword [rdx+rcx*8]
7854 // mov eax, .tls$:tlsvar
7855 // [rax+rcx] contains the address
7856 // Windows 64bit: gs:0x58
7857 // Windows 32bit: fs:__tls_array
7859 // If GV is an alias then use the aliasee for determining
7860 // thread-localness.
7861 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7862 GV = GA->resolveAliasedGlobal(false);
7863 DebugLoc dl = GA->getDebugLoc();
7864 SDValue Chain = DAG.getEntryNode();
7866 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7867 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7868 // use its literal value of 0x2C.
7869 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7870 ? Type::getInt8PtrTy(*DAG.getContext(),
7872 : Type::getInt32PtrTy(*DAG.getContext(),
7875 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7876 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7877 DAG.getExternalSymbol("_tls_array", getPointerTy()));
7879 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7880 MachinePointerInfo(Ptr),
7881 false, false, false, 0);
7883 // Load the _tls_index variable
7884 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7885 if (Subtarget->is64Bit())
7886 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7887 IDX, MachinePointerInfo(), MVT::i32,
7890 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7891 false, false, false, 0);
7893 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7895 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7897 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7898 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7899 false, false, false, 0);
7901 // Get the offset of start of .tls section
7902 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7903 GA->getValueType(0),
7904 GA->getOffset(), X86II::MO_SECREL);
7905 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7907 // The address of the thread local variable is the add of the thread
7908 // pointer with the offset of the variable.
7909 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7912 llvm_unreachable("TLS not implemented for this target.");
7915 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7916 /// and take a 2 x i32 value to shift plus a shift amount.
7917 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7918 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7919 EVT VT = Op.getValueType();
7920 unsigned VTBits = VT.getSizeInBits();
7921 DebugLoc dl = Op.getDebugLoc();
7922 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7923 SDValue ShOpLo = Op.getOperand(0);
7924 SDValue ShOpHi = Op.getOperand(1);
7925 SDValue ShAmt = Op.getOperand(2);
7926 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7927 DAG.getConstant(VTBits - 1, MVT::i8))
7928 : DAG.getConstant(0, VT);
7931 if (Op.getOpcode() == ISD::SHL_PARTS) {
7932 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7933 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7935 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7936 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7939 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7940 DAG.getConstant(VTBits, MVT::i8));
7941 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7942 AndNode, DAG.getConstant(0, MVT::i8));
7945 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7946 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7947 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7949 if (Op.getOpcode() == ISD::SHL_PARTS) {
7950 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7951 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7953 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7954 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7957 SDValue Ops[2] = { Lo, Hi };
7958 return DAG.getMergeValues(Ops, 2, dl);
7961 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7962 SelectionDAG &DAG) const {
7963 EVT SrcVT = Op.getOperand(0).getValueType();
7965 if (SrcVT.isVector())
7968 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7969 "Unknown SINT_TO_FP to lower!");
7971 // These are really Legal; return the operand so the caller accepts it as
7973 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7975 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7976 Subtarget->is64Bit()) {
7980 DebugLoc dl = Op.getDebugLoc();
7981 unsigned Size = SrcVT.getSizeInBits()/8;
7982 MachineFunction &MF = DAG.getMachineFunction();
7983 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7984 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7985 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7987 MachinePointerInfo::getFixedStack(SSFI),
7989 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7992 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7994 SelectionDAG &DAG) const {
7996 DebugLoc DL = Op.getDebugLoc();
7998 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8000 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8002 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8004 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8006 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8007 MachineMemOperand *MMO;
8009 int SSFI = FI->getIndex();
8011 DAG.getMachineFunction()
8012 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8013 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8015 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8016 StackSlot = StackSlot.getOperand(1);
8018 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8019 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8021 Tys, Ops, array_lengthof(Ops),
8025 Chain = Result.getValue(1);
8026 SDValue InFlag = Result.getValue(2);
8028 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8029 // shouldn't be necessary except that RFP cannot be live across
8030 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8031 MachineFunction &MF = DAG.getMachineFunction();
8032 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8033 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8034 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8035 Tys = DAG.getVTList(MVT::Other);
8037 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8039 MachineMemOperand *MMO =
8040 DAG.getMachineFunction()
8041 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8042 MachineMemOperand::MOStore, SSFISize, SSFISize);
8044 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8045 Ops, array_lengthof(Ops),
8046 Op.getValueType(), MMO);
8047 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8048 MachinePointerInfo::getFixedStack(SSFI),
8049 false, false, false, 0);
8055 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8056 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8057 SelectionDAG &DAG) const {
8058 // This algorithm is not obvious. Here it is what we're trying to output:
8061 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8062 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8066 pshufd $0x4e, %xmm0, %xmm1
8071 DebugLoc dl = Op.getDebugLoc();
8072 LLVMContext *Context = DAG.getContext();
8074 // Build some magic constants.
8075 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8076 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8077 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8079 SmallVector<Constant*,2> CV1;
8081 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8082 APInt(64, 0x4330000000000000ULL))));
8084 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8085 APInt(64, 0x4530000000000000ULL))));
8086 Constant *C1 = ConstantVector::get(CV1);
8087 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8089 // Load the 64-bit value into an XMM register.
8090 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8092 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8093 MachinePointerInfo::getConstantPool(),
8094 false, false, false, 16);
8095 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8096 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8099 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8100 MachinePointerInfo::getConstantPool(),
8101 false, false, false, 16);
8102 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8103 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8106 if (Subtarget->hasSSE3()) {
8107 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8108 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8110 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8111 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8113 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8114 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8118 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8119 DAG.getIntPtrConstant(0));
8122 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8123 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8124 SelectionDAG &DAG) const {
8125 DebugLoc dl = Op.getDebugLoc();
8126 // FP constant to bias correct the final result.
8127 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8130 // Load the 32-bit value into an XMM register.
8131 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8134 // Zero out the upper parts of the register.
8135 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8137 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8138 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8139 DAG.getIntPtrConstant(0));
8141 // Or the load with the bias.
8142 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8143 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8144 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8146 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8147 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8148 MVT::v2f64, Bias)));
8149 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8150 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8151 DAG.getIntPtrConstant(0));
8153 // Subtract the bias.
8154 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8156 // Handle final rounding.
8157 EVT DestVT = Op.getValueType();
8159 if (DestVT.bitsLT(MVT::f64))
8160 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8161 DAG.getIntPtrConstant(0));
8162 if (DestVT.bitsGT(MVT::f64))
8163 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8165 // Handle final rounding.
8169 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8170 SelectionDAG &DAG) const {
8171 SDValue N0 = Op.getOperand(0);
8172 EVT SVT = N0.getValueType();
8173 DebugLoc dl = Op.getDebugLoc();
8175 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8176 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8177 "Custom UINT_TO_FP is not supported!");
8179 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8180 SVT.getVectorNumElements());
8181 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8182 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8185 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8186 SelectionDAG &DAG) const {
8187 SDValue N0 = Op.getOperand(0);
8188 DebugLoc dl = Op.getDebugLoc();
8190 if (Op.getValueType().isVector())
8191 return lowerUINT_TO_FP_vec(Op, DAG);
8193 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8194 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8195 // the optimization here.
8196 if (DAG.SignBitIsZero(N0))
8197 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8199 EVT SrcVT = N0.getValueType();
8200 EVT DstVT = Op.getValueType();
8201 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8202 return LowerUINT_TO_FP_i64(Op, DAG);
8203 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8204 return LowerUINT_TO_FP_i32(Op, DAG);
8205 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8208 // Make a 64-bit buffer, and use it to build an FILD.
8209 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8210 if (SrcVT == MVT::i32) {
8211 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8212 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8213 getPointerTy(), StackSlot, WordOff);
8214 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8215 StackSlot, MachinePointerInfo(),
8217 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8218 OffsetSlot, MachinePointerInfo(),
8220 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8224 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8225 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8226 StackSlot, MachinePointerInfo(),
8228 // For i64 source, we need to add the appropriate power of 2 if the input
8229 // was negative. This is the same as the optimization in
8230 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8231 // we must be careful to do the computation in x87 extended precision, not
8232 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8233 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8234 MachineMemOperand *MMO =
8235 DAG.getMachineFunction()
8236 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8237 MachineMemOperand::MOLoad, 8, 8);
8239 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8240 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8241 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8244 APInt FF(32, 0x5F800000ULL);
8246 // Check whether the sign bit is set.
8247 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8248 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8251 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8252 SDValue FudgePtr = DAG.getConstantPool(
8253 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8256 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8257 SDValue Zero = DAG.getIntPtrConstant(0);
8258 SDValue Four = DAG.getIntPtrConstant(4);
8259 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8261 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8263 // Load the value out, extending it from f32 to f80.
8264 // FIXME: Avoid the extend by constructing the right constant pool?
8265 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8266 FudgePtr, MachinePointerInfo::getConstantPool(),
8267 MVT::f32, false, false, 4);
8268 // Extend everything to 80 bits to force it to be done on x87.
8269 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8270 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8273 std::pair<SDValue,SDValue>
8274 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8275 bool IsSigned, bool IsReplace) const {
8276 DebugLoc DL = Op.getDebugLoc();
8278 EVT DstTy = Op.getValueType();
8280 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8281 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8285 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8286 DstTy.getSimpleVT() >= MVT::i16 &&
8287 "Unknown FP_TO_INT to lower!");
8289 // These are really Legal.
8290 if (DstTy == MVT::i32 &&
8291 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8292 return std::make_pair(SDValue(), SDValue());
8293 if (Subtarget->is64Bit() &&
8294 DstTy == MVT::i64 &&
8295 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8296 return std::make_pair(SDValue(), SDValue());
8298 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8299 // stack slot, or into the FTOL runtime function.
8300 MachineFunction &MF = DAG.getMachineFunction();
8301 unsigned MemSize = DstTy.getSizeInBits()/8;
8302 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8303 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8306 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8307 Opc = X86ISD::WIN_FTOL;
8309 switch (DstTy.getSimpleVT().SimpleTy) {
8310 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8311 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8312 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8313 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8316 SDValue Chain = DAG.getEntryNode();
8317 SDValue Value = Op.getOperand(0);
8318 EVT TheVT = Op.getOperand(0).getValueType();
8319 // FIXME This causes a redundant load/store if the SSE-class value is already
8320 // in memory, such as if it is on the callstack.
8321 if (isScalarFPTypeInSSEReg(TheVT)) {
8322 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8323 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8324 MachinePointerInfo::getFixedStack(SSFI),
8326 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8328 Chain, StackSlot, DAG.getValueType(TheVT)
8331 MachineMemOperand *MMO =
8332 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8333 MachineMemOperand::MOLoad, MemSize, MemSize);
8334 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8336 Chain = Value.getValue(1);
8337 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8338 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8341 MachineMemOperand *MMO =
8342 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8343 MachineMemOperand::MOStore, MemSize, MemSize);
8345 if (Opc != X86ISD::WIN_FTOL) {
8346 // Build the FP_TO_INT*_IN_MEM
8347 SDValue Ops[] = { Chain, Value, StackSlot };
8348 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8349 Ops, 3, DstTy, MMO);
8350 return std::make_pair(FIST, StackSlot);
8352 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8353 DAG.getVTList(MVT::Other, MVT::Glue),
8355 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8356 MVT::i32, ftol.getValue(1));
8357 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8358 MVT::i32, eax.getValue(2));
8359 SDValue Ops[] = { eax, edx };
8360 SDValue pair = IsReplace
8361 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8362 : DAG.getMergeValues(Ops, 2, DL);
8363 return std::make_pair(pair, SDValue());
8367 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8368 const X86Subtarget *Subtarget) {
8369 MVT VT = Op->getValueType(0).getSimpleVT();
8370 SDValue In = Op->getOperand(0);
8371 MVT InVT = In.getValueType().getSimpleVT();
8372 DebugLoc dl = Op->getDebugLoc();
8374 // Optimize vectors in AVX mode:
8377 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8378 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8379 // Concat upper and lower parts.
8382 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8383 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8384 // Concat upper and lower parts.
8387 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8388 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8391 if (Subtarget->hasInt256())
8392 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8394 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8395 SDValue Undef = DAG.getUNDEF(InVT);
8396 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8397 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8398 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8400 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8401 VT.getVectorNumElements()/2);
8403 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8404 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8406 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8409 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8410 SelectionDAG &DAG) const {
8411 if (Subtarget->hasFp256()) {
8412 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8419 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8420 SelectionDAG &DAG) const {
8421 DebugLoc DL = Op.getDebugLoc();
8422 MVT VT = Op.getValueType().getSimpleVT();
8423 SDValue In = Op.getOperand(0);
8424 MVT SVT = In.getValueType().getSimpleVT();
8426 if (Subtarget->hasFp256()) {
8427 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8432 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8433 VT.getVectorNumElements() != SVT.getVectorNumElements())
8436 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8438 // AVX2 has better support of integer extending.
8439 if (Subtarget->hasInt256())
8440 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8442 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8443 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8444 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8445 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8446 DAG.getUNDEF(MVT::v8i16),
8449 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8452 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8453 DebugLoc DL = Op.getDebugLoc();
8454 MVT VT = Op.getValueType().getSimpleVT();
8455 SDValue In = Op.getOperand(0);
8456 MVT SVT = In.getValueType().getSimpleVT();
8458 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8459 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8460 if (Subtarget->hasInt256()) {
8461 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8462 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8463 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8465 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8466 DAG.getIntPtrConstant(0));
8469 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8470 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8471 DAG.getIntPtrConstant(0));
8472 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8473 DAG.getIntPtrConstant(2));
8475 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8476 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8479 static const int ShufMask1[] = {0, 2, 0, 0};
8480 SDValue Undef = DAG.getUNDEF(VT);
8481 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8482 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8484 // The MOVLHPS mask:
8485 static const int ShufMask2[] = {0, 1, 4, 5};
8486 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8489 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8490 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8491 if (Subtarget->hasInt256()) {
8492 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8494 SmallVector<SDValue,32> pshufbMask;
8495 for (unsigned i = 0; i < 2; ++i) {
8496 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8497 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8498 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8499 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8500 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8501 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8502 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8503 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8504 for (unsigned j = 0; j < 8; ++j)
8505 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8507 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8508 &pshufbMask[0], 32);
8509 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8510 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8512 static const int ShufMask[] = {0, 2, -1, -1};
8513 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8515 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8516 DAG.getIntPtrConstant(0));
8517 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8520 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8521 DAG.getIntPtrConstant(0));
8523 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8524 DAG.getIntPtrConstant(4));
8526 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8527 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8530 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8531 -1, -1, -1, -1, -1, -1, -1, -1};
8533 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8534 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8535 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8537 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8538 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8540 // The MOVLHPS Mask:
8541 static const int ShufMask2[] = {0, 1, 4, 5};
8542 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8543 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8546 // Handle truncation of V256 to V128 using shuffles.
8547 if (!VT.is128BitVector() || !SVT.is256BitVector())
8550 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8552 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8554 unsigned NumElems = VT.getVectorNumElements();
8555 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8558 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8559 // Prepare truncation shuffle mask
8560 for (unsigned i = 0; i != NumElems; ++i)
8562 SDValue V = DAG.getVectorShuffle(NVT, DL,
8563 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8564 DAG.getUNDEF(NVT), &MaskVec[0]);
8565 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8566 DAG.getIntPtrConstant(0));
8569 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8570 SelectionDAG &DAG) const {
8571 MVT VT = Op.getValueType().getSimpleVT();
8572 if (VT.isVector()) {
8573 if (VT == MVT::v8i16)
8574 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8575 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8576 MVT::v8i32, Op.getOperand(0)));
8580 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8581 /*IsSigned=*/ true, /*IsReplace=*/ false);
8582 SDValue FIST = Vals.first, StackSlot = Vals.second;
8583 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8584 if (FIST.getNode() == 0) return Op;
8586 if (StackSlot.getNode())
8588 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8589 FIST, StackSlot, MachinePointerInfo(),
8590 false, false, false, 0);
8592 // The node is the result.
8596 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8597 SelectionDAG &DAG) const {
8598 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8599 /*IsSigned=*/ false, /*IsReplace=*/ false);
8600 SDValue FIST = Vals.first, StackSlot = Vals.second;
8601 assert(FIST.getNode() && "Unexpected failure");
8603 if (StackSlot.getNode())
8605 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8606 FIST, StackSlot, MachinePointerInfo(),
8607 false, false, false, 0);
8609 // The node is the result.
8613 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8614 DebugLoc DL = Op.getDebugLoc();
8615 MVT VT = Op.getValueType().getSimpleVT();
8616 SDValue In = Op.getOperand(0);
8617 MVT SVT = In.getValueType().getSimpleVT();
8619 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8621 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8622 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8623 In, DAG.getUNDEF(SVT)));
8626 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8627 LLVMContext *Context = DAG.getContext();
8628 DebugLoc dl = Op.getDebugLoc();
8629 MVT VT = Op.getValueType().getSimpleVT();
8631 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8632 if (VT.isVector()) {
8633 EltVT = VT.getVectorElementType();
8634 NumElts = VT.getVectorNumElements();
8637 if (EltVT == MVT::f64)
8638 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8639 APInt(64, ~(1ULL << 63))));
8641 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8642 APInt(32, ~(1U << 31))));
8643 C = ConstantVector::getSplat(NumElts, C);
8644 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8645 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8646 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8647 MachinePointerInfo::getConstantPool(),
8648 false, false, false, Alignment);
8649 if (VT.isVector()) {
8650 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8651 return DAG.getNode(ISD::BITCAST, dl, VT,
8652 DAG.getNode(ISD::AND, dl, ANDVT,
8653 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8655 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8657 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8660 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8661 LLVMContext *Context = DAG.getContext();
8662 DebugLoc dl = Op.getDebugLoc();
8663 MVT VT = Op.getValueType().getSimpleVT();
8665 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8666 if (VT.isVector()) {
8667 EltVT = VT.getVectorElementType();
8668 NumElts = VT.getVectorNumElements();
8671 if (EltVT == MVT::f64)
8672 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8673 APInt(64, 1ULL << 63)));
8675 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8676 APInt(32, 1U << 31)));
8677 C = ConstantVector::getSplat(NumElts, C);
8678 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8679 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8680 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8681 MachinePointerInfo::getConstantPool(),
8682 false, false, false, Alignment);
8683 if (VT.isVector()) {
8684 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8685 return DAG.getNode(ISD::BITCAST, dl, VT,
8686 DAG.getNode(ISD::XOR, dl, XORVT,
8687 DAG.getNode(ISD::BITCAST, dl, XORVT,
8689 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8692 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8695 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8696 LLVMContext *Context = DAG.getContext();
8697 SDValue Op0 = Op.getOperand(0);
8698 SDValue Op1 = Op.getOperand(1);
8699 DebugLoc dl = Op.getDebugLoc();
8700 MVT VT = Op.getValueType().getSimpleVT();
8701 MVT SrcVT = Op1.getValueType().getSimpleVT();
8703 // If second operand is smaller, extend it first.
8704 if (SrcVT.bitsLT(VT)) {
8705 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8708 // And if it is bigger, shrink it first.
8709 if (SrcVT.bitsGT(VT)) {
8710 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8714 // At this point the operands and the result should have the same
8715 // type, and that won't be f80 since that is not custom lowered.
8717 // First get the sign bit of second operand.
8718 SmallVector<Constant*,4> CV;
8719 if (SrcVT == MVT::f64) {
8720 const fltSemantics &Sem = APFloat::IEEEdouble;
8721 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8722 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8724 const fltSemantics &Sem = APFloat::IEEEsingle;
8725 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8726 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8727 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8728 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8730 Constant *C = ConstantVector::get(CV);
8731 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8732 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8733 MachinePointerInfo::getConstantPool(),
8734 false, false, false, 16);
8735 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8737 // Shift sign bit right or left if the two operands have different types.
8738 if (SrcVT.bitsGT(VT)) {
8739 // Op0 is MVT::f32, Op1 is MVT::f64.
8740 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8741 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8742 DAG.getConstant(32, MVT::i32));
8743 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8744 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8745 DAG.getIntPtrConstant(0));
8748 // Clear first operand sign bit.
8750 if (VT == MVT::f64) {
8751 const fltSemantics &Sem = APFloat::IEEEdouble;
8752 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8753 APInt(64, ~(1ULL << 63)))));
8754 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8756 const fltSemantics &Sem = APFloat::IEEEsingle;
8757 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8758 APInt(32, ~(1U << 31)))));
8759 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8760 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8761 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8763 C = ConstantVector::get(CV);
8764 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8765 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8766 MachinePointerInfo::getConstantPool(),
8767 false, false, false, 16);
8768 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8770 // Or the value with the sign bit.
8771 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8774 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8775 SDValue N0 = Op.getOperand(0);
8776 DebugLoc dl = Op.getDebugLoc();
8777 MVT VT = Op.getValueType().getSimpleVT();
8779 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8780 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8781 DAG.getConstant(1, VT));
8782 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8785 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8787 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8788 SelectionDAG &DAG) const {
8789 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8791 if (!Subtarget->hasSSE41())
8794 if (!Op->hasOneUse())
8797 SDNode *N = Op.getNode();
8798 DebugLoc DL = N->getDebugLoc();
8800 SmallVector<SDValue, 8> Opnds;
8801 DenseMap<SDValue, unsigned> VecInMap;
8802 EVT VT = MVT::Other;
8804 // Recognize a special case where a vector is casted into wide integer to
8806 Opnds.push_back(N->getOperand(0));
8807 Opnds.push_back(N->getOperand(1));
8809 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8810 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8811 // BFS traverse all OR'd operands.
8812 if (I->getOpcode() == ISD::OR) {
8813 Opnds.push_back(I->getOperand(0));
8814 Opnds.push_back(I->getOperand(1));
8815 // Re-evaluate the number of nodes to be traversed.
8816 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8820 // Quit if a non-EXTRACT_VECTOR_ELT
8821 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8824 // Quit if without a constant index.
8825 SDValue Idx = I->getOperand(1);
8826 if (!isa<ConstantSDNode>(Idx))
8829 SDValue ExtractedFromVec = I->getOperand(0);
8830 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8831 if (M == VecInMap.end()) {
8832 VT = ExtractedFromVec.getValueType();
8833 // Quit if not 128/256-bit vector.
8834 if (!VT.is128BitVector() && !VT.is256BitVector())
8836 // Quit if not the same type.
8837 if (VecInMap.begin() != VecInMap.end() &&
8838 VT != VecInMap.begin()->first.getValueType())
8840 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8842 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8845 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8846 "Not extracted from 128-/256-bit vector.");
8848 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8849 SmallVector<SDValue, 8> VecIns;
8851 for (DenseMap<SDValue, unsigned>::const_iterator
8852 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8853 // Quit if not all elements are used.
8854 if (I->second != FullMask)
8856 VecIns.push_back(I->first);
8859 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8861 // Cast all vectors into TestVT for PTEST.
8862 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8863 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8865 // If more than one full vectors are evaluated, OR them first before PTEST.
8866 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8867 // Each iteration will OR 2 nodes and append the result until there is only
8868 // 1 node left, i.e. the final OR'd value of all vectors.
8869 SDValue LHS = VecIns[Slot];
8870 SDValue RHS = VecIns[Slot + 1];
8871 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8874 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8875 VecIns.back(), VecIns.back());
8878 /// Emit nodes that will be selected as "test Op0,Op0", or something
8880 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8881 SelectionDAG &DAG) const {
8882 DebugLoc dl = Op.getDebugLoc();
8884 // CF and OF aren't always set the way we want. Determine which
8885 // of these we need.
8886 bool NeedCF = false;
8887 bool NeedOF = false;
8890 case X86::COND_A: case X86::COND_AE:
8891 case X86::COND_B: case X86::COND_BE:
8894 case X86::COND_G: case X86::COND_GE:
8895 case X86::COND_L: case X86::COND_LE:
8896 case X86::COND_O: case X86::COND_NO:
8901 // See if we can use the EFLAGS value from the operand instead of
8902 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8903 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8904 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8905 // Emit a CMP with 0, which is the TEST pattern.
8906 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8907 DAG.getConstant(0, Op.getValueType()));
8909 unsigned Opcode = 0;
8910 unsigned NumOperands = 0;
8912 // Truncate operations may prevent the merge of the SETCC instruction
8913 // and the arithmetic intruction before it. Attempt to truncate the operands
8914 // of the arithmetic instruction and use a reduced bit-width instruction.
8915 bool NeedTruncation = false;
8916 SDValue ArithOp = Op;
8917 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8918 SDValue Arith = Op->getOperand(0);
8919 // Both the trunc and the arithmetic op need to have one user each.
8920 if (Arith->hasOneUse())
8921 switch (Arith.getOpcode()) {
8928 NeedTruncation = true;
8934 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8935 // which may be the result of a CAST. We use the variable 'Op', which is the
8936 // non-casted variable when we check for possible users.
8937 switch (ArithOp.getOpcode()) {
8939 // Due to an isel shortcoming, be conservative if this add is likely to be
8940 // selected as part of a load-modify-store instruction. When the root node
8941 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8942 // uses of other nodes in the match, such as the ADD in this case. This
8943 // leads to the ADD being left around and reselected, with the result being
8944 // two adds in the output. Alas, even if none our users are stores, that
8945 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8946 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8947 // climbing the DAG back to the root, and it doesn't seem to be worth the
8949 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8950 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8951 if (UI->getOpcode() != ISD::CopyToReg &&
8952 UI->getOpcode() != ISD::SETCC &&
8953 UI->getOpcode() != ISD::STORE)
8956 if (ConstantSDNode *C =
8957 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8958 // An add of one will be selected as an INC.
8959 if (C->getAPIntValue() == 1) {
8960 Opcode = X86ISD::INC;
8965 // An add of negative one (subtract of one) will be selected as a DEC.
8966 if (C->getAPIntValue().isAllOnesValue()) {
8967 Opcode = X86ISD::DEC;
8973 // Otherwise use a regular EFLAGS-setting add.
8974 Opcode = X86ISD::ADD;
8978 // If the primary and result isn't used, don't bother using X86ISD::AND,
8979 // because a TEST instruction will be better.
8980 bool NonFlagUse = false;
8981 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8982 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8984 unsigned UOpNo = UI.getOperandNo();
8985 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8986 // Look pass truncate.
8987 UOpNo = User->use_begin().getOperandNo();
8988 User = *User->use_begin();
8991 if (User->getOpcode() != ISD::BRCOND &&
8992 User->getOpcode() != ISD::SETCC &&
8993 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9006 // Due to the ISEL shortcoming noted above, be conservative if this op is
9007 // likely to be selected as part of a load-modify-store instruction.
9008 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9009 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9010 if (UI->getOpcode() == ISD::STORE)
9013 // Otherwise use a regular EFLAGS-setting instruction.
9014 switch (ArithOp.getOpcode()) {
9015 default: llvm_unreachable("unexpected operator!");
9016 case ISD::SUB: Opcode = X86ISD::SUB; break;
9017 case ISD::XOR: Opcode = X86ISD::XOR; break;
9018 case ISD::AND: Opcode = X86ISD::AND; break;
9020 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9021 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9022 if (EFLAGS.getNode())
9025 Opcode = X86ISD::OR;
9039 return SDValue(Op.getNode(), 1);
9045 // If we found that truncation is beneficial, perform the truncation and
9047 if (NeedTruncation) {
9048 EVT VT = Op.getValueType();
9049 SDValue WideVal = Op->getOperand(0);
9050 EVT WideVT = WideVal.getValueType();
9051 unsigned ConvertedOp = 0;
9052 // Use a target machine opcode to prevent further DAGCombine
9053 // optimizations that may separate the arithmetic operations
9054 // from the setcc node.
9055 switch (WideVal.getOpcode()) {
9057 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9058 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9059 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9060 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9061 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9065 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9066 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9067 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9068 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9069 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9075 // Emit a CMP with 0, which is the TEST pattern.
9076 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9077 DAG.getConstant(0, Op.getValueType()));
9079 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9080 SmallVector<SDValue, 4> Ops;
9081 for (unsigned i = 0; i != NumOperands; ++i)
9082 Ops.push_back(Op.getOperand(i));
9084 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9085 DAG.ReplaceAllUsesWith(Op, New);
9086 return SDValue(New.getNode(), 1);
9089 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9091 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9092 SelectionDAG &DAG) const {
9093 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9094 if (C->getAPIntValue() == 0)
9095 return EmitTest(Op0, X86CC, DAG);
9097 DebugLoc dl = Op0.getDebugLoc();
9098 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9099 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9100 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9101 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9102 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9104 return SDValue(Sub.getNode(), 1);
9106 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9109 /// Convert a comparison if required by the subtarget.
9110 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9111 SelectionDAG &DAG) const {
9112 // If the subtarget does not support the FUCOMI instruction, floating-point
9113 // comparisons have to be converted.
9114 if (Subtarget->hasCMov() ||
9115 Cmp.getOpcode() != X86ISD::CMP ||
9116 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9117 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9120 // The instruction selector will select an FUCOM instruction instead of
9121 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9122 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9123 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9124 DebugLoc dl = Cmp.getDebugLoc();
9125 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9126 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9127 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9128 DAG.getConstant(8, MVT::i8));
9129 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9130 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9133 static bool isAllOnes(SDValue V) {
9134 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9135 return C && C->isAllOnesValue();
9138 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9139 /// if it's possible.
9140 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9141 DebugLoc dl, SelectionDAG &DAG) const {
9142 SDValue Op0 = And.getOperand(0);
9143 SDValue Op1 = And.getOperand(1);
9144 if (Op0.getOpcode() == ISD::TRUNCATE)
9145 Op0 = Op0.getOperand(0);
9146 if (Op1.getOpcode() == ISD::TRUNCATE)
9147 Op1 = Op1.getOperand(0);
9150 if (Op1.getOpcode() == ISD::SHL)
9151 std::swap(Op0, Op1);
9152 if (Op0.getOpcode() == ISD::SHL) {
9153 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9154 if (And00C->getZExtValue() == 1) {
9155 // If we looked past a truncate, check that it's only truncating away
9157 unsigned BitWidth = Op0.getValueSizeInBits();
9158 unsigned AndBitWidth = And.getValueSizeInBits();
9159 if (BitWidth > AndBitWidth) {
9161 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9162 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9166 RHS = Op0.getOperand(1);
9168 } else if (Op1.getOpcode() == ISD::Constant) {
9169 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9170 uint64_t AndRHSVal = AndRHS->getZExtValue();
9171 SDValue AndLHS = Op0;
9173 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9174 LHS = AndLHS.getOperand(0);
9175 RHS = AndLHS.getOperand(1);
9178 // Use BT if the immediate can't be encoded in a TEST instruction.
9179 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9181 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9185 if (LHS.getNode()) {
9186 // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9187 // the condition code later.
9188 bool Invert = false;
9189 if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9191 LHS = LHS.getOperand(0);
9194 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9195 // instruction. Since the shift amount is in-range-or-undefined, we know
9196 // that doing a bittest on the i32 value is ok. We extend to i32 because
9197 // the encoding for the i16 version is larger than the i32 version.
9198 // Also promote i16 to i32 for performance / code size reason.
9199 if (LHS.getValueType() == MVT::i8 ||
9200 LHS.getValueType() == MVT::i16)
9201 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9203 // If the operand types disagree, extend the shift amount to match. Since
9204 // BT ignores high bits (like shifts) we can use anyextend.
9205 if (LHS.getValueType() != RHS.getValueType())
9206 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9208 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9209 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9210 // Flip the condition if the LHS was a not instruction
9212 Cond = X86::GetOppositeBranchCondition(Cond);
9213 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9214 DAG.getConstant(Cond, MVT::i8), BT);
9220 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9221 // ones, and then concatenate the result back.
9222 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9223 MVT VT = Op.getValueType().getSimpleVT();
9225 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9226 "Unsupported value type for operation");
9228 unsigned NumElems = VT.getVectorNumElements();
9229 DebugLoc dl = Op.getDebugLoc();
9230 SDValue CC = Op.getOperand(2);
9232 // Extract the LHS vectors
9233 SDValue LHS = Op.getOperand(0);
9234 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9235 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9237 // Extract the RHS vectors
9238 SDValue RHS = Op.getOperand(1);
9239 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9240 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9242 // Issue the operation on the smaller types and concatenate the result back
9243 MVT EltVT = VT.getVectorElementType();
9244 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9245 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9246 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9247 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9250 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9251 SelectionDAG &DAG) {
9253 SDValue Op0 = Op.getOperand(0);
9254 SDValue Op1 = Op.getOperand(1);
9255 SDValue CC = Op.getOperand(2);
9256 MVT VT = Op.getValueType().getSimpleVT();
9257 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9258 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9259 DebugLoc dl = Op.getDebugLoc();
9263 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9264 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9270 // SSE Condition code mapping:
9279 switch (SetCCOpcode) {
9280 default: llvm_unreachable("Unexpected SETCC condition");
9282 case ISD::SETEQ: SSECC = 0; break;
9284 case ISD::SETGT: Swap = true; // Fallthrough
9286 case ISD::SETOLT: SSECC = 1; break;
9288 case ISD::SETGE: Swap = true; // Fallthrough
9290 case ISD::SETOLE: SSECC = 2; break;
9291 case ISD::SETUO: SSECC = 3; break;
9293 case ISD::SETNE: SSECC = 4; break;
9294 case ISD::SETULE: Swap = true; // Fallthrough
9295 case ISD::SETUGE: SSECC = 5; break;
9296 case ISD::SETULT: Swap = true; // Fallthrough
9297 case ISD::SETUGT: SSECC = 6; break;
9298 case ISD::SETO: SSECC = 7; break;
9300 case ISD::SETONE: SSECC = 8; break;
9303 std::swap(Op0, Op1);
9305 // In the two special cases we can't handle, emit two comparisons.
9308 unsigned CombineOpc;
9309 if (SetCCOpcode == ISD::SETUEQ) {
9310 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9312 assert(SetCCOpcode == ISD::SETONE);
9313 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9316 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9317 DAG.getConstant(CC0, MVT::i8));
9318 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9319 DAG.getConstant(CC1, MVT::i8));
9320 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9322 // Handle all other FP comparisons here.
9323 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9324 DAG.getConstant(SSECC, MVT::i8));
9327 // Break 256-bit integer vector compare into smaller ones.
9328 if (VT.is256BitVector() && !Subtarget->hasInt256())
9329 return Lower256IntVSETCC(Op, DAG);
9331 // We are handling one of the integer comparisons here. Since SSE only has
9332 // GT and EQ comparisons for integer, swapping operands and multiple
9333 // operations may be required for some comparisons.
9335 bool Swap = false, Invert = false, FlipSigns = false;
9337 switch (SetCCOpcode) {
9338 default: llvm_unreachable("Unexpected SETCC condition");
9339 case ISD::SETNE: Invert = true;
9340 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9341 case ISD::SETLT: Swap = true;
9342 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9343 case ISD::SETGE: Swap = true;
9344 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9345 case ISD::SETULT: Swap = true;
9346 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9347 case ISD::SETUGE: Swap = true;
9348 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9351 std::swap(Op0, Op1);
9353 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9354 // bits of the inputs before performing those operations.
9356 EVT EltVT = VT.getVectorElementType();
9357 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9359 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9360 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9362 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9363 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9366 // Check that the operation in question is available (most are plain SSE2,
9367 // but PCMPGTQ and PCMPEQQ have different requirements).
9368 if (VT == MVT::v2i64) {
9369 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9370 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9372 // First cast everything to the right type,
9373 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9374 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9376 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9377 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9378 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9380 // Create masks for only the low parts/high parts of the 64 bit integers.
9381 const int MaskHi[] = { 1, 1, 3, 3 };
9382 const int MaskLo[] = { 0, 0, 2, 2 };
9383 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9384 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9385 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9387 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9388 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9391 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9393 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9396 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9397 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9398 // pcmpeqd + pshufd + pand.
9399 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9401 // First cast everything to the right type,
9402 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9403 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9406 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9408 // Make sure the lower and upper halves are both all-ones.
9409 const int Mask[] = { 1, 0, 3, 2 };
9410 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9411 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9414 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9416 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9420 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9422 // If the logical-not of the result is required, perform that now.
9424 Result = DAG.getNOT(dl, Result, VT);
9429 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9431 MVT VT = Op.getValueType().getSimpleVT();
9433 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9435 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9436 SDValue Op0 = Op.getOperand(0);
9437 SDValue Op1 = Op.getOperand(1);
9438 DebugLoc dl = Op.getDebugLoc();
9439 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9441 // Optimize to BT if possible.
9442 // Lower (X & (1 << N)) == 0 to BT(X, N).
9443 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9444 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9445 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9446 Op1.getOpcode() == ISD::Constant &&
9447 cast<ConstantSDNode>(Op1)->isNullValue() &&
9448 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9449 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9450 if (NewSetCC.getNode())
9454 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9456 if (Op1.getOpcode() == ISD::Constant &&
9457 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9458 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9459 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9461 // If the input is a setcc, then reuse the input setcc or use a new one with
9462 // the inverted condition.
9463 if (Op0.getOpcode() == X86ISD::SETCC) {
9464 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9465 bool Invert = (CC == ISD::SETNE) ^
9466 cast<ConstantSDNode>(Op1)->isNullValue();
9467 if (!Invert) return Op0;
9469 CCode = X86::GetOppositeBranchCondition(CCode);
9470 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9471 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9475 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9476 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9477 if (X86CC == X86::COND_INVALID)
9480 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9481 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9482 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9483 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9486 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9487 static bool isX86LogicalCmp(SDValue Op) {
9488 unsigned Opc = Op.getNode()->getOpcode();
9489 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9490 Opc == X86ISD::SAHF)
9492 if (Op.getResNo() == 1 &&
9493 (Opc == X86ISD::ADD ||
9494 Opc == X86ISD::SUB ||
9495 Opc == X86ISD::ADC ||
9496 Opc == X86ISD::SBB ||
9497 Opc == X86ISD::SMUL ||
9498 Opc == X86ISD::UMUL ||
9499 Opc == X86ISD::INC ||
9500 Opc == X86ISD::DEC ||
9501 Opc == X86ISD::OR ||
9502 Opc == X86ISD::XOR ||
9503 Opc == X86ISD::AND))
9506 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9512 static bool isZero(SDValue V) {
9513 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9514 return C && C->isNullValue();
9517 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9518 if (V.getOpcode() != ISD::TRUNCATE)
9521 SDValue VOp0 = V.getOperand(0);
9522 unsigned InBits = VOp0.getValueSizeInBits();
9523 unsigned Bits = V.getValueSizeInBits();
9524 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9527 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9528 bool addTest = true;
9529 SDValue Cond = Op.getOperand(0);
9530 SDValue Op1 = Op.getOperand(1);
9531 SDValue Op2 = Op.getOperand(2);
9532 DebugLoc DL = Op.getDebugLoc();
9535 if (Cond.getOpcode() == ISD::SETCC) {
9536 SDValue NewCond = LowerSETCC(Cond, DAG);
9537 if (NewCond.getNode())
9541 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9542 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9543 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9544 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9545 if (Cond.getOpcode() == X86ISD::SETCC &&
9546 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9547 isZero(Cond.getOperand(1).getOperand(1))) {
9548 SDValue Cmp = Cond.getOperand(1);
9550 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9552 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9553 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9554 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9556 SDValue CmpOp0 = Cmp.getOperand(0);
9557 // Apply further optimizations for special cases
9558 // (select (x != 0), -1, 0) -> neg & sbb
9559 // (select (x == 0), 0, -1) -> neg & sbb
9560 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9561 if (YC->isNullValue() &&
9562 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9563 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9564 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9565 DAG.getConstant(0, CmpOp0.getValueType()),
9567 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9568 DAG.getConstant(X86::COND_B, MVT::i8),
9569 SDValue(Neg.getNode(), 1));
9573 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9574 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9575 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9577 SDValue Res = // Res = 0 or -1.
9578 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9579 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9581 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9582 Res = DAG.getNOT(DL, Res, Res.getValueType());
9584 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9585 if (N2C == 0 || !N2C->isNullValue())
9586 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9591 // Look past (and (setcc_carry (cmp ...)), 1).
9592 if (Cond.getOpcode() == ISD::AND &&
9593 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9594 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9595 if (C && C->getAPIntValue() == 1)
9596 Cond = Cond.getOperand(0);
9599 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9600 // setting operand in place of the X86ISD::SETCC.
9601 unsigned CondOpcode = Cond.getOpcode();
9602 if (CondOpcode == X86ISD::SETCC ||
9603 CondOpcode == X86ISD::SETCC_CARRY) {
9604 CC = Cond.getOperand(0);
9606 SDValue Cmp = Cond.getOperand(1);
9607 unsigned Opc = Cmp.getOpcode();
9608 MVT VT = Op.getValueType().getSimpleVT();
9610 bool IllegalFPCMov = false;
9611 if (VT.isFloatingPoint() && !VT.isVector() &&
9612 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9613 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9615 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9616 Opc == X86ISD::BT) { // FIXME
9620 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9621 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9622 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9623 Cond.getOperand(0).getValueType() != MVT::i8)) {
9624 SDValue LHS = Cond.getOperand(0);
9625 SDValue RHS = Cond.getOperand(1);
9629 switch (CondOpcode) {
9630 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9631 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9632 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9633 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9634 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9635 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9636 default: llvm_unreachable("unexpected overflowing operator");
9638 if (CondOpcode == ISD::UMULO)
9639 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9642 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9644 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9646 if (CondOpcode == ISD::UMULO)
9647 Cond = X86Op.getValue(2);
9649 Cond = X86Op.getValue(1);
9651 CC = DAG.getConstant(X86Cond, MVT::i8);
9656 // Look pass the truncate if the high bits are known zero.
9657 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9658 Cond = Cond.getOperand(0);
9660 // We know the result of AND is compared against zero. Try to match
9662 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9663 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9664 if (NewSetCC.getNode()) {
9665 CC = NewSetCC.getOperand(0);
9666 Cond = NewSetCC.getOperand(1);
9673 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9674 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9677 // a < b ? -1 : 0 -> RES = ~setcc_carry
9678 // a < b ? 0 : -1 -> RES = setcc_carry
9679 // a >= b ? -1 : 0 -> RES = setcc_carry
9680 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9681 if (Cond.getOpcode() == X86ISD::SUB) {
9682 Cond = ConvertCmpIfNecessary(Cond, DAG);
9683 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9685 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9686 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9687 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9688 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9689 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9690 return DAG.getNOT(DL, Res, Res.getValueType());
9695 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9696 // widen the cmov and push the truncate through. This avoids introducing a new
9697 // branch during isel and doesn't add any extensions.
9698 if (Op.getValueType() == MVT::i8 &&
9699 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9700 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9701 if (T1.getValueType() == T2.getValueType() &&
9702 // Blacklist CopyFromReg to avoid partial register stalls.
9703 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9704 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9705 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9706 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9710 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9711 // condition is true.
9712 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9713 SDValue Ops[] = { Op2, Op1, CC, Cond };
9714 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9717 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9718 SelectionDAG &DAG) const {
9719 MVT VT = Op->getValueType(0).getSimpleVT();
9720 SDValue In = Op->getOperand(0);
9721 MVT InVT = In.getValueType().getSimpleVT();
9722 DebugLoc dl = Op->getDebugLoc();
9724 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9725 (VT != MVT::v8i32 || InVT != MVT::v8i16))
9728 if (Subtarget->hasInt256())
9729 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9731 // Optimize vectors in AVX mode
9732 // Sign extend v8i16 to v8i32 and
9735 // Divide input vector into two parts
9736 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9737 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9738 // concat the vectors to original VT
9740 unsigned NumElems = InVT.getVectorNumElements();
9741 SDValue Undef = DAG.getUNDEF(InVT);
9743 SmallVector<int,8> ShufMask1(NumElems, -1);
9744 for (unsigned i = 0; i != NumElems/2; ++i)
9747 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9749 SmallVector<int,8> ShufMask2(NumElems, -1);
9750 for (unsigned i = 0; i != NumElems/2; ++i)
9751 ShufMask2[i] = i + NumElems/2;
9753 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9755 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9756 VT.getVectorNumElements()/2);
9758 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9759 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9761 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9764 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9765 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9766 // from the AND / OR.
9767 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9768 Opc = Op.getOpcode();
9769 if (Opc != ISD::OR && Opc != ISD::AND)
9771 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9772 Op.getOperand(0).hasOneUse() &&
9773 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9774 Op.getOperand(1).hasOneUse());
9777 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9778 // 1 and that the SETCC node has a single use.
9779 static bool isXor1OfSetCC(SDValue Op) {
9780 if (Op.getOpcode() != ISD::XOR)
9782 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9783 if (N1C && N1C->getAPIntValue() == 1) {
9784 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9785 Op.getOperand(0).hasOneUse();
9790 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9791 bool addTest = true;
9792 SDValue Chain = Op.getOperand(0);
9793 SDValue Cond = Op.getOperand(1);
9794 SDValue Dest = Op.getOperand(2);
9795 DebugLoc dl = Op.getDebugLoc();
9797 bool Inverted = false;
9799 if (Cond.getOpcode() == ISD::SETCC) {
9800 // Check for setcc([su]{add,sub,mul}o == 0).
9801 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9802 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9803 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9804 Cond.getOperand(0).getResNo() == 1 &&
9805 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9806 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9807 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9808 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9809 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9810 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9812 Cond = Cond.getOperand(0);
9814 SDValue NewCond = LowerSETCC(Cond, DAG);
9815 if (NewCond.getNode())
9820 // FIXME: LowerXALUO doesn't handle these!!
9821 else if (Cond.getOpcode() == X86ISD::ADD ||
9822 Cond.getOpcode() == X86ISD::SUB ||
9823 Cond.getOpcode() == X86ISD::SMUL ||
9824 Cond.getOpcode() == X86ISD::UMUL)
9825 Cond = LowerXALUO(Cond, DAG);
9828 // Look pass (and (setcc_carry (cmp ...)), 1).
9829 if (Cond.getOpcode() == ISD::AND &&
9830 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9831 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9832 if (C && C->getAPIntValue() == 1)
9833 Cond = Cond.getOperand(0);
9836 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9837 // setting operand in place of the X86ISD::SETCC.
9838 unsigned CondOpcode = Cond.getOpcode();
9839 if (CondOpcode == X86ISD::SETCC ||
9840 CondOpcode == X86ISD::SETCC_CARRY) {
9841 CC = Cond.getOperand(0);
9843 SDValue Cmp = Cond.getOperand(1);
9844 unsigned Opc = Cmp.getOpcode();
9845 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9846 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9850 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9854 // These can only come from an arithmetic instruction with overflow,
9855 // e.g. SADDO, UADDO.
9856 Cond = Cond.getNode()->getOperand(1);
9862 CondOpcode = Cond.getOpcode();
9863 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9864 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9865 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9866 Cond.getOperand(0).getValueType() != MVT::i8)) {
9867 SDValue LHS = Cond.getOperand(0);
9868 SDValue RHS = Cond.getOperand(1);
9872 switch (CondOpcode) {
9873 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9874 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9875 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9876 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9877 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9878 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9879 default: llvm_unreachable("unexpected overflowing operator");
9882 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9883 if (CondOpcode == ISD::UMULO)
9884 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9887 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9889 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9891 if (CondOpcode == ISD::UMULO)
9892 Cond = X86Op.getValue(2);
9894 Cond = X86Op.getValue(1);
9896 CC = DAG.getConstant(X86Cond, MVT::i8);
9900 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9901 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9902 if (CondOpc == ISD::OR) {
9903 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9904 // two branches instead of an explicit OR instruction with a
9906 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9907 isX86LogicalCmp(Cmp)) {
9908 CC = Cond.getOperand(0).getOperand(0);
9909 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9910 Chain, Dest, CC, Cmp);
9911 CC = Cond.getOperand(1).getOperand(0);
9915 } else { // ISD::AND
9916 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9917 // two branches instead of an explicit AND instruction with a
9918 // separate test. However, we only do this if this block doesn't
9919 // have a fall-through edge, because this requires an explicit
9920 // jmp when the condition is false.
9921 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9922 isX86LogicalCmp(Cmp) &&
9923 Op.getNode()->hasOneUse()) {
9924 X86::CondCode CCode =
9925 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9926 CCode = X86::GetOppositeBranchCondition(CCode);
9927 CC = DAG.getConstant(CCode, MVT::i8);
9928 SDNode *User = *Op.getNode()->use_begin();
9929 // Look for an unconditional branch following this conditional branch.
9930 // We need this because we need to reverse the successors in order
9931 // to implement FCMP_OEQ.
9932 if (User->getOpcode() == ISD::BR) {
9933 SDValue FalseBB = User->getOperand(1);
9935 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9936 assert(NewBR == User);
9940 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9941 Chain, Dest, CC, Cmp);
9942 X86::CondCode CCode =
9943 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9944 CCode = X86::GetOppositeBranchCondition(CCode);
9945 CC = DAG.getConstant(CCode, MVT::i8);
9951 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9952 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9953 // It should be transformed during dag combiner except when the condition
9954 // is set by a arithmetics with overflow node.
9955 X86::CondCode CCode =
9956 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9957 CCode = X86::GetOppositeBranchCondition(CCode);
9958 CC = DAG.getConstant(CCode, MVT::i8);
9959 Cond = Cond.getOperand(0).getOperand(1);
9961 } else if (Cond.getOpcode() == ISD::SETCC &&
9962 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9963 // For FCMP_OEQ, we can emit
9964 // two branches instead of an explicit AND instruction with a
9965 // separate test. However, we only do this if this block doesn't
9966 // have a fall-through edge, because this requires an explicit
9967 // jmp when the condition is false.
9968 if (Op.getNode()->hasOneUse()) {
9969 SDNode *User = *Op.getNode()->use_begin();
9970 // Look for an unconditional branch following this conditional branch.
9971 // We need this because we need to reverse the successors in order
9972 // to implement FCMP_OEQ.
9973 if (User->getOpcode() == ISD::BR) {
9974 SDValue FalseBB = User->getOperand(1);
9976 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9977 assert(NewBR == User);
9981 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9982 Cond.getOperand(0), Cond.getOperand(1));
9983 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9984 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9985 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9986 Chain, Dest, CC, Cmp);
9987 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9992 } else if (Cond.getOpcode() == ISD::SETCC &&
9993 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9994 // For FCMP_UNE, we can emit
9995 // two branches instead of an explicit AND instruction with a
9996 // separate test. However, we only do this if this block doesn't
9997 // have a fall-through edge, because this requires an explicit
9998 // jmp when the condition is false.
9999 if (Op.getNode()->hasOneUse()) {
10000 SDNode *User = *Op.getNode()->use_begin();
10001 // Look for an unconditional branch following this conditional branch.
10002 // We need this because we need to reverse the successors in order
10003 // to implement FCMP_UNE.
10004 if (User->getOpcode() == ISD::BR) {
10005 SDValue FalseBB = User->getOperand(1);
10007 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10008 assert(NewBR == User);
10011 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10012 Cond.getOperand(0), Cond.getOperand(1));
10013 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10014 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10015 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10016 Chain, Dest, CC, Cmp);
10017 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10027 // Look pass the truncate if the high bits are known zero.
10028 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10029 Cond = Cond.getOperand(0);
10031 // We know the result of AND is compared against zero. Try to match
10033 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10034 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10035 if (NewSetCC.getNode()) {
10036 CC = NewSetCC.getOperand(0);
10037 Cond = NewSetCC.getOperand(1);
10044 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10045 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10047 Cond = ConvertCmpIfNecessary(Cond, DAG);
10048 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10049 Chain, Dest, CC, Cond);
10052 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10053 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10054 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10055 // that the guard pages used by the OS virtual memory manager are allocated in
10056 // correct sequence.
10058 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10059 SelectionDAG &DAG) const {
10060 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10061 getTargetMachine().Options.EnableSegmentedStacks) &&
10062 "This should be used only on Windows targets or when segmented stacks "
10064 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10065 DebugLoc dl = Op.getDebugLoc();
10068 SDValue Chain = Op.getOperand(0);
10069 SDValue Size = Op.getOperand(1);
10070 // FIXME: Ensure alignment here
10072 bool Is64Bit = Subtarget->is64Bit();
10073 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10075 if (getTargetMachine().Options.EnableSegmentedStacks) {
10076 MachineFunction &MF = DAG.getMachineFunction();
10077 MachineRegisterInfo &MRI = MF.getRegInfo();
10080 // The 64 bit implementation of segmented stacks needs to clobber both r10
10081 // r11. This makes it impossible to use it along with nested parameters.
10082 const Function *F = MF.getFunction();
10084 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10086 if (I->hasNestAttr())
10087 report_fatal_error("Cannot use segmented stacks with functions that "
10088 "have nested arguments.");
10091 const TargetRegisterClass *AddrRegClass =
10092 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10093 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10094 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10095 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10096 DAG.getRegister(Vreg, SPTy));
10097 SDValue Ops1[2] = { Value, Chain };
10098 return DAG.getMergeValues(Ops1, 2, dl);
10101 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10103 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10104 Flag = Chain.getValue(1);
10105 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10107 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10108 Flag = Chain.getValue(1);
10110 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10113 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10114 return DAG.getMergeValues(Ops1, 2, dl);
10118 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10119 MachineFunction &MF = DAG.getMachineFunction();
10120 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10122 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10123 DebugLoc DL = Op.getDebugLoc();
10125 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10126 // vastart just stores the address of the VarArgsFrameIndex slot into the
10127 // memory location argument.
10128 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10130 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10131 MachinePointerInfo(SV), false, false, 0);
10135 // gp_offset (0 - 6 * 8)
10136 // fp_offset (48 - 48 + 8 * 16)
10137 // overflow_arg_area (point to parameters coming in memory).
10139 SmallVector<SDValue, 8> MemOps;
10140 SDValue FIN = Op.getOperand(1);
10142 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10143 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10145 FIN, MachinePointerInfo(SV), false, false, 0);
10146 MemOps.push_back(Store);
10149 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10150 FIN, DAG.getIntPtrConstant(4));
10151 Store = DAG.getStore(Op.getOperand(0), DL,
10152 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10154 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10155 MemOps.push_back(Store);
10157 // Store ptr to overflow_arg_area
10158 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10159 FIN, DAG.getIntPtrConstant(4));
10160 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10162 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10163 MachinePointerInfo(SV, 8),
10165 MemOps.push_back(Store);
10167 // Store ptr to reg_save_area.
10168 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10169 FIN, DAG.getIntPtrConstant(8));
10170 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10172 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10173 MachinePointerInfo(SV, 16), false, false, 0);
10174 MemOps.push_back(Store);
10175 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10176 &MemOps[0], MemOps.size());
10179 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10180 assert(Subtarget->is64Bit() &&
10181 "LowerVAARG only handles 64-bit va_arg!");
10182 assert((Subtarget->isTargetLinux() ||
10183 Subtarget->isTargetDarwin()) &&
10184 "Unhandled target in LowerVAARG");
10185 assert(Op.getNode()->getNumOperands() == 4);
10186 SDValue Chain = Op.getOperand(0);
10187 SDValue SrcPtr = Op.getOperand(1);
10188 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10189 unsigned Align = Op.getConstantOperandVal(3);
10190 DebugLoc dl = Op.getDebugLoc();
10192 EVT ArgVT = Op.getNode()->getValueType(0);
10193 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10194 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10197 // Decide which area this value should be read from.
10198 // TODO: Implement the AMD64 ABI in its entirety. This simple
10199 // selection mechanism works only for the basic types.
10200 if (ArgVT == MVT::f80) {
10201 llvm_unreachable("va_arg for f80 not yet implemented");
10202 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10203 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10204 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10205 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10207 llvm_unreachable("Unhandled argument type in LowerVAARG");
10210 if (ArgMode == 2) {
10211 // Sanity Check: Make sure using fp_offset makes sense.
10212 assert(!getTargetMachine().Options.UseSoftFloat &&
10213 !(DAG.getMachineFunction()
10214 .getFunction()->getAttributes()
10215 .hasAttribute(AttributeSet::FunctionIndex,
10216 Attribute::NoImplicitFloat)) &&
10217 Subtarget->hasSSE1());
10220 // Insert VAARG_64 node into the DAG
10221 // VAARG_64 returns two values: Variable Argument Address, Chain
10222 SmallVector<SDValue, 11> InstOps;
10223 InstOps.push_back(Chain);
10224 InstOps.push_back(SrcPtr);
10225 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10226 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10227 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10228 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10229 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10230 VTs, &InstOps[0], InstOps.size(),
10232 MachinePointerInfo(SV),
10234 /*Volatile=*/false,
10236 /*WriteMem=*/true);
10237 Chain = VAARG.getValue(1);
10239 // Load the next argument and return it
10240 return DAG.getLoad(ArgVT, dl,
10243 MachinePointerInfo(),
10244 false, false, false, 0);
10247 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10248 SelectionDAG &DAG) {
10249 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10250 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10251 SDValue Chain = Op.getOperand(0);
10252 SDValue DstPtr = Op.getOperand(1);
10253 SDValue SrcPtr = Op.getOperand(2);
10254 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10255 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10256 DebugLoc DL = Op.getDebugLoc();
10258 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10259 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10261 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10264 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10265 // may or may not be a constant. Takes immediate version of shift as input.
10266 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10267 SDValue SrcOp, SDValue ShAmt,
10268 SelectionDAG &DAG) {
10269 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10271 if (isa<ConstantSDNode>(ShAmt)) {
10272 // Constant may be a TargetConstant. Use a regular constant.
10273 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10275 default: llvm_unreachable("Unknown target vector shift node");
10276 case X86ISD::VSHLI:
10277 case X86ISD::VSRLI:
10278 case X86ISD::VSRAI:
10279 return DAG.getNode(Opc, dl, VT, SrcOp,
10280 DAG.getConstant(ShiftAmt, MVT::i32));
10284 // Change opcode to non-immediate version
10286 default: llvm_unreachable("Unknown target vector shift node");
10287 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10288 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10289 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10292 // Need to build a vector containing shift amount
10293 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10296 ShOps[1] = DAG.getConstant(0, MVT::i32);
10297 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10298 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10300 // The return type has to be a 128-bit type with the same element
10301 // type as the input type.
10302 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10303 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10305 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10306 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10309 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10310 DebugLoc dl = Op.getDebugLoc();
10311 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10313 default: return SDValue(); // Don't custom lower most intrinsics.
10314 // Comparison intrinsics.
10315 case Intrinsic::x86_sse_comieq_ss:
10316 case Intrinsic::x86_sse_comilt_ss:
10317 case Intrinsic::x86_sse_comile_ss:
10318 case Intrinsic::x86_sse_comigt_ss:
10319 case Intrinsic::x86_sse_comige_ss:
10320 case Intrinsic::x86_sse_comineq_ss:
10321 case Intrinsic::x86_sse_ucomieq_ss:
10322 case Intrinsic::x86_sse_ucomilt_ss:
10323 case Intrinsic::x86_sse_ucomile_ss:
10324 case Intrinsic::x86_sse_ucomigt_ss:
10325 case Intrinsic::x86_sse_ucomige_ss:
10326 case Intrinsic::x86_sse_ucomineq_ss:
10327 case Intrinsic::x86_sse2_comieq_sd:
10328 case Intrinsic::x86_sse2_comilt_sd:
10329 case Intrinsic::x86_sse2_comile_sd:
10330 case Intrinsic::x86_sse2_comigt_sd:
10331 case Intrinsic::x86_sse2_comige_sd:
10332 case Intrinsic::x86_sse2_comineq_sd:
10333 case Intrinsic::x86_sse2_ucomieq_sd:
10334 case Intrinsic::x86_sse2_ucomilt_sd:
10335 case Intrinsic::x86_sse2_ucomile_sd:
10336 case Intrinsic::x86_sse2_ucomigt_sd:
10337 case Intrinsic::x86_sse2_ucomige_sd:
10338 case Intrinsic::x86_sse2_ucomineq_sd: {
10342 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10343 case Intrinsic::x86_sse_comieq_ss:
10344 case Intrinsic::x86_sse2_comieq_sd:
10345 Opc = X86ISD::COMI;
10348 case Intrinsic::x86_sse_comilt_ss:
10349 case Intrinsic::x86_sse2_comilt_sd:
10350 Opc = X86ISD::COMI;
10353 case Intrinsic::x86_sse_comile_ss:
10354 case Intrinsic::x86_sse2_comile_sd:
10355 Opc = X86ISD::COMI;
10358 case Intrinsic::x86_sse_comigt_ss:
10359 case Intrinsic::x86_sse2_comigt_sd:
10360 Opc = X86ISD::COMI;
10363 case Intrinsic::x86_sse_comige_ss:
10364 case Intrinsic::x86_sse2_comige_sd:
10365 Opc = X86ISD::COMI;
10368 case Intrinsic::x86_sse_comineq_ss:
10369 case Intrinsic::x86_sse2_comineq_sd:
10370 Opc = X86ISD::COMI;
10373 case Intrinsic::x86_sse_ucomieq_ss:
10374 case Intrinsic::x86_sse2_ucomieq_sd:
10375 Opc = X86ISD::UCOMI;
10378 case Intrinsic::x86_sse_ucomilt_ss:
10379 case Intrinsic::x86_sse2_ucomilt_sd:
10380 Opc = X86ISD::UCOMI;
10383 case Intrinsic::x86_sse_ucomile_ss:
10384 case Intrinsic::x86_sse2_ucomile_sd:
10385 Opc = X86ISD::UCOMI;
10388 case Intrinsic::x86_sse_ucomigt_ss:
10389 case Intrinsic::x86_sse2_ucomigt_sd:
10390 Opc = X86ISD::UCOMI;
10393 case Intrinsic::x86_sse_ucomige_ss:
10394 case Intrinsic::x86_sse2_ucomige_sd:
10395 Opc = X86ISD::UCOMI;
10398 case Intrinsic::x86_sse_ucomineq_ss:
10399 case Intrinsic::x86_sse2_ucomineq_sd:
10400 Opc = X86ISD::UCOMI;
10405 SDValue LHS = Op.getOperand(1);
10406 SDValue RHS = Op.getOperand(2);
10407 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10408 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10409 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10410 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10411 DAG.getConstant(X86CC, MVT::i8), Cond);
10412 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10415 // Arithmetic intrinsics.
10416 case Intrinsic::x86_sse2_pmulu_dq:
10417 case Intrinsic::x86_avx2_pmulu_dq:
10418 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10419 Op.getOperand(1), Op.getOperand(2));
10421 // SSE2/AVX2 sub with unsigned saturation intrinsics
10422 case Intrinsic::x86_sse2_psubus_b:
10423 case Intrinsic::x86_sse2_psubus_w:
10424 case Intrinsic::x86_avx2_psubus_b:
10425 case Intrinsic::x86_avx2_psubus_w:
10426 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10427 Op.getOperand(1), Op.getOperand(2));
10429 // SSE3/AVX horizontal add/sub intrinsics
10430 case Intrinsic::x86_sse3_hadd_ps:
10431 case Intrinsic::x86_sse3_hadd_pd:
10432 case Intrinsic::x86_avx_hadd_ps_256:
10433 case Intrinsic::x86_avx_hadd_pd_256:
10434 case Intrinsic::x86_sse3_hsub_ps:
10435 case Intrinsic::x86_sse3_hsub_pd:
10436 case Intrinsic::x86_avx_hsub_ps_256:
10437 case Intrinsic::x86_avx_hsub_pd_256:
10438 case Intrinsic::x86_ssse3_phadd_w_128:
10439 case Intrinsic::x86_ssse3_phadd_d_128:
10440 case Intrinsic::x86_avx2_phadd_w:
10441 case Intrinsic::x86_avx2_phadd_d:
10442 case Intrinsic::x86_ssse3_phsub_w_128:
10443 case Intrinsic::x86_ssse3_phsub_d_128:
10444 case Intrinsic::x86_avx2_phsub_w:
10445 case Intrinsic::x86_avx2_phsub_d: {
10448 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10449 case Intrinsic::x86_sse3_hadd_ps:
10450 case Intrinsic::x86_sse3_hadd_pd:
10451 case Intrinsic::x86_avx_hadd_ps_256:
10452 case Intrinsic::x86_avx_hadd_pd_256:
10453 Opcode = X86ISD::FHADD;
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 Opcode = X86ISD::FHSUB;
10461 case Intrinsic::x86_ssse3_phadd_w_128:
10462 case Intrinsic::x86_ssse3_phadd_d_128:
10463 case Intrinsic::x86_avx2_phadd_w:
10464 case Intrinsic::x86_avx2_phadd_d:
10465 Opcode = X86ISD::HADD;
10467 case Intrinsic::x86_ssse3_phsub_w_128:
10468 case Intrinsic::x86_ssse3_phsub_d_128:
10469 case Intrinsic::x86_avx2_phsub_w:
10470 case Intrinsic::x86_avx2_phsub_d:
10471 Opcode = X86ISD::HSUB;
10474 return DAG.getNode(Opcode, dl, Op.getValueType(),
10475 Op.getOperand(1), Op.getOperand(2));
10478 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10479 case Intrinsic::x86_sse2_pmaxu_b:
10480 case Intrinsic::x86_sse41_pmaxuw:
10481 case Intrinsic::x86_sse41_pmaxud:
10482 case Intrinsic::x86_avx2_pmaxu_b:
10483 case Intrinsic::x86_avx2_pmaxu_w:
10484 case Intrinsic::x86_avx2_pmaxu_d:
10485 case Intrinsic::x86_sse2_pminu_b:
10486 case Intrinsic::x86_sse41_pminuw:
10487 case Intrinsic::x86_sse41_pminud:
10488 case Intrinsic::x86_avx2_pminu_b:
10489 case Intrinsic::x86_avx2_pminu_w:
10490 case Intrinsic::x86_avx2_pminu_d:
10491 case Intrinsic::x86_sse41_pmaxsb:
10492 case Intrinsic::x86_sse2_pmaxs_w:
10493 case Intrinsic::x86_sse41_pmaxsd:
10494 case Intrinsic::x86_avx2_pmaxs_b:
10495 case Intrinsic::x86_avx2_pmaxs_w:
10496 case Intrinsic::x86_avx2_pmaxs_d:
10497 case Intrinsic::x86_sse41_pminsb:
10498 case Intrinsic::x86_sse2_pmins_w:
10499 case Intrinsic::x86_sse41_pminsd:
10500 case Intrinsic::x86_avx2_pmins_b:
10501 case Intrinsic::x86_avx2_pmins_w:
10502 case Intrinsic::x86_avx2_pmins_d: {
10505 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10506 case Intrinsic::x86_sse2_pmaxu_b:
10507 case Intrinsic::x86_sse41_pmaxuw:
10508 case Intrinsic::x86_sse41_pmaxud:
10509 case Intrinsic::x86_avx2_pmaxu_b:
10510 case Intrinsic::x86_avx2_pmaxu_w:
10511 case Intrinsic::x86_avx2_pmaxu_d:
10512 Opcode = X86ISD::UMAX;
10514 case Intrinsic::x86_sse2_pminu_b:
10515 case Intrinsic::x86_sse41_pminuw:
10516 case Intrinsic::x86_sse41_pminud:
10517 case Intrinsic::x86_avx2_pminu_b:
10518 case Intrinsic::x86_avx2_pminu_w:
10519 case Intrinsic::x86_avx2_pminu_d:
10520 Opcode = X86ISD::UMIN;
10522 case Intrinsic::x86_sse41_pmaxsb:
10523 case Intrinsic::x86_sse2_pmaxs_w:
10524 case Intrinsic::x86_sse41_pmaxsd:
10525 case Intrinsic::x86_avx2_pmaxs_b:
10526 case Intrinsic::x86_avx2_pmaxs_w:
10527 case Intrinsic::x86_avx2_pmaxs_d:
10528 Opcode = X86ISD::SMAX;
10530 case Intrinsic::x86_sse41_pminsb:
10531 case Intrinsic::x86_sse2_pmins_w:
10532 case Intrinsic::x86_sse41_pminsd:
10533 case Intrinsic::x86_avx2_pmins_b:
10534 case Intrinsic::x86_avx2_pmins_w:
10535 case Intrinsic::x86_avx2_pmins_d:
10536 Opcode = X86ISD::SMIN;
10539 return DAG.getNode(Opcode, dl, Op.getValueType(),
10540 Op.getOperand(1), Op.getOperand(2));
10543 // SSE/SSE2/AVX floating point max/min intrinsics.
10544 case Intrinsic::x86_sse_max_ps:
10545 case Intrinsic::x86_sse2_max_pd:
10546 case Intrinsic::x86_avx_max_ps_256:
10547 case Intrinsic::x86_avx_max_pd_256:
10548 case Intrinsic::x86_sse_min_ps:
10549 case Intrinsic::x86_sse2_min_pd:
10550 case Intrinsic::x86_avx_min_ps_256:
10551 case Intrinsic::x86_avx_min_pd_256: {
10554 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10555 case Intrinsic::x86_sse_max_ps:
10556 case Intrinsic::x86_sse2_max_pd:
10557 case Intrinsic::x86_avx_max_ps_256:
10558 case Intrinsic::x86_avx_max_pd_256:
10559 Opcode = X86ISD::FMAX;
10561 case Intrinsic::x86_sse_min_ps:
10562 case Intrinsic::x86_sse2_min_pd:
10563 case Intrinsic::x86_avx_min_ps_256:
10564 case Intrinsic::x86_avx_min_pd_256:
10565 Opcode = X86ISD::FMIN;
10568 return DAG.getNode(Opcode, dl, Op.getValueType(),
10569 Op.getOperand(1), Op.getOperand(2));
10572 // AVX2 variable shift intrinsics
10573 case Intrinsic::x86_avx2_psllv_d:
10574 case Intrinsic::x86_avx2_psllv_q:
10575 case Intrinsic::x86_avx2_psllv_d_256:
10576 case Intrinsic::x86_avx2_psllv_q_256:
10577 case Intrinsic::x86_avx2_psrlv_d:
10578 case Intrinsic::x86_avx2_psrlv_q:
10579 case Intrinsic::x86_avx2_psrlv_d_256:
10580 case Intrinsic::x86_avx2_psrlv_q_256:
10581 case Intrinsic::x86_avx2_psrav_d:
10582 case Intrinsic::x86_avx2_psrav_d_256: {
10585 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10586 case Intrinsic::x86_avx2_psllv_d:
10587 case Intrinsic::x86_avx2_psllv_q:
10588 case Intrinsic::x86_avx2_psllv_d_256:
10589 case Intrinsic::x86_avx2_psllv_q_256:
10592 case Intrinsic::x86_avx2_psrlv_d:
10593 case Intrinsic::x86_avx2_psrlv_q:
10594 case Intrinsic::x86_avx2_psrlv_d_256:
10595 case Intrinsic::x86_avx2_psrlv_q_256:
10598 case Intrinsic::x86_avx2_psrav_d:
10599 case Intrinsic::x86_avx2_psrav_d_256:
10603 return DAG.getNode(Opcode, dl, Op.getValueType(),
10604 Op.getOperand(1), Op.getOperand(2));
10607 case Intrinsic::x86_ssse3_pshuf_b_128:
10608 case Intrinsic::x86_avx2_pshuf_b:
10609 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10610 Op.getOperand(1), Op.getOperand(2));
10612 case Intrinsic::x86_ssse3_psign_b_128:
10613 case Intrinsic::x86_ssse3_psign_w_128:
10614 case Intrinsic::x86_ssse3_psign_d_128:
10615 case Intrinsic::x86_avx2_psign_b:
10616 case Intrinsic::x86_avx2_psign_w:
10617 case Intrinsic::x86_avx2_psign_d:
10618 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10619 Op.getOperand(1), Op.getOperand(2));
10621 case Intrinsic::x86_sse41_insertps:
10622 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10623 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10625 case Intrinsic::x86_avx_vperm2f128_ps_256:
10626 case Intrinsic::x86_avx_vperm2f128_pd_256:
10627 case Intrinsic::x86_avx_vperm2f128_si_256:
10628 case Intrinsic::x86_avx2_vperm2i128:
10629 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10630 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10632 case Intrinsic::x86_avx2_permd:
10633 case Intrinsic::x86_avx2_permps:
10634 // Operands intentionally swapped. Mask is last operand to intrinsic,
10635 // but second operand for node/intruction.
10636 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10637 Op.getOperand(2), Op.getOperand(1));
10639 case Intrinsic::x86_sse_sqrt_ps:
10640 case Intrinsic::x86_sse2_sqrt_pd:
10641 case Intrinsic::x86_avx_sqrt_ps_256:
10642 case Intrinsic::x86_avx_sqrt_pd_256:
10643 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10645 // ptest and testp intrinsics. The intrinsic these come from are designed to
10646 // return an integer value, not just an instruction so lower it to the ptest
10647 // or testp pattern and a setcc for the result.
10648 case Intrinsic::x86_sse41_ptestz:
10649 case Intrinsic::x86_sse41_ptestc:
10650 case Intrinsic::x86_sse41_ptestnzc:
10651 case Intrinsic::x86_avx_ptestz_256:
10652 case Intrinsic::x86_avx_ptestc_256:
10653 case Intrinsic::x86_avx_ptestnzc_256:
10654 case Intrinsic::x86_avx_vtestz_ps:
10655 case Intrinsic::x86_avx_vtestc_ps:
10656 case Intrinsic::x86_avx_vtestnzc_ps:
10657 case Intrinsic::x86_avx_vtestz_pd:
10658 case Intrinsic::x86_avx_vtestc_pd:
10659 case Intrinsic::x86_avx_vtestnzc_pd:
10660 case Intrinsic::x86_avx_vtestz_ps_256:
10661 case Intrinsic::x86_avx_vtestc_ps_256:
10662 case Intrinsic::x86_avx_vtestnzc_ps_256:
10663 case Intrinsic::x86_avx_vtestz_pd_256:
10664 case Intrinsic::x86_avx_vtestc_pd_256:
10665 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10666 bool IsTestPacked = false;
10669 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10670 case Intrinsic::x86_avx_vtestz_ps:
10671 case Intrinsic::x86_avx_vtestz_pd:
10672 case Intrinsic::x86_avx_vtestz_ps_256:
10673 case Intrinsic::x86_avx_vtestz_pd_256:
10674 IsTestPacked = true; // Fallthrough
10675 case Intrinsic::x86_sse41_ptestz:
10676 case Intrinsic::x86_avx_ptestz_256:
10678 X86CC = X86::COND_E;
10680 case Intrinsic::x86_avx_vtestc_ps:
10681 case Intrinsic::x86_avx_vtestc_pd:
10682 case Intrinsic::x86_avx_vtestc_ps_256:
10683 case Intrinsic::x86_avx_vtestc_pd_256:
10684 IsTestPacked = true; // Fallthrough
10685 case Intrinsic::x86_sse41_ptestc:
10686 case Intrinsic::x86_avx_ptestc_256:
10688 X86CC = X86::COND_B;
10690 case Intrinsic::x86_avx_vtestnzc_ps:
10691 case Intrinsic::x86_avx_vtestnzc_pd:
10692 case Intrinsic::x86_avx_vtestnzc_ps_256:
10693 case Intrinsic::x86_avx_vtestnzc_pd_256:
10694 IsTestPacked = true; // Fallthrough
10695 case Intrinsic::x86_sse41_ptestnzc:
10696 case Intrinsic::x86_avx_ptestnzc_256:
10698 X86CC = X86::COND_A;
10702 SDValue LHS = Op.getOperand(1);
10703 SDValue RHS = Op.getOperand(2);
10704 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10705 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10706 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10707 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10708 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10711 // SSE/AVX shift intrinsics
10712 case Intrinsic::x86_sse2_psll_w:
10713 case Intrinsic::x86_sse2_psll_d:
10714 case Intrinsic::x86_sse2_psll_q:
10715 case Intrinsic::x86_avx2_psll_w:
10716 case Intrinsic::x86_avx2_psll_d:
10717 case Intrinsic::x86_avx2_psll_q:
10718 case Intrinsic::x86_sse2_psrl_w:
10719 case Intrinsic::x86_sse2_psrl_d:
10720 case Intrinsic::x86_sse2_psrl_q:
10721 case Intrinsic::x86_avx2_psrl_w:
10722 case Intrinsic::x86_avx2_psrl_d:
10723 case Intrinsic::x86_avx2_psrl_q:
10724 case Intrinsic::x86_sse2_psra_w:
10725 case Intrinsic::x86_sse2_psra_d:
10726 case Intrinsic::x86_avx2_psra_w:
10727 case Intrinsic::x86_avx2_psra_d: {
10730 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10731 case Intrinsic::x86_sse2_psll_w:
10732 case Intrinsic::x86_sse2_psll_d:
10733 case Intrinsic::x86_sse2_psll_q:
10734 case Intrinsic::x86_avx2_psll_w:
10735 case Intrinsic::x86_avx2_psll_d:
10736 case Intrinsic::x86_avx2_psll_q:
10737 Opcode = X86ISD::VSHL;
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 Opcode = X86ISD::VSRL;
10747 case Intrinsic::x86_sse2_psra_w:
10748 case Intrinsic::x86_sse2_psra_d:
10749 case Intrinsic::x86_avx2_psra_w:
10750 case Intrinsic::x86_avx2_psra_d:
10751 Opcode = X86ISD::VSRA;
10754 return DAG.getNode(Opcode, dl, Op.getValueType(),
10755 Op.getOperand(1), Op.getOperand(2));
10758 // SSE/AVX immediate shift intrinsics
10759 case Intrinsic::x86_sse2_pslli_w:
10760 case Intrinsic::x86_sse2_pslli_d:
10761 case Intrinsic::x86_sse2_pslli_q:
10762 case Intrinsic::x86_avx2_pslli_w:
10763 case Intrinsic::x86_avx2_pslli_d:
10764 case Intrinsic::x86_avx2_pslli_q:
10765 case Intrinsic::x86_sse2_psrli_w:
10766 case Intrinsic::x86_sse2_psrli_d:
10767 case Intrinsic::x86_sse2_psrli_q:
10768 case Intrinsic::x86_avx2_psrli_w:
10769 case Intrinsic::x86_avx2_psrli_d:
10770 case Intrinsic::x86_avx2_psrli_q:
10771 case Intrinsic::x86_sse2_psrai_w:
10772 case Intrinsic::x86_sse2_psrai_d:
10773 case Intrinsic::x86_avx2_psrai_w:
10774 case Intrinsic::x86_avx2_psrai_d: {
10777 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10778 case Intrinsic::x86_sse2_pslli_w:
10779 case Intrinsic::x86_sse2_pslli_d:
10780 case Intrinsic::x86_sse2_pslli_q:
10781 case Intrinsic::x86_avx2_pslli_w:
10782 case Intrinsic::x86_avx2_pslli_d:
10783 case Intrinsic::x86_avx2_pslli_q:
10784 Opcode = X86ISD::VSHLI;
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 Opcode = X86ISD::VSRLI;
10794 case Intrinsic::x86_sse2_psrai_w:
10795 case Intrinsic::x86_sse2_psrai_d:
10796 case Intrinsic::x86_avx2_psrai_w:
10797 case Intrinsic::x86_avx2_psrai_d:
10798 Opcode = X86ISD::VSRAI;
10801 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10802 Op.getOperand(1), Op.getOperand(2), DAG);
10805 case Intrinsic::x86_sse42_pcmpistria128:
10806 case Intrinsic::x86_sse42_pcmpestria128:
10807 case Intrinsic::x86_sse42_pcmpistric128:
10808 case Intrinsic::x86_sse42_pcmpestric128:
10809 case Intrinsic::x86_sse42_pcmpistrio128:
10810 case Intrinsic::x86_sse42_pcmpestrio128:
10811 case Intrinsic::x86_sse42_pcmpistris128:
10812 case Intrinsic::x86_sse42_pcmpestris128:
10813 case Intrinsic::x86_sse42_pcmpistriz128:
10814 case Intrinsic::x86_sse42_pcmpestriz128: {
10818 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10819 case Intrinsic::x86_sse42_pcmpistria128:
10820 Opcode = X86ISD::PCMPISTRI;
10821 X86CC = X86::COND_A;
10823 case Intrinsic::x86_sse42_pcmpestria128:
10824 Opcode = X86ISD::PCMPESTRI;
10825 X86CC = X86::COND_A;
10827 case Intrinsic::x86_sse42_pcmpistric128:
10828 Opcode = X86ISD::PCMPISTRI;
10829 X86CC = X86::COND_B;
10831 case Intrinsic::x86_sse42_pcmpestric128:
10832 Opcode = X86ISD::PCMPESTRI;
10833 X86CC = X86::COND_B;
10835 case Intrinsic::x86_sse42_pcmpistrio128:
10836 Opcode = X86ISD::PCMPISTRI;
10837 X86CC = X86::COND_O;
10839 case Intrinsic::x86_sse42_pcmpestrio128:
10840 Opcode = X86ISD::PCMPESTRI;
10841 X86CC = X86::COND_O;
10843 case Intrinsic::x86_sse42_pcmpistris128:
10844 Opcode = X86ISD::PCMPISTRI;
10845 X86CC = X86::COND_S;
10847 case Intrinsic::x86_sse42_pcmpestris128:
10848 Opcode = X86ISD::PCMPESTRI;
10849 X86CC = X86::COND_S;
10851 case Intrinsic::x86_sse42_pcmpistriz128:
10852 Opcode = X86ISD::PCMPISTRI;
10853 X86CC = X86::COND_E;
10855 case Intrinsic::x86_sse42_pcmpestriz128:
10856 Opcode = X86ISD::PCMPESTRI;
10857 X86CC = X86::COND_E;
10860 SmallVector<SDValue, 5> NewOps;
10861 NewOps.append(Op->op_begin()+1, Op->op_end());
10862 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10863 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10864 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10865 DAG.getConstant(X86CC, MVT::i8),
10866 SDValue(PCMP.getNode(), 1));
10867 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10870 case Intrinsic::x86_sse42_pcmpistri128:
10871 case Intrinsic::x86_sse42_pcmpestri128: {
10873 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10874 Opcode = X86ISD::PCMPISTRI;
10876 Opcode = X86ISD::PCMPESTRI;
10878 SmallVector<SDValue, 5> NewOps;
10879 NewOps.append(Op->op_begin()+1, Op->op_end());
10880 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10881 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10883 case Intrinsic::x86_fma_vfmadd_ps:
10884 case Intrinsic::x86_fma_vfmadd_pd:
10885 case Intrinsic::x86_fma_vfmsub_ps:
10886 case Intrinsic::x86_fma_vfmsub_pd:
10887 case Intrinsic::x86_fma_vfnmadd_ps:
10888 case Intrinsic::x86_fma_vfnmadd_pd:
10889 case Intrinsic::x86_fma_vfnmsub_ps:
10890 case Intrinsic::x86_fma_vfnmsub_pd:
10891 case Intrinsic::x86_fma_vfmaddsub_ps:
10892 case Intrinsic::x86_fma_vfmaddsub_pd:
10893 case Intrinsic::x86_fma_vfmsubadd_ps:
10894 case Intrinsic::x86_fma_vfmsubadd_pd:
10895 case Intrinsic::x86_fma_vfmadd_ps_256:
10896 case Intrinsic::x86_fma_vfmadd_pd_256:
10897 case Intrinsic::x86_fma_vfmsub_ps_256:
10898 case Intrinsic::x86_fma_vfmsub_pd_256:
10899 case Intrinsic::x86_fma_vfnmadd_ps_256:
10900 case Intrinsic::x86_fma_vfnmadd_pd_256:
10901 case Intrinsic::x86_fma_vfnmsub_ps_256:
10902 case Intrinsic::x86_fma_vfnmsub_pd_256:
10903 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10904 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10905 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10906 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10909 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10910 case Intrinsic::x86_fma_vfmadd_ps:
10911 case Intrinsic::x86_fma_vfmadd_pd:
10912 case Intrinsic::x86_fma_vfmadd_ps_256:
10913 case Intrinsic::x86_fma_vfmadd_pd_256:
10914 Opc = X86ISD::FMADD;
10916 case Intrinsic::x86_fma_vfmsub_ps:
10917 case Intrinsic::x86_fma_vfmsub_pd:
10918 case Intrinsic::x86_fma_vfmsub_ps_256:
10919 case Intrinsic::x86_fma_vfmsub_pd_256:
10920 Opc = X86ISD::FMSUB;
10922 case Intrinsic::x86_fma_vfnmadd_ps:
10923 case Intrinsic::x86_fma_vfnmadd_pd:
10924 case Intrinsic::x86_fma_vfnmadd_ps_256:
10925 case Intrinsic::x86_fma_vfnmadd_pd_256:
10926 Opc = X86ISD::FNMADD;
10928 case Intrinsic::x86_fma_vfnmsub_ps:
10929 case Intrinsic::x86_fma_vfnmsub_pd:
10930 case Intrinsic::x86_fma_vfnmsub_ps_256:
10931 case Intrinsic::x86_fma_vfnmsub_pd_256:
10932 Opc = X86ISD::FNMSUB;
10934 case Intrinsic::x86_fma_vfmaddsub_ps:
10935 case Intrinsic::x86_fma_vfmaddsub_pd:
10936 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10937 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10938 Opc = X86ISD::FMADDSUB;
10940 case Intrinsic::x86_fma_vfmsubadd_ps:
10941 case Intrinsic::x86_fma_vfmsubadd_pd:
10942 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10943 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10944 Opc = X86ISD::FMSUBADD;
10948 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10949 Op.getOperand(2), Op.getOperand(3));
10954 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10955 DebugLoc dl = Op.getDebugLoc();
10956 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10958 default: return SDValue(); // Don't custom lower most intrinsics.
10960 // RDRAND/RDSEED intrinsics.
10961 case Intrinsic::x86_rdrand_16:
10962 case Intrinsic::x86_rdrand_32:
10963 case Intrinsic::x86_rdrand_64:
10964 case Intrinsic::x86_rdseed_16:
10965 case Intrinsic::x86_rdseed_32:
10966 case Intrinsic::x86_rdseed_64: {
10967 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10968 IntNo == Intrinsic::x86_rdseed_32 ||
10969 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10971 // Emit the node with the right value type.
10972 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10973 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10975 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10976 // Otherwise return the value from Rand, which is always 0, casted to i32.
10977 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10978 DAG.getConstant(1, Op->getValueType(1)),
10979 DAG.getConstant(X86::COND_B, MVT::i32),
10980 SDValue(Result.getNode(), 1) };
10981 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10982 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10985 // Return { result, isValid, chain }.
10986 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10987 SDValue(Result.getNode(), 2));
10990 // XTEST intrinsics.
10991 case Intrinsic::x86_xtest: {
10992 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
10993 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
10994 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10995 DAG.getConstant(X86::COND_NE, MVT::i8),
10997 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
10998 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
10999 Ret, SDValue(InTrans.getNode(), 1));
11004 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11005 SelectionDAG &DAG) const {
11006 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11007 MFI->setReturnAddressIsTaken(true);
11009 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11010 DebugLoc dl = Op.getDebugLoc();
11011 EVT PtrVT = getPointerTy();
11014 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11016 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11017 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11018 DAG.getNode(ISD::ADD, dl, PtrVT,
11019 FrameAddr, Offset),
11020 MachinePointerInfo(), false, false, false, 0);
11023 // Just load the return address.
11024 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11025 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11026 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11029 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11030 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11031 MFI->setFrameAddressIsTaken(true);
11033 EVT VT = Op.getValueType();
11034 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
11035 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11036 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
11037 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11039 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11040 MachinePointerInfo(),
11041 false, false, false, 0);
11045 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11046 SelectionDAG &DAG) const {
11047 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11050 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11051 SDValue Chain = Op.getOperand(0);
11052 SDValue Offset = Op.getOperand(1);
11053 SDValue Handler = Op.getOperand(2);
11054 DebugLoc dl = Op.getDebugLoc();
11056 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
11057 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
11059 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
11061 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
11062 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11063 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
11064 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11066 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11068 return DAG.getNode(X86ISD::EH_RETURN, dl,
11070 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11073 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11074 SelectionDAG &DAG) const {
11075 DebugLoc DL = Op.getDebugLoc();
11076 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11077 DAG.getVTList(MVT::i32, MVT::Other),
11078 Op.getOperand(0), Op.getOperand(1));
11081 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11082 SelectionDAG &DAG) const {
11083 DebugLoc DL = Op.getDebugLoc();
11084 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11085 Op.getOperand(0), Op.getOperand(1));
11088 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11089 return Op.getOperand(0);
11092 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11093 SelectionDAG &DAG) const {
11094 SDValue Root = Op.getOperand(0);
11095 SDValue Trmp = Op.getOperand(1); // trampoline
11096 SDValue FPtr = Op.getOperand(2); // nested function
11097 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11098 DebugLoc dl = Op.getDebugLoc();
11100 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11101 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11103 if (Subtarget->is64Bit()) {
11104 SDValue OutChains[6];
11106 // Large code-model.
11107 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
11108 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11110 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11111 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11113 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11115 // Load the pointer to the nested function into R11.
11116 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11117 SDValue Addr = Trmp;
11118 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11119 Addr, MachinePointerInfo(TrmpAddr),
11122 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11123 DAG.getConstant(2, MVT::i64));
11124 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11125 MachinePointerInfo(TrmpAddr, 2),
11128 // Load the 'nest' parameter value into R10.
11129 // R10 is specified in X86CallingConv.td
11130 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11131 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11132 DAG.getConstant(10, MVT::i64));
11133 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11134 Addr, MachinePointerInfo(TrmpAddr, 10),
11137 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11138 DAG.getConstant(12, MVT::i64));
11139 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11140 MachinePointerInfo(TrmpAddr, 12),
11143 // Jump to the nested function.
11144 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11145 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11146 DAG.getConstant(20, MVT::i64));
11147 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11148 Addr, MachinePointerInfo(TrmpAddr, 20),
11151 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11152 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11153 DAG.getConstant(22, MVT::i64));
11154 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11155 MachinePointerInfo(TrmpAddr, 22),
11158 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11160 const Function *Func =
11161 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11162 CallingConv::ID CC = Func->getCallingConv();
11167 llvm_unreachable("Unsupported calling convention");
11168 case CallingConv::C:
11169 case CallingConv::X86_StdCall: {
11170 // Pass 'nest' parameter in ECX.
11171 // Must be kept in sync with X86CallingConv.td
11172 NestReg = X86::ECX;
11174 // Check that ECX wasn't needed by an 'inreg' parameter.
11175 FunctionType *FTy = Func->getFunctionType();
11176 const AttributeSet &Attrs = Func->getAttributes();
11178 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11179 unsigned InRegCount = 0;
11182 for (FunctionType::param_iterator I = FTy->param_begin(),
11183 E = FTy->param_end(); I != E; ++I, ++Idx)
11184 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11185 // FIXME: should only count parameters that are lowered to integers.
11186 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11188 if (InRegCount > 2) {
11189 report_fatal_error("Nest register in use - reduce number of inreg"
11195 case CallingConv::X86_FastCall:
11196 case CallingConv::X86_ThisCall:
11197 case CallingConv::Fast:
11198 // Pass 'nest' parameter in EAX.
11199 // Must be kept in sync with X86CallingConv.td
11200 NestReg = X86::EAX;
11204 SDValue OutChains[4];
11205 SDValue Addr, Disp;
11207 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11208 DAG.getConstant(10, MVT::i32));
11209 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11211 // This is storing the opcode for MOV32ri.
11212 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11213 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11214 OutChains[0] = DAG.getStore(Root, dl,
11215 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11216 Trmp, MachinePointerInfo(TrmpAddr),
11219 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11220 DAG.getConstant(1, MVT::i32));
11221 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11222 MachinePointerInfo(TrmpAddr, 1),
11225 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11226 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11227 DAG.getConstant(5, MVT::i32));
11228 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11229 MachinePointerInfo(TrmpAddr, 5),
11232 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11233 DAG.getConstant(6, MVT::i32));
11234 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11235 MachinePointerInfo(TrmpAddr, 6),
11238 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11242 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11243 SelectionDAG &DAG) const {
11245 The rounding mode is in bits 11:10 of FPSR, and has the following
11247 00 Round to nearest
11252 FLT_ROUNDS, on the other hand, expects the following:
11259 To perform the conversion, we do:
11260 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11263 MachineFunction &MF = DAG.getMachineFunction();
11264 const TargetMachine &TM = MF.getTarget();
11265 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11266 unsigned StackAlignment = TFI.getStackAlignment();
11267 EVT VT = Op.getValueType();
11268 DebugLoc DL = Op.getDebugLoc();
11270 // Save FP Control Word to stack slot
11271 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11272 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11274 MachineMemOperand *MMO =
11275 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11276 MachineMemOperand::MOStore, 2, 2);
11278 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11279 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11280 DAG.getVTList(MVT::Other),
11281 Ops, 2, MVT::i16, MMO);
11283 // Load FP Control Word from stack slot
11284 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11285 MachinePointerInfo(), false, false, false, 0);
11287 // Transform as necessary
11289 DAG.getNode(ISD::SRL, DL, MVT::i16,
11290 DAG.getNode(ISD::AND, DL, MVT::i16,
11291 CWD, DAG.getConstant(0x800, MVT::i16)),
11292 DAG.getConstant(11, MVT::i8));
11294 DAG.getNode(ISD::SRL, DL, MVT::i16,
11295 DAG.getNode(ISD::AND, DL, MVT::i16,
11296 CWD, DAG.getConstant(0x400, MVT::i16)),
11297 DAG.getConstant(9, MVT::i8));
11300 DAG.getNode(ISD::AND, DL, MVT::i16,
11301 DAG.getNode(ISD::ADD, DL, MVT::i16,
11302 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11303 DAG.getConstant(1, MVT::i16)),
11304 DAG.getConstant(3, MVT::i16));
11306 return DAG.getNode((VT.getSizeInBits() < 16 ?
11307 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11310 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11311 EVT VT = Op.getValueType();
11313 unsigned NumBits = VT.getSizeInBits();
11314 DebugLoc dl = Op.getDebugLoc();
11316 Op = Op.getOperand(0);
11317 if (VT == MVT::i8) {
11318 // Zero extend to i32 since there is not an i8 bsr.
11320 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11323 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11324 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11325 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11327 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11330 DAG.getConstant(NumBits+NumBits-1, OpVT),
11331 DAG.getConstant(X86::COND_E, MVT::i8),
11334 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11336 // Finally xor with NumBits-1.
11337 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11340 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11344 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11345 EVT VT = Op.getValueType();
11347 unsigned NumBits = VT.getSizeInBits();
11348 DebugLoc dl = Op.getDebugLoc();
11350 Op = Op.getOperand(0);
11351 if (VT == MVT::i8) {
11352 // Zero extend to i32 since there is not an i8 bsr.
11354 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11357 // Issue a bsr (scan bits in reverse).
11358 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11359 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11361 // And xor with NumBits-1.
11362 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11365 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11369 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11370 EVT VT = Op.getValueType();
11371 unsigned NumBits = VT.getSizeInBits();
11372 DebugLoc dl = Op.getDebugLoc();
11373 Op = Op.getOperand(0);
11375 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11376 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11377 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11379 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11382 DAG.getConstant(NumBits, VT),
11383 DAG.getConstant(X86::COND_E, MVT::i8),
11386 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11389 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11390 // ones, and then concatenate the result back.
11391 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11392 EVT VT = Op.getValueType();
11394 assert(VT.is256BitVector() && VT.isInteger() &&
11395 "Unsupported value type for operation");
11397 unsigned NumElems = VT.getVectorNumElements();
11398 DebugLoc dl = Op.getDebugLoc();
11400 // Extract the LHS vectors
11401 SDValue LHS = Op.getOperand(0);
11402 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11403 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11405 // Extract the RHS vectors
11406 SDValue RHS = Op.getOperand(1);
11407 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11408 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11410 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11411 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11413 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11414 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11415 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11418 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11419 assert(Op.getValueType().is256BitVector() &&
11420 Op.getValueType().isInteger() &&
11421 "Only handle AVX 256-bit vector integer operation");
11422 return Lower256IntArith(Op, DAG);
11425 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11426 assert(Op.getValueType().is256BitVector() &&
11427 Op.getValueType().isInteger() &&
11428 "Only handle AVX 256-bit vector integer operation");
11429 return Lower256IntArith(Op, DAG);
11432 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11433 SelectionDAG &DAG) {
11434 DebugLoc dl = Op.getDebugLoc();
11435 EVT VT = Op.getValueType();
11437 // Decompose 256-bit ops into smaller 128-bit ops.
11438 if (VT.is256BitVector() && !Subtarget->hasInt256())
11439 return Lower256IntArith(Op, DAG);
11441 SDValue A = Op.getOperand(0);
11442 SDValue B = Op.getOperand(1);
11444 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11445 if (VT == MVT::v4i32) {
11446 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11447 "Should not custom lower when pmuldq is available!");
11449 // Extract the odd parts.
11450 const int UnpackMask[] = { 1, -1, 3, -1 };
11451 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11452 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11454 // Multiply the even parts.
11455 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11456 // Now multiply odd parts.
11457 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11459 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11460 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11462 // Merge the two vectors back together with a shuffle. This expands into 2
11464 const int ShufMask[] = { 0, 4, 2, 6 };
11465 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11468 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11469 "Only know how to lower V2I64/V4I64 multiply");
11471 // Ahi = psrlqi(a, 32);
11472 // Bhi = psrlqi(b, 32);
11474 // AloBlo = pmuludq(a, b);
11475 // AloBhi = pmuludq(a, Bhi);
11476 // AhiBlo = pmuludq(Ahi, b);
11478 // AloBhi = psllqi(AloBhi, 32);
11479 // AhiBlo = psllqi(AhiBlo, 32);
11480 // return AloBlo + AloBhi + AhiBlo;
11482 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11484 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11485 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11487 // Bit cast to 32-bit vectors for MULUDQ
11488 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11489 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11490 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11491 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11492 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11494 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11495 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11496 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11498 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11499 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11501 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11502 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11505 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11506 EVT VT = Op.getValueType();
11507 EVT EltTy = VT.getVectorElementType();
11508 unsigned NumElts = VT.getVectorNumElements();
11509 SDValue N0 = Op.getOperand(0);
11510 DebugLoc dl = Op.getDebugLoc();
11512 // Lower sdiv X, pow2-const.
11513 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11517 APInt SplatValue, SplatUndef;
11518 unsigned MinSplatBits;
11520 if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11523 if ((SplatValue != 0) &&
11524 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11525 unsigned lg2 = SplatValue.countTrailingZeros();
11526 // Splat the sign bit.
11527 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11528 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11529 // Add (N0 < 0) ? abs2 - 1 : 0;
11530 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11531 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11532 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11533 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11534 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11536 // If we're dividing by a positive value, we're done. Otherwise, we must
11537 // negate the result.
11538 if (SplatValue.isNonNegative())
11541 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11542 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11543 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11548 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11549 const X86Subtarget *Subtarget) {
11550 EVT VT = Op.getValueType();
11551 DebugLoc dl = Op.getDebugLoc();
11552 SDValue R = Op.getOperand(0);
11553 SDValue Amt = Op.getOperand(1);
11555 // Optimize shl/srl/sra with constant shift amount.
11556 if (isSplatVector(Amt.getNode())) {
11557 SDValue SclrAmt = Amt->getOperand(0);
11558 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11559 uint64_t ShiftAmt = C->getZExtValue();
11561 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11562 (Subtarget->hasInt256() &&
11563 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11564 if (Op.getOpcode() == ISD::SHL)
11565 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11566 DAG.getConstant(ShiftAmt, MVT::i32));
11567 if (Op.getOpcode() == ISD::SRL)
11568 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11569 DAG.getConstant(ShiftAmt, MVT::i32));
11570 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11571 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11572 DAG.getConstant(ShiftAmt, MVT::i32));
11575 if (VT == MVT::v16i8) {
11576 if (Op.getOpcode() == ISD::SHL) {
11577 // Make a large shift.
11578 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11579 DAG.getConstant(ShiftAmt, MVT::i32));
11580 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11581 // Zero out the rightmost bits.
11582 SmallVector<SDValue, 16> V(16,
11583 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11585 return DAG.getNode(ISD::AND, dl, VT, SHL,
11586 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11588 if (Op.getOpcode() == ISD::SRL) {
11589 // Make a large shift.
11590 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11591 DAG.getConstant(ShiftAmt, MVT::i32));
11592 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11593 // Zero out the leftmost bits.
11594 SmallVector<SDValue, 16> V(16,
11595 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11597 return DAG.getNode(ISD::AND, dl, VT, SRL,
11598 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11600 if (Op.getOpcode() == ISD::SRA) {
11601 if (ShiftAmt == 7) {
11602 // R s>> 7 === R s< 0
11603 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11604 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11607 // R s>> a === ((R u>> a) ^ m) - m
11608 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11609 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11611 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11612 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11613 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11616 llvm_unreachable("Unknown shift opcode.");
11619 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11620 if (Op.getOpcode() == ISD::SHL) {
11621 // Make a large shift.
11622 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11623 DAG.getConstant(ShiftAmt, MVT::i32));
11624 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11625 // Zero out the rightmost bits.
11626 SmallVector<SDValue, 32> V(32,
11627 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11629 return DAG.getNode(ISD::AND, dl, VT, SHL,
11630 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11632 if (Op.getOpcode() == ISD::SRL) {
11633 // Make a large shift.
11634 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11635 DAG.getConstant(ShiftAmt, MVT::i32));
11636 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11637 // Zero out the leftmost bits.
11638 SmallVector<SDValue, 32> V(32,
11639 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11641 return DAG.getNode(ISD::AND, dl, VT, SRL,
11642 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11644 if (Op.getOpcode() == ISD::SRA) {
11645 if (ShiftAmt == 7) {
11646 // R s>> 7 === R s< 0
11647 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11648 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11651 // R s>> a === ((R u>> a) ^ m) - m
11652 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11653 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11655 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11656 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11657 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11660 llvm_unreachable("Unknown shift opcode.");
11665 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11666 if (!Subtarget->is64Bit() &&
11667 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11668 Amt.getOpcode() == ISD::BITCAST &&
11669 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11670 Amt = Amt.getOperand(0);
11671 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11672 VT.getVectorNumElements();
11673 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11674 uint64_t ShiftAmt = 0;
11675 for (unsigned i = 0; i != Ratio; ++i) {
11676 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11680 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11682 // Check remaining shift amounts.
11683 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11684 uint64_t ShAmt = 0;
11685 for (unsigned j = 0; j != Ratio; ++j) {
11686 ConstantSDNode *C =
11687 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11691 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11693 if (ShAmt != ShiftAmt)
11696 switch (Op.getOpcode()) {
11698 llvm_unreachable("Unknown shift opcode!");
11700 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11701 DAG.getConstant(ShiftAmt, MVT::i32));
11703 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11704 DAG.getConstant(ShiftAmt, MVT::i32));
11706 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11707 DAG.getConstant(ShiftAmt, MVT::i32));
11714 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11715 const X86Subtarget* Subtarget) {
11716 EVT VT = Op.getValueType();
11717 DebugLoc dl = Op.getDebugLoc();
11718 SDValue R = Op.getOperand(0);
11719 SDValue Amt = Op.getOperand(1);
11721 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11722 VT == MVT::v4i32 || VT == MVT::v8i16 ||
11723 (Subtarget->hasInt256() &&
11724 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11725 VT == MVT::v8i32 || VT == MVT::v16i16))) {
11727 EVT EltVT = VT.getVectorElementType();
11729 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11730 unsigned NumElts = VT.getVectorNumElements();
11732 for (i = 0; i != NumElts; ++i) {
11733 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11737 for (j = i; j != NumElts; ++j) {
11738 SDValue Arg = Amt.getOperand(j);
11739 if (Arg.getOpcode() == ISD::UNDEF) continue;
11740 if (Arg != Amt.getOperand(i))
11743 if (i != NumElts && j == NumElts)
11744 BaseShAmt = Amt.getOperand(i);
11746 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11747 Amt = Amt.getOperand(0);
11748 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11749 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11750 SDValue InVec = Amt.getOperand(0);
11751 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11752 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11754 for (; i != NumElts; ++i) {
11755 SDValue Arg = InVec.getOperand(i);
11756 if (Arg.getOpcode() == ISD::UNDEF) continue;
11760 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11761 if (ConstantSDNode *C =
11762 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11763 unsigned SplatIdx =
11764 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11765 if (C->getZExtValue() == SplatIdx)
11766 BaseShAmt = InVec.getOperand(1);
11769 if (BaseShAmt.getNode() == 0)
11770 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11771 DAG.getIntPtrConstant(0));
11775 if (BaseShAmt.getNode()) {
11776 if (EltVT.bitsGT(MVT::i32))
11777 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11778 else if (EltVT.bitsLT(MVT::i32))
11779 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11781 switch (Op.getOpcode()) {
11783 llvm_unreachable("Unknown shift opcode!");
11785 switch (VT.getSimpleVT().SimpleTy) {
11786 default: return SDValue();
11793 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11796 switch (VT.getSimpleVT().SimpleTy) {
11797 default: return SDValue();
11802 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11805 switch (VT.getSimpleVT().SimpleTy) {
11806 default: return SDValue();
11813 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11819 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11820 if (!Subtarget->is64Bit() &&
11821 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11822 Amt.getOpcode() == ISD::BITCAST &&
11823 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11824 Amt = Amt.getOperand(0);
11825 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11826 VT.getVectorNumElements();
11827 std::vector<SDValue> Vals(Ratio);
11828 for (unsigned i = 0; i != Ratio; ++i)
11829 Vals[i] = Amt.getOperand(i);
11830 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11831 for (unsigned j = 0; j != Ratio; ++j)
11832 if (Vals[j] != Amt.getOperand(i + j))
11835 switch (Op.getOpcode()) {
11837 llvm_unreachable("Unknown shift opcode!");
11839 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11841 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11843 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11850 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11852 EVT VT = Op.getValueType();
11853 DebugLoc dl = Op.getDebugLoc();
11854 SDValue R = Op.getOperand(0);
11855 SDValue Amt = Op.getOperand(1);
11858 if (!Subtarget->hasSSE2())
11861 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11865 V = LowerScalarVariableShift(Op, DAG, Subtarget);
11869 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11870 if (Subtarget->hasInt256()) {
11871 if (Op.getOpcode() == ISD::SRL &&
11872 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11873 VT == MVT::v4i64 || VT == MVT::v8i32))
11875 if (Op.getOpcode() == ISD::SHL &&
11876 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11877 VT == MVT::v4i64 || VT == MVT::v8i32))
11879 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11883 // Lower SHL with variable shift amount.
11884 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11885 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11887 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11888 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11889 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11890 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11892 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11893 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11896 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11897 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11899 // Turn 'a' into a mask suitable for VSELECT
11900 SDValue VSelM = DAG.getConstant(0x80, VT);
11901 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11902 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11904 SDValue CM1 = DAG.getConstant(0x0f, VT);
11905 SDValue CM2 = DAG.getConstant(0x3f, VT);
11907 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11908 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11909 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11910 DAG.getConstant(4, MVT::i32), DAG);
11911 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11912 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11915 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11916 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11917 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11919 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11920 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11921 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11922 DAG.getConstant(2, MVT::i32), DAG);
11923 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11924 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11927 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11928 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11929 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11931 // return VSELECT(r, r+r, a);
11932 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11933 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11937 // Decompose 256-bit shifts into smaller 128-bit shifts.
11938 if (VT.is256BitVector()) {
11939 unsigned NumElems = VT.getVectorNumElements();
11940 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11941 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11943 // Extract the two vectors
11944 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11945 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11947 // Recreate the shift amount vectors
11948 SDValue Amt1, Amt2;
11949 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11950 // Constant shift amount
11951 SmallVector<SDValue, 4> Amt1Csts;
11952 SmallVector<SDValue, 4> Amt2Csts;
11953 for (unsigned i = 0; i != NumElems/2; ++i)
11954 Amt1Csts.push_back(Amt->getOperand(i));
11955 for (unsigned i = NumElems/2; i != NumElems; ++i)
11956 Amt2Csts.push_back(Amt->getOperand(i));
11958 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11959 &Amt1Csts[0], NumElems/2);
11960 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11961 &Amt2Csts[0], NumElems/2);
11963 // Variable shift amount
11964 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11965 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11968 // Issue new vector shifts for the smaller types
11969 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11970 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11972 // Concatenate the result back
11973 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11979 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11980 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11981 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11982 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11983 // has only one use.
11984 SDNode *N = Op.getNode();
11985 SDValue LHS = N->getOperand(0);
11986 SDValue RHS = N->getOperand(1);
11987 unsigned BaseOp = 0;
11989 DebugLoc DL = Op.getDebugLoc();
11990 switch (Op.getOpcode()) {
11991 default: llvm_unreachable("Unknown ovf instruction!");
11993 // A subtract of one will be selected as a INC. Note that INC doesn't
11994 // set CF, so we can't do this for UADDO.
11995 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11997 BaseOp = X86ISD::INC;
11998 Cond = X86::COND_O;
12001 BaseOp = X86ISD::ADD;
12002 Cond = X86::COND_O;
12005 BaseOp = X86ISD::ADD;
12006 Cond = X86::COND_B;
12009 // A subtract of one will be selected as a DEC. Note that DEC doesn't
12010 // set CF, so we can't do this for USUBO.
12011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12013 BaseOp = X86ISD::DEC;
12014 Cond = X86::COND_O;
12017 BaseOp = X86ISD::SUB;
12018 Cond = X86::COND_O;
12021 BaseOp = X86ISD::SUB;
12022 Cond = X86::COND_B;
12025 BaseOp = X86ISD::SMUL;
12026 Cond = X86::COND_O;
12028 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12029 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12031 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12034 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12035 DAG.getConstant(X86::COND_O, MVT::i32),
12036 SDValue(Sum.getNode(), 2));
12038 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12042 // Also sets EFLAGS.
12043 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12044 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12047 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12048 DAG.getConstant(Cond, MVT::i32),
12049 SDValue(Sum.getNode(), 1));
12051 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12054 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12055 SelectionDAG &DAG) const {
12056 DebugLoc dl = Op.getDebugLoc();
12057 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12058 EVT VT = Op.getValueType();
12060 if (!Subtarget->hasSSE2() || !VT.isVector())
12063 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12064 ExtraVT.getScalarType().getSizeInBits();
12065 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12067 switch (VT.getSimpleVT().SimpleTy) {
12068 default: return SDValue();
12071 if (!Subtarget->hasFp256())
12073 if (!Subtarget->hasInt256()) {
12074 // needs to be split
12075 unsigned NumElems = VT.getVectorNumElements();
12077 // Extract the LHS vectors
12078 SDValue LHS = Op.getOperand(0);
12079 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12080 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12082 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12083 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12085 EVT ExtraEltVT = ExtraVT.getVectorElementType();
12086 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12087 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12089 SDValue Extra = DAG.getValueType(ExtraVT);
12091 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12092 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12094 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12099 // (sext (vzext x)) -> (vsext x)
12100 SDValue Op0 = Op.getOperand(0);
12101 SDValue Op00 = Op0.getOperand(0);
12103 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12104 if (Op0.getOpcode() == ISD::BITCAST &&
12105 Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12106 Tmp1 = LowerVectorIntExtend(Op00, DAG);
12107 if (Tmp1.getNode()) {
12108 SDValue Tmp1Op0 = Tmp1.getOperand(0);
12109 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12110 "This optimization is invalid without a VZEXT.");
12111 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12114 // If the above didn't work, then just use Shift-Left + Shift-Right.
12115 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12116 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12121 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
12122 SelectionDAG &DAG) {
12123 DebugLoc dl = Op.getDebugLoc();
12125 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
12126 // There isn't any reason to disable it if the target processor supports it.
12127 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
12128 SDValue Chain = Op.getOperand(0);
12129 SDValue Zero = DAG.getConstant(0, MVT::i32);
12131 DAG.getRegister(X86::ESP, MVT::i32), // Base
12132 DAG.getTargetConstant(1, MVT::i8), // Scale
12133 DAG.getRegister(0, MVT::i32), // Index
12134 DAG.getTargetConstant(0, MVT::i32), // Disp
12135 DAG.getRegister(0, MVT::i32), // Segment.
12140 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12141 array_lengthof(Ops));
12142 return SDValue(Res, 0);
12145 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
12147 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12149 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12150 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12151 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
12152 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
12154 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
12155 if (!Op1 && !Op2 && !Op3 && Op4)
12156 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
12158 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
12159 if (Op1 && !Op2 && !Op3 && !Op4)
12160 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
12162 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
12164 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12167 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12168 SelectionDAG &DAG) {
12169 DebugLoc dl = Op.getDebugLoc();
12170 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12171 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12172 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12173 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12175 // The only fence that needs an instruction is a sequentially-consistent
12176 // cross-thread fence.
12177 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12178 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12179 // no-sse2). There isn't any reason to disable it if the target processor
12181 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12182 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12184 SDValue Chain = Op.getOperand(0);
12185 SDValue Zero = DAG.getConstant(0, MVT::i32);
12187 DAG.getRegister(X86::ESP, MVT::i32), // Base
12188 DAG.getTargetConstant(1, MVT::i8), // Scale
12189 DAG.getRegister(0, MVT::i32), // Index
12190 DAG.getTargetConstant(0, MVT::i32), // Disp
12191 DAG.getRegister(0, MVT::i32), // Segment.
12196 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12197 array_lengthof(Ops));
12198 return SDValue(Res, 0);
12201 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12202 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12205 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12206 SelectionDAG &DAG) {
12207 EVT T = Op.getValueType();
12208 DebugLoc DL = Op.getDebugLoc();
12211 switch(T.getSimpleVT().SimpleTy) {
12212 default: llvm_unreachable("Invalid value type!");
12213 case MVT::i8: Reg = X86::AL; size = 1; break;
12214 case MVT::i16: Reg = X86::AX; size = 2; break;
12215 case MVT::i32: Reg = X86::EAX; size = 4; break;
12217 assert(Subtarget->is64Bit() && "Node not type legal!");
12218 Reg = X86::RAX; size = 8;
12221 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12222 Op.getOperand(2), SDValue());
12223 SDValue Ops[] = { cpIn.getValue(0),
12226 DAG.getTargetConstant(size, MVT::i8),
12227 cpIn.getValue(1) };
12228 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12229 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12230 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12233 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12237 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12238 SelectionDAG &DAG) {
12239 assert(Subtarget->is64Bit() && "Result not type legalized?");
12240 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12241 SDValue TheChain = Op.getOperand(0);
12242 DebugLoc dl = Op.getDebugLoc();
12243 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12244 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12245 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12247 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12248 DAG.getConstant(32, MVT::i8));
12250 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12253 return DAG.getMergeValues(Ops, 2, dl);
12256 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12257 EVT SrcVT = Op.getOperand(0).getValueType();
12258 EVT DstVT = Op.getValueType();
12259 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12260 Subtarget->hasMMX() && "Unexpected custom BITCAST");
12261 assert((DstVT == MVT::i64 ||
12262 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12263 "Unexpected custom BITCAST");
12264 // i64 <=> MMX conversions are Legal.
12265 if (SrcVT==MVT::i64 && DstVT.isVector())
12267 if (DstVT==MVT::i64 && SrcVT.isVector())
12269 // MMX <=> MMX conversions are Legal.
12270 if (SrcVT.isVector() && DstVT.isVector())
12272 // All other conversions need to be expanded.
12276 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12277 SDNode *Node = Op.getNode();
12278 DebugLoc dl = Node->getDebugLoc();
12279 EVT T = Node->getValueType(0);
12280 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12281 DAG.getConstant(0, T), Node->getOperand(2));
12282 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12283 cast<AtomicSDNode>(Node)->getMemoryVT(),
12284 Node->getOperand(0),
12285 Node->getOperand(1), negOp,
12286 cast<AtomicSDNode>(Node)->getSrcValue(),
12287 cast<AtomicSDNode>(Node)->getAlignment(),
12288 cast<AtomicSDNode>(Node)->getOrdering(),
12289 cast<AtomicSDNode>(Node)->getSynchScope());
12292 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12293 SDNode *Node = Op.getNode();
12294 DebugLoc dl = Node->getDebugLoc();
12295 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12297 // Convert seq_cst store -> xchg
12298 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12299 // FIXME: On 32-bit, store -> fist or movq would be more efficient
12300 // (The only way to get a 16-byte store is cmpxchg16b)
12301 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12302 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12303 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12304 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12305 cast<AtomicSDNode>(Node)->getMemoryVT(),
12306 Node->getOperand(0),
12307 Node->getOperand(1), Node->getOperand(2),
12308 cast<AtomicSDNode>(Node)->getMemOperand(),
12309 cast<AtomicSDNode>(Node)->getOrdering(),
12310 cast<AtomicSDNode>(Node)->getSynchScope());
12311 return Swap.getValue(1);
12313 // Other atomic stores have a simple pattern.
12317 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12318 EVT VT = Op.getNode()->getValueType(0);
12320 // Let legalize expand this if it isn't a legal type yet.
12321 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12324 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12327 bool ExtraOp = false;
12328 switch (Op.getOpcode()) {
12329 default: llvm_unreachable("Invalid code");
12330 case ISD::ADDC: Opc = X86ISD::ADD; break;
12331 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12332 case ISD::SUBC: Opc = X86ISD::SUB; break;
12333 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12337 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12339 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12340 Op.getOperand(1), Op.getOperand(2));
12343 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12344 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12346 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12347 // which returns the values as { float, float } (in XMM0) or
12348 // { double, double } (which is returned in XMM0, XMM1).
12349 DebugLoc dl = Op.getDebugLoc();
12350 SDValue Arg = Op.getOperand(0);
12351 EVT ArgVT = Arg.getValueType();
12352 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12355 ArgListEntry Entry;
12359 Entry.isSExt = false;
12360 Entry.isZExt = false;
12361 Args.push_back(Entry);
12363 bool isF64 = ArgVT == MVT::f64;
12364 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12365 // the small struct {f32, f32} is returned in (eax, edx). For f64,
12366 // the results are returned via SRet in memory.
12367 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
12368 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12370 Type *RetTy = isF64
12371 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12372 : (Type*)VectorType::get(ArgTy, 4);
12374 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12375 false, false, false, false, 0,
12376 CallingConv::C, /*isTaillCall=*/false,
12377 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12378 Callee, Args, DAG, dl);
12379 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12382 // Returned in xmm0 and xmm1.
12383 return CallResult.first;
12385 // Returned in bits 0:31 and 32:64 xmm0.
12386 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12387 CallResult.first, DAG.getIntPtrConstant(0));
12388 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12389 CallResult.first, DAG.getIntPtrConstant(1));
12390 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12391 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12394 /// LowerOperation - Provide custom lowering hooks for some operations.
12396 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12397 switch (Op.getOpcode()) {
12398 default: llvm_unreachable("Should not custom lower this!");
12399 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12400 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
12401 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12402 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12403 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12404 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12405 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12406 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12407 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12408 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12409 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12410 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12411 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12412 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12413 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12414 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12415 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12416 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12417 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12418 case ISD::SHL_PARTS:
12419 case ISD::SRA_PARTS:
12420 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12421 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12422 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12423 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12424 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12425 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12426 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12427 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12428 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12429 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12430 case ISD::FABS: return LowerFABS(Op, DAG);
12431 case ISD::FNEG: return LowerFNEG(Op, DAG);
12432 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12433 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12434 case ISD::SETCC: return LowerSETCC(Op, DAG);
12435 case ISD::SELECT: return LowerSELECT(Op, DAG);
12436 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12437 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12438 case ISD::VASTART: return LowerVASTART(Op, DAG);
12439 case ISD::VAARG: return LowerVAARG(Op, DAG);
12440 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12441 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12442 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12443 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12444 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12445 case ISD::FRAME_TO_ARGS_OFFSET:
12446 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12447 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12448 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12449 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12450 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12451 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12452 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12453 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12454 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12455 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12456 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12457 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12460 case ISD::SHL: return LowerShift(Op, DAG);
12466 case ISD::UMULO: return LowerXALUO(Op, DAG);
12467 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12468 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12472 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12473 case ISD::ADD: return LowerADD(Op, DAG);
12474 case ISD::SUB: return LowerSUB(Op, DAG);
12475 case ISD::SDIV: return LowerSDIV(Op, DAG);
12476 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
12480 static void ReplaceATOMIC_LOAD(SDNode *Node,
12481 SmallVectorImpl<SDValue> &Results,
12482 SelectionDAG &DAG) {
12483 DebugLoc dl = Node->getDebugLoc();
12484 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12486 // Convert wide load -> cmpxchg8b/cmpxchg16b
12487 // FIXME: On 32-bit, load -> fild or movq would be more efficient
12488 // (The only way to get a 16-byte load is cmpxchg16b)
12489 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12490 SDValue Zero = DAG.getConstant(0, VT);
12491 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12492 Node->getOperand(0),
12493 Node->getOperand(1), Zero, Zero,
12494 cast<AtomicSDNode>(Node)->getMemOperand(),
12495 cast<AtomicSDNode>(Node)->getOrdering(),
12496 cast<AtomicSDNode>(Node)->getSynchScope());
12497 Results.push_back(Swap.getValue(0));
12498 Results.push_back(Swap.getValue(1));
12502 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12503 SelectionDAG &DAG, unsigned NewOp) {
12504 DebugLoc dl = Node->getDebugLoc();
12505 assert (Node->getValueType(0) == MVT::i64 &&
12506 "Only know how to expand i64 atomics");
12508 SDValue Chain = Node->getOperand(0);
12509 SDValue In1 = Node->getOperand(1);
12510 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12511 Node->getOperand(2), DAG.getIntPtrConstant(0));
12512 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12513 Node->getOperand(2), DAG.getIntPtrConstant(1));
12514 SDValue Ops[] = { Chain, In1, In2L, In2H };
12515 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12517 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12518 cast<MemSDNode>(Node)->getMemOperand());
12519 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12520 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12521 Results.push_back(Result.getValue(2));
12524 /// ReplaceNodeResults - Replace a node with an illegal result type
12525 /// with a new node built out of custom code.
12526 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12527 SmallVectorImpl<SDValue>&Results,
12528 SelectionDAG &DAG) const {
12529 DebugLoc dl = N->getDebugLoc();
12530 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12531 switch (N->getOpcode()) {
12533 llvm_unreachable("Do not know how to custom type legalize this operation!");
12534 case ISD::SIGN_EXTEND_INREG:
12539 // We don't want to expand or promote these.
12541 case ISD::FP_TO_SINT:
12542 case ISD::FP_TO_UINT: {
12543 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12545 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12548 std::pair<SDValue,SDValue> Vals =
12549 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12550 SDValue FIST = Vals.first, StackSlot = Vals.second;
12551 if (FIST.getNode() != 0) {
12552 EVT VT = N->getValueType(0);
12553 // Return a load from the stack slot.
12554 if (StackSlot.getNode() != 0)
12555 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12556 MachinePointerInfo(),
12557 false, false, false, 0));
12559 Results.push_back(FIST);
12563 case ISD::UINT_TO_FP: {
12564 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12565 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12566 N->getValueType(0) != MVT::v2f32)
12568 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12570 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12572 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12573 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12574 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12575 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12576 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12577 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12580 case ISD::FP_ROUND: {
12581 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12583 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12584 Results.push_back(V);
12587 case ISD::READCYCLECOUNTER: {
12588 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12589 SDValue TheChain = N->getOperand(0);
12590 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12591 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12593 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12595 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12596 SDValue Ops[] = { eax, edx };
12597 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12598 Results.push_back(edx.getValue(1));
12601 case ISD::ATOMIC_CMP_SWAP: {
12602 EVT T = N->getValueType(0);
12603 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12604 bool Regs64bit = T == MVT::i128;
12605 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12606 SDValue cpInL, cpInH;
12607 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12608 DAG.getConstant(0, HalfT));
12609 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12610 DAG.getConstant(1, HalfT));
12611 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12612 Regs64bit ? X86::RAX : X86::EAX,
12614 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12615 Regs64bit ? X86::RDX : X86::EDX,
12616 cpInH, cpInL.getValue(1));
12617 SDValue swapInL, swapInH;
12618 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12619 DAG.getConstant(0, HalfT));
12620 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12621 DAG.getConstant(1, HalfT));
12622 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12623 Regs64bit ? X86::RBX : X86::EBX,
12624 swapInL, cpInH.getValue(1));
12625 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12626 Regs64bit ? X86::RCX : X86::ECX,
12627 swapInH, swapInL.getValue(1));
12628 SDValue Ops[] = { swapInH.getValue(0),
12630 swapInH.getValue(1) };
12631 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12632 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12633 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12634 X86ISD::LCMPXCHG8_DAG;
12635 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12637 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12638 Regs64bit ? X86::RAX : X86::EAX,
12639 HalfT, Result.getValue(1));
12640 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12641 Regs64bit ? X86::RDX : X86::EDX,
12642 HalfT, cpOutL.getValue(2));
12643 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12644 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12645 Results.push_back(cpOutH.getValue(1));
12648 case ISD::ATOMIC_LOAD_ADD:
12649 case ISD::ATOMIC_LOAD_AND:
12650 case ISD::ATOMIC_LOAD_NAND:
12651 case ISD::ATOMIC_LOAD_OR:
12652 case ISD::ATOMIC_LOAD_SUB:
12653 case ISD::ATOMIC_LOAD_XOR:
12654 case ISD::ATOMIC_LOAD_MAX:
12655 case ISD::ATOMIC_LOAD_MIN:
12656 case ISD::ATOMIC_LOAD_UMAX:
12657 case ISD::ATOMIC_LOAD_UMIN:
12658 case ISD::ATOMIC_SWAP: {
12660 switch (N->getOpcode()) {
12661 default: llvm_unreachable("Unexpected opcode");
12662 case ISD::ATOMIC_LOAD_ADD:
12663 Opc = X86ISD::ATOMADD64_DAG;
12665 case ISD::ATOMIC_LOAD_AND:
12666 Opc = X86ISD::ATOMAND64_DAG;
12668 case ISD::ATOMIC_LOAD_NAND:
12669 Opc = X86ISD::ATOMNAND64_DAG;
12671 case ISD::ATOMIC_LOAD_OR:
12672 Opc = X86ISD::ATOMOR64_DAG;
12674 case ISD::ATOMIC_LOAD_SUB:
12675 Opc = X86ISD::ATOMSUB64_DAG;
12677 case ISD::ATOMIC_LOAD_XOR:
12678 Opc = X86ISD::ATOMXOR64_DAG;
12680 case ISD::ATOMIC_LOAD_MAX:
12681 Opc = X86ISD::ATOMMAX64_DAG;
12683 case ISD::ATOMIC_LOAD_MIN:
12684 Opc = X86ISD::ATOMMIN64_DAG;
12686 case ISD::ATOMIC_LOAD_UMAX:
12687 Opc = X86ISD::ATOMUMAX64_DAG;
12689 case ISD::ATOMIC_LOAD_UMIN:
12690 Opc = X86ISD::ATOMUMIN64_DAG;
12692 case ISD::ATOMIC_SWAP:
12693 Opc = X86ISD::ATOMSWAP64_DAG;
12696 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12699 case ISD::ATOMIC_LOAD:
12700 ReplaceATOMIC_LOAD(N, Results, DAG);
12704 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12706 default: return NULL;
12707 case X86ISD::BSF: return "X86ISD::BSF";
12708 case X86ISD::BSR: return "X86ISD::BSR";
12709 case X86ISD::SHLD: return "X86ISD::SHLD";
12710 case X86ISD::SHRD: return "X86ISD::SHRD";
12711 case X86ISD::FAND: return "X86ISD::FAND";
12712 case X86ISD::FOR: return "X86ISD::FOR";
12713 case X86ISD::FXOR: return "X86ISD::FXOR";
12714 case X86ISD::FSRL: return "X86ISD::FSRL";
12715 case X86ISD::FILD: return "X86ISD::FILD";
12716 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12717 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12718 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12719 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12720 case X86ISD::FLD: return "X86ISD::FLD";
12721 case X86ISD::FST: return "X86ISD::FST";
12722 case X86ISD::CALL: return "X86ISD::CALL";
12723 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12724 case X86ISD::BT: return "X86ISD::BT";
12725 case X86ISD::CMP: return "X86ISD::CMP";
12726 case X86ISD::COMI: return "X86ISD::COMI";
12727 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12728 case X86ISD::SETCC: return "X86ISD::SETCC";
12729 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12730 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12731 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12732 case X86ISD::CMOV: return "X86ISD::CMOV";
12733 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12734 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12735 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12736 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12737 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12738 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12739 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12740 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12741 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12742 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12743 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12744 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12745 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12746 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12747 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12748 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12749 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12750 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12751 case X86ISD::HADD: return "X86ISD::HADD";
12752 case X86ISD::HSUB: return "X86ISD::HSUB";
12753 case X86ISD::FHADD: return "X86ISD::FHADD";
12754 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12755 case X86ISD::UMAX: return "X86ISD::UMAX";
12756 case X86ISD::UMIN: return "X86ISD::UMIN";
12757 case X86ISD::SMAX: return "X86ISD::SMAX";
12758 case X86ISD::SMIN: return "X86ISD::SMIN";
12759 case X86ISD::FMAX: return "X86ISD::FMAX";
12760 case X86ISD::FMIN: return "X86ISD::FMIN";
12761 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12762 case X86ISD::FMINC: return "X86ISD::FMINC";
12763 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12764 case X86ISD::FRCP: return "X86ISD::FRCP";
12765 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12766 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12767 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12768 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12769 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12770 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12771 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12772 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12773 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12774 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12775 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12776 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12777 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12778 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12779 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12780 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12781 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12782 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12783 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12784 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12785 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12786 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12787 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12788 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12789 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12790 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12791 case X86ISD::VSHL: return "X86ISD::VSHL";
12792 case X86ISD::VSRL: return "X86ISD::VSRL";
12793 case X86ISD::VSRA: return "X86ISD::VSRA";
12794 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12795 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12796 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12797 case X86ISD::CMPP: return "X86ISD::CMPP";
12798 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12799 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12800 case X86ISD::ADD: return "X86ISD::ADD";
12801 case X86ISD::SUB: return "X86ISD::SUB";
12802 case X86ISD::ADC: return "X86ISD::ADC";
12803 case X86ISD::SBB: return "X86ISD::SBB";
12804 case X86ISD::SMUL: return "X86ISD::SMUL";
12805 case X86ISD::UMUL: return "X86ISD::UMUL";
12806 case X86ISD::INC: return "X86ISD::INC";
12807 case X86ISD::DEC: return "X86ISD::DEC";
12808 case X86ISD::OR: return "X86ISD::OR";
12809 case X86ISD::XOR: return "X86ISD::XOR";
12810 case X86ISD::AND: return "X86ISD::AND";
12811 case X86ISD::BLSI: return "X86ISD::BLSI";
12812 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12813 case X86ISD::BLSR: return "X86ISD::BLSR";
12814 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12815 case X86ISD::PTEST: return "X86ISD::PTEST";
12816 case X86ISD::TESTP: return "X86ISD::TESTP";
12817 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
12818 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12819 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12820 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12821 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12822 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12823 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12824 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12825 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12826 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12827 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12828 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12829 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12830 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12831 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12832 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12833 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12834 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12835 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12836 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12837 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12838 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12839 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12840 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12841 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12842 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12843 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12844 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12845 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12846 case X86ISD::SAHF: return "X86ISD::SAHF";
12847 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12848 case X86ISD::RDSEED: return "X86ISD::RDSEED";
12849 case X86ISD::FMADD: return "X86ISD::FMADD";
12850 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12851 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12852 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12853 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12854 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12855 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12856 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12857 case X86ISD::XTEST: return "X86ISD::XTEST";
12861 // isLegalAddressingMode - Return true if the addressing mode represented
12862 // by AM is legal for this target, for a load/store of the specified type.
12863 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12865 // X86 supports extremely general addressing modes.
12866 CodeModel::Model M = getTargetMachine().getCodeModel();
12867 Reloc::Model R = getTargetMachine().getRelocationModel();
12869 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12870 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12875 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12877 // If a reference to this global requires an extra load, we can't fold it.
12878 if (isGlobalStubReference(GVFlags))
12881 // If BaseGV requires a register for the PIC base, we cannot also have a
12882 // BaseReg specified.
12883 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12886 // If lower 4G is not available, then we must use rip-relative addressing.
12887 if ((M != CodeModel::Small || R != Reloc::Static) &&
12888 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12892 switch (AM.Scale) {
12898 // These scales always work.
12903 // These scales are formed with basereg+scalereg. Only accept if there is
12908 default: // Other stuff never works.
12915 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12916 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12918 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12919 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12920 return NumBits1 > NumBits2;
12923 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12924 return isInt<32>(Imm);
12927 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12928 // Can also use sub to handle negated immediates.
12929 return isInt<32>(Imm);
12932 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12933 if (!VT1.isInteger() || !VT2.isInteger())
12935 unsigned NumBits1 = VT1.getSizeInBits();
12936 unsigned NumBits2 = VT2.getSizeInBits();
12937 return NumBits1 > NumBits2;
12940 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12941 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12942 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12945 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12946 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12947 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12950 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12951 EVT VT1 = Val.getValueType();
12952 if (isZExtFree(VT1, VT2))
12955 if (Val.getOpcode() != ISD::LOAD)
12958 if (!VT1.isSimple() || !VT1.isInteger() ||
12959 !VT2.isSimple() || !VT2.isInteger())
12962 switch (VT1.getSimpleVT().SimpleTy) {
12967 // X86 has 8, 16, and 32-bit zero-extending loads.
12974 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12975 // i16 instructions are longer (0x66 prefix) and potentially slower.
12976 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12979 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12980 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12981 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12982 /// are assumed to be legal.
12984 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12986 // Very little shuffling can be done for 64-bit vectors right now.
12987 if (VT.getSizeInBits() == 64)
12990 // FIXME: pshufb, blends, shifts.
12991 return (VT.getVectorNumElements() == 2 ||
12992 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12993 isMOVLMask(M, VT) ||
12994 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12995 isPSHUFDMask(M, VT) ||
12996 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12997 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12998 isPALIGNRMask(M, VT, Subtarget) ||
12999 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13000 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13001 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13002 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13006 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13008 unsigned NumElts = VT.getVectorNumElements();
13009 // FIXME: This collection of masks seems suspect.
13012 if (NumElts == 4 && VT.is128BitVector()) {
13013 return (isMOVLMask(Mask, VT) ||
13014 isCommutedMOVLMask(Mask, VT, true) ||
13015 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13016 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13021 //===----------------------------------------------------------------------===//
13022 // X86 Scheduler Hooks
13023 //===----------------------------------------------------------------------===//
13025 /// Utility function to emit xbegin specifying the start of an RTM region.
13026 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13027 const TargetInstrInfo *TII) {
13028 DebugLoc DL = MI->getDebugLoc();
13030 const BasicBlock *BB = MBB->getBasicBlock();
13031 MachineFunction::iterator I = MBB;
13034 // For the v = xbegin(), we generate
13045 MachineBasicBlock *thisMBB = MBB;
13046 MachineFunction *MF = MBB->getParent();
13047 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13048 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13049 MF->insert(I, mainMBB);
13050 MF->insert(I, sinkMBB);
13052 // Transfer the remainder of BB and its successor edges to sinkMBB.
13053 sinkMBB->splice(sinkMBB->begin(), MBB,
13054 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13055 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13059 // # fallthrough to mainMBB
13060 // # abortion to sinkMBB
13061 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13062 thisMBB->addSuccessor(mainMBB);
13063 thisMBB->addSuccessor(sinkMBB);
13067 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13068 mainMBB->addSuccessor(sinkMBB);
13071 // EAX is live into the sinkMBB
13072 sinkMBB->addLiveIn(X86::EAX);
13073 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13074 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13077 MI->eraseFromParent();
13081 // Get CMPXCHG opcode for the specified data type.
13082 static unsigned getCmpXChgOpcode(EVT VT) {
13083 switch (VT.getSimpleVT().SimpleTy) {
13084 case MVT::i8: return X86::LCMPXCHG8;
13085 case MVT::i16: return X86::LCMPXCHG16;
13086 case MVT::i32: return X86::LCMPXCHG32;
13087 case MVT::i64: return X86::LCMPXCHG64;
13091 llvm_unreachable("Invalid operand size!");
13094 // Get LOAD opcode for the specified data type.
13095 static unsigned getLoadOpcode(EVT VT) {
13096 switch (VT.getSimpleVT().SimpleTy) {
13097 case MVT::i8: return X86::MOV8rm;
13098 case MVT::i16: return X86::MOV16rm;
13099 case MVT::i32: return X86::MOV32rm;
13100 case MVT::i64: return X86::MOV64rm;
13104 llvm_unreachable("Invalid operand size!");
13107 // Get opcode of the non-atomic one from the specified atomic instruction.
13108 static unsigned getNonAtomicOpcode(unsigned Opc) {
13110 case X86::ATOMAND8: return X86::AND8rr;
13111 case X86::ATOMAND16: return X86::AND16rr;
13112 case X86::ATOMAND32: return X86::AND32rr;
13113 case X86::ATOMAND64: return X86::AND64rr;
13114 case X86::ATOMOR8: return X86::OR8rr;
13115 case X86::ATOMOR16: return X86::OR16rr;
13116 case X86::ATOMOR32: return X86::OR32rr;
13117 case X86::ATOMOR64: return X86::OR64rr;
13118 case X86::ATOMXOR8: return X86::XOR8rr;
13119 case X86::ATOMXOR16: return X86::XOR16rr;
13120 case X86::ATOMXOR32: return X86::XOR32rr;
13121 case X86::ATOMXOR64: return X86::XOR64rr;
13123 llvm_unreachable("Unhandled atomic-load-op opcode!");
13126 // Get opcode of the non-atomic one from the specified atomic instruction with
13128 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13129 unsigned &ExtraOpc) {
13131 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
13132 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
13133 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
13134 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
13135 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
13136 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13137 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13138 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13139 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
13140 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13141 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13142 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13143 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
13144 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13145 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13146 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13147 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
13148 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13149 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13150 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13152 llvm_unreachable("Unhandled atomic-load-op opcode!");
13155 // Get opcode of the non-atomic one from the specified atomic instruction for
13156 // 64-bit data type on 32-bit target.
13157 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13159 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
13160 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
13161 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
13162 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
13163 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
13164 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13165 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
13166 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
13167 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
13168 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
13170 llvm_unreachable("Unhandled atomic-load-op opcode!");
13173 // Get opcode of the non-atomic one from the specified atomic instruction for
13174 // 64-bit data type on 32-bit target with extra opcode.
13175 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13177 unsigned &ExtraOpc) {
13179 case X86::ATOMNAND6432:
13180 ExtraOpc = X86::NOT32r;
13181 HiOpc = X86::AND32rr;
13182 return X86::AND32rr;
13184 llvm_unreachable("Unhandled atomic-load-op opcode!");
13187 // Get pseudo CMOV opcode from the specified data type.
13188 static unsigned getPseudoCMOVOpc(EVT VT) {
13189 switch (VT.getSimpleVT().SimpleTy) {
13190 case MVT::i8: return X86::CMOV_GR8;
13191 case MVT::i16: return X86::CMOV_GR16;
13192 case MVT::i32: return X86::CMOV_GR32;
13196 llvm_unreachable("Unknown CMOV opcode!");
13199 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13200 // They will be translated into a spin-loop or compare-exchange loop from
13203 // dst = atomic-fetch-op MI.addr, MI.val
13209 // t1 = LOAD MI.addr
13211 // t4 = phi(t1, t3 / loop)
13212 // t2 = OP MI.val, t4
13214 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13220 MachineBasicBlock *
13221 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13222 MachineBasicBlock *MBB) const {
13223 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13224 DebugLoc DL = MI->getDebugLoc();
13226 MachineFunction *MF = MBB->getParent();
13227 MachineRegisterInfo &MRI = MF->getRegInfo();
13229 const BasicBlock *BB = MBB->getBasicBlock();
13230 MachineFunction::iterator I = MBB;
13233 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13234 "Unexpected number of operands");
13236 assert(MI->hasOneMemOperand() &&
13237 "Expected atomic-load-op to have one memoperand");
13239 // Memory Reference
13240 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13241 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13243 unsigned DstReg, SrcReg;
13244 unsigned MemOpndSlot;
13246 unsigned CurOp = 0;
13248 DstReg = MI->getOperand(CurOp++).getReg();
13249 MemOpndSlot = CurOp;
13250 CurOp += X86::AddrNumOperands;
13251 SrcReg = MI->getOperand(CurOp++).getReg();
13253 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13254 MVT::SimpleValueType VT = *RC->vt_begin();
13255 unsigned t1 = MRI.createVirtualRegister(RC);
13256 unsigned t2 = MRI.createVirtualRegister(RC);
13257 unsigned t3 = MRI.createVirtualRegister(RC);
13258 unsigned t4 = MRI.createVirtualRegister(RC);
13259 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13261 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13262 unsigned LOADOpc = getLoadOpcode(VT);
13264 // For the atomic load-arith operator, we generate
13267 // t1 = LOAD [MI.addr]
13269 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
13270 // t1 = OP MI.val, EAX
13272 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13278 MachineBasicBlock *thisMBB = MBB;
13279 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13280 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13281 MF->insert(I, mainMBB);
13282 MF->insert(I, sinkMBB);
13284 MachineInstrBuilder MIB;
13286 // Transfer the remainder of BB and its successor edges to sinkMBB.
13287 sinkMBB->splice(sinkMBB->begin(), MBB,
13288 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13289 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13292 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13293 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13294 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13296 NewMO.setIsKill(false);
13297 MIB.addOperand(NewMO);
13299 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13300 unsigned flags = (*MMOI)->getFlags();
13301 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13302 MachineMemOperand *MMO =
13303 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13304 (*MMOI)->getSize(),
13305 (*MMOI)->getBaseAlignment(),
13306 (*MMOI)->getTBAAInfo(),
13307 (*MMOI)->getRanges());
13308 MIB.addMemOperand(MMO);
13311 thisMBB->addSuccessor(mainMBB);
13314 MachineBasicBlock *origMainMBB = mainMBB;
13317 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13318 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13320 unsigned Opc = MI->getOpcode();
13323 llvm_unreachable("Unhandled atomic-load-op opcode!");
13324 case X86::ATOMAND8:
13325 case X86::ATOMAND16:
13326 case X86::ATOMAND32:
13327 case X86::ATOMAND64:
13329 case X86::ATOMOR16:
13330 case X86::ATOMOR32:
13331 case X86::ATOMOR64:
13332 case X86::ATOMXOR8:
13333 case X86::ATOMXOR16:
13334 case X86::ATOMXOR32:
13335 case X86::ATOMXOR64: {
13336 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13337 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13341 case X86::ATOMNAND8:
13342 case X86::ATOMNAND16:
13343 case X86::ATOMNAND32:
13344 case X86::ATOMNAND64: {
13345 unsigned Tmp = MRI.createVirtualRegister(RC);
13347 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13348 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13350 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13353 case X86::ATOMMAX8:
13354 case X86::ATOMMAX16:
13355 case X86::ATOMMAX32:
13356 case X86::ATOMMAX64:
13357 case X86::ATOMMIN8:
13358 case X86::ATOMMIN16:
13359 case X86::ATOMMIN32:
13360 case X86::ATOMMIN64:
13361 case X86::ATOMUMAX8:
13362 case X86::ATOMUMAX16:
13363 case X86::ATOMUMAX32:
13364 case X86::ATOMUMAX64:
13365 case X86::ATOMUMIN8:
13366 case X86::ATOMUMIN16:
13367 case X86::ATOMUMIN32:
13368 case X86::ATOMUMIN64: {
13370 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13372 BuildMI(mainMBB, DL, TII->get(CMPOpc))
13376 if (Subtarget->hasCMov()) {
13377 if (VT != MVT::i8) {
13379 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13383 // Promote i8 to i32 to use CMOV32
13384 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13385 const TargetRegisterClass *RC32 =
13386 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13387 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13388 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13389 unsigned Tmp = MRI.createVirtualRegister(RC32);
13391 unsigned Undef = MRI.createVirtualRegister(RC32);
13392 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13394 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13397 .addImm(X86::sub_8bit);
13398 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13401 .addImm(X86::sub_8bit);
13403 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13407 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13408 .addReg(Tmp, 0, X86::sub_8bit);
13411 // Use pseudo select and lower them.
13412 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13413 "Invalid atomic-load-op transformation!");
13414 unsigned SelOpc = getPseudoCMOVOpc(VT);
13415 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13416 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13417 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13418 .addReg(SrcReg).addReg(t4)
13420 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13421 // Replace the original PHI node as mainMBB is changed after CMOV
13423 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13424 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13425 Phi->eraseFromParent();
13431 // Copy PhyReg back from virtual register.
13432 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13435 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13436 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13437 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13439 NewMO.setIsKill(false);
13440 MIB.addOperand(NewMO);
13443 MIB.setMemRefs(MMOBegin, MMOEnd);
13445 // Copy PhyReg back to virtual register.
13446 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13449 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13451 mainMBB->addSuccessor(origMainMBB);
13452 mainMBB->addSuccessor(sinkMBB);
13455 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13456 TII->get(TargetOpcode::COPY), DstReg)
13459 MI->eraseFromParent();
13463 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13464 // instructions. They will be translated into a spin-loop or compare-exchange
13468 // dst = atomic-fetch-op MI.addr, MI.val
13474 // t1L = LOAD [MI.addr + 0]
13475 // t1H = LOAD [MI.addr + 4]
13477 // t4L = phi(t1L, t3L / loop)
13478 // t4H = phi(t1H, t3H / loop)
13479 // t2L = OP MI.val.lo, t4L
13480 // t2H = OP MI.val.hi, t4H
13485 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13493 MachineBasicBlock *
13494 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13495 MachineBasicBlock *MBB) const {
13496 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13497 DebugLoc DL = MI->getDebugLoc();
13499 MachineFunction *MF = MBB->getParent();
13500 MachineRegisterInfo &MRI = MF->getRegInfo();
13502 const BasicBlock *BB = MBB->getBasicBlock();
13503 MachineFunction::iterator I = MBB;
13506 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13507 "Unexpected number of operands");
13509 assert(MI->hasOneMemOperand() &&
13510 "Expected atomic-load-op32 to have one memoperand");
13512 // Memory Reference
13513 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13514 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13516 unsigned DstLoReg, DstHiReg;
13517 unsigned SrcLoReg, SrcHiReg;
13518 unsigned MemOpndSlot;
13520 unsigned CurOp = 0;
13522 DstLoReg = MI->getOperand(CurOp++).getReg();
13523 DstHiReg = MI->getOperand(CurOp++).getReg();
13524 MemOpndSlot = CurOp;
13525 CurOp += X86::AddrNumOperands;
13526 SrcLoReg = MI->getOperand(CurOp++).getReg();
13527 SrcHiReg = MI->getOperand(CurOp++).getReg();
13529 const TargetRegisterClass *RC = &X86::GR32RegClass;
13530 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13532 unsigned t1L = MRI.createVirtualRegister(RC);
13533 unsigned t1H = MRI.createVirtualRegister(RC);
13534 unsigned t2L = MRI.createVirtualRegister(RC);
13535 unsigned t2H = MRI.createVirtualRegister(RC);
13536 unsigned t3L = MRI.createVirtualRegister(RC);
13537 unsigned t3H = MRI.createVirtualRegister(RC);
13538 unsigned t4L = MRI.createVirtualRegister(RC);
13539 unsigned t4H = MRI.createVirtualRegister(RC);
13541 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13542 unsigned LOADOpc = X86::MOV32rm;
13544 // For the atomic load-arith operator, we generate
13547 // t1L = LOAD [MI.addr + 0]
13548 // t1H = LOAD [MI.addr + 4]
13550 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
13551 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
13552 // t2L = OP MI.val.lo, t4L
13553 // t2H = OP MI.val.hi, t4H
13556 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13564 MachineBasicBlock *thisMBB = MBB;
13565 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13566 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13567 MF->insert(I, mainMBB);
13568 MF->insert(I, sinkMBB);
13570 MachineInstrBuilder MIB;
13572 // Transfer the remainder of BB and its successor edges to sinkMBB.
13573 sinkMBB->splice(sinkMBB->begin(), MBB,
13574 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13575 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13579 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13580 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13581 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13583 NewMO.setIsKill(false);
13584 MIB.addOperand(NewMO);
13586 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13587 unsigned flags = (*MMOI)->getFlags();
13588 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13589 MachineMemOperand *MMO =
13590 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13591 (*MMOI)->getSize(),
13592 (*MMOI)->getBaseAlignment(),
13593 (*MMOI)->getTBAAInfo(),
13594 (*MMOI)->getRanges());
13595 MIB.addMemOperand(MMO);
13597 MachineInstr *LowMI = MIB;
13600 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13601 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13602 if (i == X86::AddrDisp) {
13603 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13605 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13607 NewMO.setIsKill(false);
13608 MIB.addOperand(NewMO);
13611 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13613 thisMBB->addSuccessor(mainMBB);
13616 MachineBasicBlock *origMainMBB = mainMBB;
13619 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13620 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13621 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13622 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13624 unsigned Opc = MI->getOpcode();
13627 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13628 case X86::ATOMAND6432:
13629 case X86::ATOMOR6432:
13630 case X86::ATOMXOR6432:
13631 case X86::ATOMADD6432:
13632 case X86::ATOMSUB6432: {
13634 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13635 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13637 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13641 case X86::ATOMNAND6432: {
13642 unsigned HiOpc, NOTOpc;
13643 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13644 unsigned TmpL = MRI.createVirtualRegister(RC);
13645 unsigned TmpH = MRI.createVirtualRegister(RC);
13646 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13648 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13650 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13651 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13654 case X86::ATOMMAX6432:
13655 case X86::ATOMMIN6432:
13656 case X86::ATOMUMAX6432:
13657 case X86::ATOMUMIN6432: {
13659 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13660 unsigned cL = MRI.createVirtualRegister(RC8);
13661 unsigned cH = MRI.createVirtualRegister(RC8);
13662 unsigned cL32 = MRI.createVirtualRegister(RC);
13663 unsigned cH32 = MRI.createVirtualRegister(RC);
13664 unsigned cc = MRI.createVirtualRegister(RC);
13665 // cl := cmp src_lo, lo
13666 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13667 .addReg(SrcLoReg).addReg(t4L);
13668 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13669 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13670 // ch := cmp src_hi, hi
13671 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13672 .addReg(SrcHiReg).addReg(t4H);
13673 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13674 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13675 // cc := if (src_hi == hi) ? cl : ch;
13676 if (Subtarget->hasCMov()) {
13677 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13678 .addReg(cH32).addReg(cL32);
13680 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13681 .addReg(cH32).addReg(cL32)
13682 .addImm(X86::COND_E);
13683 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13685 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13686 if (Subtarget->hasCMov()) {
13687 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13688 .addReg(SrcLoReg).addReg(t4L);
13689 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13690 .addReg(SrcHiReg).addReg(t4H);
13692 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13693 .addReg(SrcLoReg).addReg(t4L)
13694 .addImm(X86::COND_NE);
13695 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13696 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13697 // 2nd CMOV lowering.
13698 mainMBB->addLiveIn(X86::EFLAGS);
13699 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13700 .addReg(SrcHiReg).addReg(t4H)
13701 .addImm(X86::COND_NE);
13702 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13703 // Replace the original PHI node as mainMBB is changed after CMOV
13705 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13706 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13707 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13708 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13709 PhiL->eraseFromParent();
13710 PhiH->eraseFromParent();
13714 case X86::ATOMSWAP6432: {
13716 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13717 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13718 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13723 // Copy EDX:EAX back from HiReg:LoReg
13724 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13725 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13726 // Copy ECX:EBX from t1H:t1L
13727 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13728 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13730 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13731 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13732 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13734 NewMO.setIsKill(false);
13735 MIB.addOperand(NewMO);
13737 MIB.setMemRefs(MMOBegin, MMOEnd);
13739 // Copy EDX:EAX back to t3H:t3L
13740 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13741 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13743 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13745 mainMBB->addSuccessor(origMainMBB);
13746 mainMBB->addSuccessor(sinkMBB);
13749 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13750 TII->get(TargetOpcode::COPY), DstLoReg)
13752 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13753 TII->get(TargetOpcode::COPY), DstHiReg)
13756 MI->eraseFromParent();
13760 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13761 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13762 // in the .td file.
13763 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13764 const TargetInstrInfo *TII) {
13766 switch (MI->getOpcode()) {
13767 default: llvm_unreachable("illegal opcode!");
13768 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
13769 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13770 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
13771 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13772 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
13773 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13774 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
13775 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13778 DebugLoc dl = MI->getDebugLoc();
13779 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13781 unsigned NumArgs = MI->getNumOperands();
13782 for (unsigned i = 1; i < NumArgs; ++i) {
13783 MachineOperand &Op = MI->getOperand(i);
13784 if (!(Op.isReg() && Op.isImplicit()))
13785 MIB.addOperand(Op);
13787 if (MI->hasOneMemOperand())
13788 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13790 BuildMI(*BB, MI, dl,
13791 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13792 .addReg(X86::XMM0);
13794 MI->eraseFromParent();
13798 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13799 // defs in an instruction pattern
13800 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13801 const TargetInstrInfo *TII) {
13803 switch (MI->getOpcode()) {
13804 default: llvm_unreachable("illegal opcode!");
13805 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
13806 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13807 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
13808 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13809 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13810 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13811 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13812 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13815 DebugLoc dl = MI->getDebugLoc();
13816 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13818 unsigned NumArgs = MI->getNumOperands(); // remove the results
13819 for (unsigned i = 1; i < NumArgs; ++i) {
13820 MachineOperand &Op = MI->getOperand(i);
13821 if (!(Op.isReg() && Op.isImplicit()))
13822 MIB.addOperand(Op);
13824 if (MI->hasOneMemOperand())
13825 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13827 BuildMI(*BB, MI, dl,
13828 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13831 MI->eraseFromParent();
13835 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13836 const TargetInstrInfo *TII,
13837 const X86Subtarget* Subtarget) {
13838 DebugLoc dl = MI->getDebugLoc();
13840 // Address into RAX/EAX, other two args into ECX, EDX.
13841 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13842 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13843 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13844 for (int i = 0; i < X86::AddrNumOperands; ++i)
13845 MIB.addOperand(MI->getOperand(i));
13847 unsigned ValOps = X86::AddrNumOperands;
13848 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13849 .addReg(MI->getOperand(ValOps).getReg());
13850 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13851 .addReg(MI->getOperand(ValOps+1).getReg());
13853 // The instruction doesn't actually take any operands though.
13854 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13856 MI->eraseFromParent(); // The pseudo is gone now.
13860 MachineBasicBlock *
13861 X86TargetLowering::EmitVAARG64WithCustomInserter(
13863 MachineBasicBlock *MBB) const {
13864 // Emit va_arg instruction on X86-64.
13866 // Operands to this pseudo-instruction:
13867 // 0 ) Output : destination address (reg)
13868 // 1-5) Input : va_list address (addr, i64mem)
13869 // 6 ) ArgSize : Size (in bytes) of vararg type
13870 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13871 // 8 ) Align : Alignment of type
13872 // 9 ) EFLAGS (implicit-def)
13874 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13875 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13877 unsigned DestReg = MI->getOperand(0).getReg();
13878 MachineOperand &Base = MI->getOperand(1);
13879 MachineOperand &Scale = MI->getOperand(2);
13880 MachineOperand &Index = MI->getOperand(3);
13881 MachineOperand &Disp = MI->getOperand(4);
13882 MachineOperand &Segment = MI->getOperand(5);
13883 unsigned ArgSize = MI->getOperand(6).getImm();
13884 unsigned ArgMode = MI->getOperand(7).getImm();
13885 unsigned Align = MI->getOperand(8).getImm();
13887 // Memory Reference
13888 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13889 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13890 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13892 // Machine Information
13893 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13894 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13895 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13896 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13897 DebugLoc DL = MI->getDebugLoc();
13899 // struct va_list {
13902 // i64 overflow_area (address)
13903 // i64 reg_save_area (address)
13905 // sizeof(va_list) = 24
13906 // alignment(va_list) = 8
13908 unsigned TotalNumIntRegs = 6;
13909 unsigned TotalNumXMMRegs = 8;
13910 bool UseGPOffset = (ArgMode == 1);
13911 bool UseFPOffset = (ArgMode == 2);
13912 unsigned MaxOffset = TotalNumIntRegs * 8 +
13913 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13915 /* Align ArgSize to a multiple of 8 */
13916 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13917 bool NeedsAlign = (Align > 8);
13919 MachineBasicBlock *thisMBB = MBB;
13920 MachineBasicBlock *overflowMBB;
13921 MachineBasicBlock *offsetMBB;
13922 MachineBasicBlock *endMBB;
13924 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13925 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13926 unsigned OffsetReg = 0;
13928 if (!UseGPOffset && !UseFPOffset) {
13929 // If we only pull from the overflow region, we don't create a branch.
13930 // We don't need to alter control flow.
13931 OffsetDestReg = 0; // unused
13932 OverflowDestReg = DestReg;
13935 overflowMBB = thisMBB;
13938 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13939 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13940 // If not, pull from overflow_area. (branch to overflowMBB)
13945 // offsetMBB overflowMBB
13950 // Registers for the PHI in endMBB
13951 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13952 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13954 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13955 MachineFunction *MF = MBB->getParent();
13956 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13957 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13958 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13960 MachineFunction::iterator MBBIter = MBB;
13963 // Insert the new basic blocks
13964 MF->insert(MBBIter, offsetMBB);
13965 MF->insert(MBBIter, overflowMBB);
13966 MF->insert(MBBIter, endMBB);
13968 // Transfer the remainder of MBB and its successor edges to endMBB.
13969 endMBB->splice(endMBB->begin(), thisMBB,
13970 llvm::next(MachineBasicBlock::iterator(MI)),
13972 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13974 // Make offsetMBB and overflowMBB successors of thisMBB
13975 thisMBB->addSuccessor(offsetMBB);
13976 thisMBB->addSuccessor(overflowMBB);
13978 // endMBB is a successor of both offsetMBB and overflowMBB
13979 offsetMBB->addSuccessor(endMBB);
13980 overflowMBB->addSuccessor(endMBB);
13982 // Load the offset value into a register
13983 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13984 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13988 .addDisp(Disp, UseFPOffset ? 4 : 0)
13989 .addOperand(Segment)
13990 .setMemRefs(MMOBegin, MMOEnd);
13992 // Check if there is enough room left to pull this argument.
13993 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13995 .addImm(MaxOffset + 8 - ArgSizeA8);
13997 // Branch to "overflowMBB" if offset >= max
13998 // Fall through to "offsetMBB" otherwise
13999 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14000 .addMBB(overflowMBB);
14003 // In offsetMBB, emit code to use the reg_save_area.
14005 assert(OffsetReg != 0);
14007 // Read the reg_save_area address.
14008 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14009 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14014 .addOperand(Segment)
14015 .setMemRefs(MMOBegin, MMOEnd);
14017 // Zero-extend the offset
14018 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14019 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14022 .addImm(X86::sub_32bit);
14024 // Add the offset to the reg_save_area to get the final address.
14025 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14026 .addReg(OffsetReg64)
14027 .addReg(RegSaveReg);
14029 // Compute the offset for the next argument
14030 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14031 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14033 .addImm(UseFPOffset ? 16 : 8);
14035 // Store it back into the va_list.
14036 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14040 .addDisp(Disp, UseFPOffset ? 4 : 0)
14041 .addOperand(Segment)
14042 .addReg(NextOffsetReg)
14043 .setMemRefs(MMOBegin, MMOEnd);
14046 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14051 // Emit code to use overflow area
14054 // Load the overflow_area address into a register.
14055 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14056 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14061 .addOperand(Segment)
14062 .setMemRefs(MMOBegin, MMOEnd);
14064 // If we need to align it, do so. Otherwise, just copy the address
14065 // to OverflowDestReg.
14067 // Align the overflow address
14068 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14069 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14071 // aligned_addr = (addr + (align-1)) & ~(align-1)
14072 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14073 .addReg(OverflowAddrReg)
14076 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14078 .addImm(~(uint64_t)(Align-1));
14080 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14081 .addReg(OverflowAddrReg);
14084 // Compute the next overflow address after this argument.
14085 // (the overflow address should be kept 8-byte aligned)
14086 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14087 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14088 .addReg(OverflowDestReg)
14089 .addImm(ArgSizeA8);
14091 // Store the new overflow address.
14092 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14097 .addOperand(Segment)
14098 .addReg(NextAddrReg)
14099 .setMemRefs(MMOBegin, MMOEnd);
14101 // If we branched, emit the PHI to the front of endMBB.
14103 BuildMI(*endMBB, endMBB->begin(), DL,
14104 TII->get(X86::PHI), DestReg)
14105 .addReg(OffsetDestReg).addMBB(offsetMBB)
14106 .addReg(OverflowDestReg).addMBB(overflowMBB);
14109 // Erase the pseudo instruction
14110 MI->eraseFromParent();
14115 MachineBasicBlock *
14116 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14118 MachineBasicBlock *MBB) const {
14119 // Emit code to save XMM registers to the stack. The ABI says that the
14120 // number of registers to save is given in %al, so it's theoretically
14121 // possible to do an indirect jump trick to avoid saving all of them,
14122 // however this code takes a simpler approach and just executes all
14123 // of the stores if %al is non-zero. It's less code, and it's probably
14124 // easier on the hardware branch predictor, and stores aren't all that
14125 // expensive anyway.
14127 // Create the new basic blocks. One block contains all the XMM stores,
14128 // and one block is the final destination regardless of whether any
14129 // stores were performed.
14130 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14131 MachineFunction *F = MBB->getParent();
14132 MachineFunction::iterator MBBIter = MBB;
14134 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14135 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14136 F->insert(MBBIter, XMMSaveMBB);
14137 F->insert(MBBIter, EndMBB);
14139 // Transfer the remainder of MBB and its successor edges to EndMBB.
14140 EndMBB->splice(EndMBB->begin(), MBB,
14141 llvm::next(MachineBasicBlock::iterator(MI)),
14143 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14145 // The original block will now fall through to the XMM save block.
14146 MBB->addSuccessor(XMMSaveMBB);
14147 // The XMMSaveMBB will fall through to the end block.
14148 XMMSaveMBB->addSuccessor(EndMBB);
14150 // Now add the instructions.
14151 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14152 DebugLoc DL = MI->getDebugLoc();
14154 unsigned CountReg = MI->getOperand(0).getReg();
14155 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14156 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14158 if (!Subtarget->isTargetWin64()) {
14159 // If %al is 0, branch around the XMM save block.
14160 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14161 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14162 MBB->addSuccessor(EndMBB);
14165 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14166 // In the XMM save block, save all the XMM argument registers.
14167 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14168 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14169 MachineMemOperand *MMO =
14170 F->getMachineMemOperand(
14171 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14172 MachineMemOperand::MOStore,
14173 /*Size=*/16, /*Align=*/16);
14174 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14175 .addFrameIndex(RegSaveFrameIndex)
14176 .addImm(/*Scale=*/1)
14177 .addReg(/*IndexReg=*/0)
14178 .addImm(/*Disp=*/Offset)
14179 .addReg(/*Segment=*/0)
14180 .addReg(MI->getOperand(i).getReg())
14181 .addMemOperand(MMO);
14184 MI->eraseFromParent(); // The pseudo instruction is gone now.
14189 // The EFLAGS operand of SelectItr might be missing a kill marker
14190 // because there were multiple uses of EFLAGS, and ISel didn't know
14191 // which to mark. Figure out whether SelectItr should have had a
14192 // kill marker, and set it if it should. Returns the correct kill
14194 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14195 MachineBasicBlock* BB,
14196 const TargetRegisterInfo* TRI) {
14197 // Scan forward through BB for a use/def of EFLAGS.
14198 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14199 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14200 const MachineInstr& mi = *miI;
14201 if (mi.readsRegister(X86::EFLAGS))
14203 if (mi.definesRegister(X86::EFLAGS))
14204 break; // Should have kill-flag - update below.
14207 // If we hit the end of the block, check whether EFLAGS is live into a
14209 if (miI == BB->end()) {
14210 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14211 sEnd = BB->succ_end();
14212 sItr != sEnd; ++sItr) {
14213 MachineBasicBlock* succ = *sItr;
14214 if (succ->isLiveIn(X86::EFLAGS))
14219 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14220 // out. SelectMI should have a kill flag on EFLAGS.
14221 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14225 MachineBasicBlock *
14226 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14227 MachineBasicBlock *BB) const {
14228 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14229 DebugLoc DL = MI->getDebugLoc();
14231 // To "insert" a SELECT_CC instruction, we actually have to insert the
14232 // diamond control-flow pattern. The incoming instruction knows the
14233 // destination vreg to set, the condition code register to branch on, the
14234 // true/false values to select between, and a branch opcode to use.
14235 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14236 MachineFunction::iterator It = BB;
14242 // cmpTY ccX, r1, r2
14244 // fallthrough --> copy0MBB
14245 MachineBasicBlock *thisMBB = BB;
14246 MachineFunction *F = BB->getParent();
14247 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14248 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14249 F->insert(It, copy0MBB);
14250 F->insert(It, sinkMBB);
14252 // If the EFLAGS register isn't dead in the terminator, then claim that it's
14253 // live into the sink and copy blocks.
14254 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14255 if (!MI->killsRegister(X86::EFLAGS) &&
14256 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14257 copy0MBB->addLiveIn(X86::EFLAGS);
14258 sinkMBB->addLiveIn(X86::EFLAGS);
14261 // Transfer the remainder of BB and its successor edges to sinkMBB.
14262 sinkMBB->splice(sinkMBB->begin(), BB,
14263 llvm::next(MachineBasicBlock::iterator(MI)),
14265 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14267 // Add the true and fallthrough blocks as its successors.
14268 BB->addSuccessor(copy0MBB);
14269 BB->addSuccessor(sinkMBB);
14271 // Create the conditional branch instruction.
14273 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14274 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14277 // %FalseValue = ...
14278 // # fallthrough to sinkMBB
14279 copy0MBB->addSuccessor(sinkMBB);
14282 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14284 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14285 TII->get(X86::PHI), MI->getOperand(0).getReg())
14286 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14287 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14289 MI->eraseFromParent(); // The pseudo instruction is gone now.
14293 MachineBasicBlock *
14294 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14295 bool Is64Bit) const {
14296 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14297 DebugLoc DL = MI->getDebugLoc();
14298 MachineFunction *MF = BB->getParent();
14299 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14301 assert(getTargetMachine().Options.EnableSegmentedStacks);
14303 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14304 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14307 // ... [Till the alloca]
14308 // If stacklet is not large enough, jump to mallocMBB
14311 // Allocate by subtracting from RSP
14312 // Jump to continueMBB
14315 // Allocate by call to runtime
14319 // [rest of original BB]
14322 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14323 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14324 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14326 MachineRegisterInfo &MRI = MF->getRegInfo();
14327 const TargetRegisterClass *AddrRegClass =
14328 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14330 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14331 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14332 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14333 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14334 sizeVReg = MI->getOperand(1).getReg(),
14335 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14337 MachineFunction::iterator MBBIter = BB;
14340 MF->insert(MBBIter, bumpMBB);
14341 MF->insert(MBBIter, mallocMBB);
14342 MF->insert(MBBIter, continueMBB);
14344 continueMBB->splice(continueMBB->begin(), BB, llvm::next
14345 (MachineBasicBlock::iterator(MI)), BB->end());
14346 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14348 // Add code to the main basic block to check if the stack limit has been hit,
14349 // and if so, jump to mallocMBB otherwise to bumpMBB.
14350 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14351 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14352 .addReg(tmpSPVReg).addReg(sizeVReg);
14353 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14354 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14355 .addReg(SPLimitVReg);
14356 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14358 // bumpMBB simply decreases the stack pointer, since we know the current
14359 // stacklet has enough space.
14360 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14361 .addReg(SPLimitVReg);
14362 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14363 .addReg(SPLimitVReg);
14364 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14366 // Calls into a routine in libgcc to allocate more space from the heap.
14367 const uint32_t *RegMask =
14368 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14370 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14372 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14373 .addExternalSymbol("__morestack_allocate_stack_space")
14374 .addRegMask(RegMask)
14375 .addReg(X86::RDI, RegState::Implicit)
14376 .addReg(X86::RAX, RegState::ImplicitDefine);
14378 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14380 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14381 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14382 .addExternalSymbol("__morestack_allocate_stack_space")
14383 .addRegMask(RegMask)
14384 .addReg(X86::EAX, RegState::ImplicitDefine);
14388 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14391 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14392 .addReg(Is64Bit ? X86::RAX : X86::EAX);
14393 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14395 // Set up the CFG correctly.
14396 BB->addSuccessor(bumpMBB);
14397 BB->addSuccessor(mallocMBB);
14398 mallocMBB->addSuccessor(continueMBB);
14399 bumpMBB->addSuccessor(continueMBB);
14401 // Take care of the PHI nodes.
14402 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14403 MI->getOperand(0).getReg())
14404 .addReg(mallocPtrVReg).addMBB(mallocMBB)
14405 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14407 // Delete the original pseudo instruction.
14408 MI->eraseFromParent();
14411 return continueMBB;
14414 MachineBasicBlock *
14415 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14416 MachineBasicBlock *BB) const {
14417 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14418 DebugLoc DL = MI->getDebugLoc();
14420 assert(!Subtarget->isTargetEnvMacho());
14422 // The lowering is pretty easy: we're just emitting the call to _alloca. The
14423 // non-trivial part is impdef of ESP.
14425 if (Subtarget->isTargetWin64()) {
14426 if (Subtarget->isTargetCygMing()) {
14427 // ___chkstk(Mingw64):
14428 // Clobbers R10, R11, RAX and EFLAGS.
14430 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14431 .addExternalSymbol("___chkstk")
14432 .addReg(X86::RAX, RegState::Implicit)
14433 .addReg(X86::RSP, RegState::Implicit)
14434 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14435 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14436 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14438 // __chkstk(MSVCRT): does not update stack pointer.
14439 // Clobbers R10, R11 and EFLAGS.
14440 // FIXME: RAX(allocated size) might be reused and not killed.
14441 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14442 .addExternalSymbol("__chkstk")
14443 .addReg(X86::RAX, RegState::Implicit)
14444 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14445 // RAX has the offset to subtracted from RSP.
14446 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14451 const char *StackProbeSymbol =
14452 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14454 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14455 .addExternalSymbol(StackProbeSymbol)
14456 .addReg(X86::EAX, RegState::Implicit)
14457 .addReg(X86::ESP, RegState::Implicit)
14458 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14459 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14460 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14463 MI->eraseFromParent(); // The pseudo instruction is gone now.
14467 MachineBasicBlock *
14468 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14469 MachineBasicBlock *BB) const {
14470 // This is pretty easy. We're taking the value that we received from
14471 // our load from the relocation, sticking it in either RDI (x86-64)
14472 // or EAX and doing an indirect call. The return value will then
14473 // be in the normal return register.
14474 const X86InstrInfo *TII
14475 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14476 DebugLoc DL = MI->getDebugLoc();
14477 MachineFunction *F = BB->getParent();
14479 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14480 assert(MI->getOperand(3).isGlobal() && "This should be a global");
14482 // Get a register mask for the lowered call.
14483 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14484 // proper register mask.
14485 const uint32_t *RegMask =
14486 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14487 if (Subtarget->is64Bit()) {
14488 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14489 TII->get(X86::MOV64rm), X86::RDI)
14491 .addImm(0).addReg(0)
14492 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14493 MI->getOperand(3).getTargetFlags())
14495 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14496 addDirectMem(MIB, X86::RDI);
14497 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14498 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14499 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14500 TII->get(X86::MOV32rm), X86::EAX)
14502 .addImm(0).addReg(0)
14503 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14504 MI->getOperand(3).getTargetFlags())
14506 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14507 addDirectMem(MIB, X86::EAX);
14508 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14510 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14511 TII->get(X86::MOV32rm), X86::EAX)
14512 .addReg(TII->getGlobalBaseReg(F))
14513 .addImm(0).addReg(0)
14514 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14515 MI->getOperand(3).getTargetFlags())
14517 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14518 addDirectMem(MIB, X86::EAX);
14519 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14522 MI->eraseFromParent(); // The pseudo instruction is gone now.
14526 MachineBasicBlock *
14527 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14528 MachineBasicBlock *MBB) const {
14529 DebugLoc DL = MI->getDebugLoc();
14530 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14532 MachineFunction *MF = MBB->getParent();
14533 MachineRegisterInfo &MRI = MF->getRegInfo();
14535 const BasicBlock *BB = MBB->getBasicBlock();
14536 MachineFunction::iterator I = MBB;
14539 // Memory Reference
14540 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14541 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14544 unsigned MemOpndSlot = 0;
14546 unsigned CurOp = 0;
14548 DstReg = MI->getOperand(CurOp++).getReg();
14549 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14550 assert(RC->hasType(MVT::i32) && "Invalid destination!");
14551 unsigned mainDstReg = MRI.createVirtualRegister(RC);
14552 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14554 MemOpndSlot = CurOp;
14556 MVT PVT = getPointerTy();
14557 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14558 "Invalid Pointer Size!");
14560 // For v = setjmp(buf), we generate
14563 // buf[LabelOffset] = restoreMBB
14564 // SjLjSetup restoreMBB
14570 // v = phi(main, restore)
14575 MachineBasicBlock *thisMBB = MBB;
14576 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14577 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14578 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14579 MF->insert(I, mainMBB);
14580 MF->insert(I, sinkMBB);
14581 MF->push_back(restoreMBB);
14583 MachineInstrBuilder MIB;
14585 // Transfer the remainder of BB and its successor edges to sinkMBB.
14586 sinkMBB->splice(sinkMBB->begin(), MBB,
14587 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14588 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14591 unsigned PtrStoreOpc = 0;
14592 unsigned LabelReg = 0;
14593 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14594 Reloc::Model RM = getTargetMachine().getRelocationModel();
14595 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14596 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14598 // Prepare IP either in reg or imm.
14599 if (!UseImmLabel) {
14600 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14601 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14602 LabelReg = MRI.createVirtualRegister(PtrRC);
14603 if (Subtarget->is64Bit()) {
14604 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14608 .addMBB(restoreMBB)
14611 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14612 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14613 .addReg(XII->getGlobalBaseReg(MF))
14616 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14620 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14622 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14623 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14624 if (i == X86::AddrDisp)
14625 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14627 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14630 MIB.addReg(LabelReg);
14632 MIB.addMBB(restoreMBB);
14633 MIB.setMemRefs(MMOBegin, MMOEnd);
14635 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14636 .addMBB(restoreMBB);
14637 MIB.addRegMask(RegInfo->getNoPreservedMask());
14638 thisMBB->addSuccessor(mainMBB);
14639 thisMBB->addSuccessor(restoreMBB);
14643 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14644 mainMBB->addSuccessor(sinkMBB);
14647 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14648 TII->get(X86::PHI), DstReg)
14649 .addReg(mainDstReg).addMBB(mainMBB)
14650 .addReg(restoreDstReg).addMBB(restoreMBB);
14653 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14654 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14655 restoreMBB->addSuccessor(sinkMBB);
14657 MI->eraseFromParent();
14661 MachineBasicBlock *
14662 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14663 MachineBasicBlock *MBB) const {
14664 DebugLoc DL = MI->getDebugLoc();
14665 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14667 MachineFunction *MF = MBB->getParent();
14668 MachineRegisterInfo &MRI = MF->getRegInfo();
14670 // Memory Reference
14671 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14672 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14674 MVT PVT = getPointerTy();
14675 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14676 "Invalid Pointer Size!");
14678 const TargetRegisterClass *RC =
14679 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14680 unsigned Tmp = MRI.createVirtualRegister(RC);
14681 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14682 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14683 unsigned SP = RegInfo->getStackRegister();
14685 MachineInstrBuilder MIB;
14687 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14688 const int64_t SPOffset = 2 * PVT.getStoreSize();
14690 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14691 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14694 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14695 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14696 MIB.addOperand(MI->getOperand(i));
14697 MIB.setMemRefs(MMOBegin, MMOEnd);
14699 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14700 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14701 if (i == X86::AddrDisp)
14702 MIB.addDisp(MI->getOperand(i), LabelOffset);
14704 MIB.addOperand(MI->getOperand(i));
14706 MIB.setMemRefs(MMOBegin, MMOEnd);
14708 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14709 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14710 if (i == X86::AddrDisp)
14711 MIB.addDisp(MI->getOperand(i), SPOffset);
14713 MIB.addOperand(MI->getOperand(i));
14715 MIB.setMemRefs(MMOBegin, MMOEnd);
14717 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14719 MI->eraseFromParent();
14723 MachineBasicBlock *
14724 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14725 MachineBasicBlock *BB) const {
14726 switch (MI->getOpcode()) {
14727 default: llvm_unreachable("Unexpected instr type to insert");
14728 case X86::TAILJMPd64:
14729 case X86::TAILJMPr64:
14730 case X86::TAILJMPm64:
14731 llvm_unreachable("TAILJMP64 would not be touched here.");
14732 case X86::TCRETURNdi64:
14733 case X86::TCRETURNri64:
14734 case X86::TCRETURNmi64:
14736 case X86::WIN_ALLOCA:
14737 return EmitLoweredWinAlloca(MI, BB);
14738 case X86::SEG_ALLOCA_32:
14739 return EmitLoweredSegAlloca(MI, BB, false);
14740 case X86::SEG_ALLOCA_64:
14741 return EmitLoweredSegAlloca(MI, BB, true);
14742 case X86::TLSCall_32:
14743 case X86::TLSCall_64:
14744 return EmitLoweredTLSCall(MI, BB);
14745 case X86::CMOV_GR8:
14746 case X86::CMOV_FR32:
14747 case X86::CMOV_FR64:
14748 case X86::CMOV_V4F32:
14749 case X86::CMOV_V2F64:
14750 case X86::CMOV_V2I64:
14751 case X86::CMOV_V8F32:
14752 case X86::CMOV_V4F64:
14753 case X86::CMOV_V4I64:
14754 case X86::CMOV_GR16:
14755 case X86::CMOV_GR32:
14756 case X86::CMOV_RFP32:
14757 case X86::CMOV_RFP64:
14758 case X86::CMOV_RFP80:
14759 return EmitLoweredSelect(MI, BB);
14761 case X86::FP32_TO_INT16_IN_MEM:
14762 case X86::FP32_TO_INT32_IN_MEM:
14763 case X86::FP32_TO_INT64_IN_MEM:
14764 case X86::FP64_TO_INT16_IN_MEM:
14765 case X86::FP64_TO_INT32_IN_MEM:
14766 case X86::FP64_TO_INT64_IN_MEM:
14767 case X86::FP80_TO_INT16_IN_MEM:
14768 case X86::FP80_TO_INT32_IN_MEM:
14769 case X86::FP80_TO_INT64_IN_MEM: {
14770 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14771 DebugLoc DL = MI->getDebugLoc();
14773 // Change the floating point control register to use "round towards zero"
14774 // mode when truncating to an integer value.
14775 MachineFunction *F = BB->getParent();
14776 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14777 addFrameReference(BuildMI(*BB, MI, DL,
14778 TII->get(X86::FNSTCW16m)), CWFrameIdx);
14780 // Load the old value of the high byte of the control word...
14782 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14783 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14786 // Set the high part to be round to zero...
14787 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14790 // Reload the modified control word now...
14791 addFrameReference(BuildMI(*BB, MI, DL,
14792 TII->get(X86::FLDCW16m)), CWFrameIdx);
14794 // Restore the memory image of control word to original value
14795 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14798 // Get the X86 opcode to use.
14800 switch (MI->getOpcode()) {
14801 default: llvm_unreachable("illegal opcode!");
14802 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14803 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14804 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14805 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14806 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14807 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14808 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14809 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14810 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14814 MachineOperand &Op = MI->getOperand(0);
14816 AM.BaseType = X86AddressMode::RegBase;
14817 AM.Base.Reg = Op.getReg();
14819 AM.BaseType = X86AddressMode::FrameIndexBase;
14820 AM.Base.FrameIndex = Op.getIndex();
14822 Op = MI->getOperand(1);
14824 AM.Scale = Op.getImm();
14825 Op = MI->getOperand(2);
14827 AM.IndexReg = Op.getImm();
14828 Op = MI->getOperand(3);
14829 if (Op.isGlobal()) {
14830 AM.GV = Op.getGlobal();
14832 AM.Disp = Op.getImm();
14834 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14835 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14837 // Reload the original control word now.
14838 addFrameReference(BuildMI(*BB, MI, DL,
14839 TII->get(X86::FLDCW16m)), CWFrameIdx);
14841 MI->eraseFromParent(); // The pseudo instruction is gone now.
14844 // String/text processing lowering.
14845 case X86::PCMPISTRM128REG:
14846 case X86::VPCMPISTRM128REG:
14847 case X86::PCMPISTRM128MEM:
14848 case X86::VPCMPISTRM128MEM:
14849 case X86::PCMPESTRM128REG:
14850 case X86::VPCMPESTRM128REG:
14851 case X86::PCMPESTRM128MEM:
14852 case X86::VPCMPESTRM128MEM:
14853 assert(Subtarget->hasSSE42() &&
14854 "Target must have SSE4.2 or AVX features enabled");
14855 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14857 // String/text processing lowering.
14858 case X86::PCMPISTRIREG:
14859 case X86::VPCMPISTRIREG:
14860 case X86::PCMPISTRIMEM:
14861 case X86::VPCMPISTRIMEM:
14862 case X86::PCMPESTRIREG:
14863 case X86::VPCMPESTRIREG:
14864 case X86::PCMPESTRIMEM:
14865 case X86::VPCMPESTRIMEM:
14866 assert(Subtarget->hasSSE42() &&
14867 "Target must have SSE4.2 or AVX features enabled");
14868 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14870 // Thread synchronization.
14872 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14876 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14878 // Atomic Lowering.
14879 case X86::ATOMAND8:
14880 case X86::ATOMAND16:
14881 case X86::ATOMAND32:
14882 case X86::ATOMAND64:
14885 case X86::ATOMOR16:
14886 case X86::ATOMOR32:
14887 case X86::ATOMOR64:
14889 case X86::ATOMXOR16:
14890 case X86::ATOMXOR8:
14891 case X86::ATOMXOR32:
14892 case X86::ATOMXOR64:
14894 case X86::ATOMNAND8:
14895 case X86::ATOMNAND16:
14896 case X86::ATOMNAND32:
14897 case X86::ATOMNAND64:
14899 case X86::ATOMMAX8:
14900 case X86::ATOMMAX16:
14901 case X86::ATOMMAX32:
14902 case X86::ATOMMAX64:
14904 case X86::ATOMMIN8:
14905 case X86::ATOMMIN16:
14906 case X86::ATOMMIN32:
14907 case X86::ATOMMIN64:
14909 case X86::ATOMUMAX8:
14910 case X86::ATOMUMAX16:
14911 case X86::ATOMUMAX32:
14912 case X86::ATOMUMAX64:
14914 case X86::ATOMUMIN8:
14915 case X86::ATOMUMIN16:
14916 case X86::ATOMUMIN32:
14917 case X86::ATOMUMIN64:
14918 return EmitAtomicLoadArith(MI, BB);
14920 // This group does 64-bit operations on a 32-bit host.
14921 case X86::ATOMAND6432:
14922 case X86::ATOMOR6432:
14923 case X86::ATOMXOR6432:
14924 case X86::ATOMNAND6432:
14925 case X86::ATOMADD6432:
14926 case X86::ATOMSUB6432:
14927 case X86::ATOMMAX6432:
14928 case X86::ATOMMIN6432:
14929 case X86::ATOMUMAX6432:
14930 case X86::ATOMUMIN6432:
14931 case X86::ATOMSWAP6432:
14932 return EmitAtomicLoadArith6432(MI, BB);
14934 case X86::VASTART_SAVE_XMM_REGS:
14935 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14937 case X86::VAARG_64:
14938 return EmitVAARG64WithCustomInserter(MI, BB);
14940 case X86::EH_SjLj_SetJmp32:
14941 case X86::EH_SjLj_SetJmp64:
14942 return emitEHSjLjSetJmp(MI, BB);
14944 case X86::EH_SjLj_LongJmp32:
14945 case X86::EH_SjLj_LongJmp64:
14946 return emitEHSjLjLongJmp(MI, BB);
14950 //===----------------------------------------------------------------------===//
14951 // X86 Optimization Hooks
14952 //===----------------------------------------------------------------------===//
14954 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14957 const SelectionDAG &DAG,
14958 unsigned Depth) const {
14959 unsigned BitWidth = KnownZero.getBitWidth();
14960 unsigned Opc = Op.getOpcode();
14961 assert((Opc >= ISD::BUILTIN_OP_END ||
14962 Opc == ISD::INTRINSIC_WO_CHAIN ||
14963 Opc == ISD::INTRINSIC_W_CHAIN ||
14964 Opc == ISD::INTRINSIC_VOID) &&
14965 "Should use MaskedValueIsZero if you don't know whether Op"
14966 " is a target node!");
14968 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14982 // These nodes' second result is a boolean.
14983 if (Op.getResNo() == 0)
14986 case X86ISD::SETCC:
14987 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14989 case ISD::INTRINSIC_WO_CHAIN: {
14990 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14991 unsigned NumLoBits = 0;
14994 case Intrinsic::x86_sse_movmsk_ps:
14995 case Intrinsic::x86_avx_movmsk_ps_256:
14996 case Intrinsic::x86_sse2_movmsk_pd:
14997 case Intrinsic::x86_avx_movmsk_pd_256:
14998 case Intrinsic::x86_mmx_pmovmskb:
14999 case Intrinsic::x86_sse2_pmovmskb_128:
15000 case Intrinsic::x86_avx2_pmovmskb: {
15001 // High bits of movmskp{s|d}, pmovmskb are known zero.
15003 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15004 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
15005 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
15006 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
15007 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
15008 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
15009 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
15010 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
15012 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15021 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15022 unsigned Depth) const {
15023 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15024 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15025 return Op.getValueType().getScalarType().getSizeInBits();
15031 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15032 /// node is a GlobalAddress + offset.
15033 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15034 const GlobalValue* &GA,
15035 int64_t &Offset) const {
15036 if (N->getOpcode() == X86ISD::Wrapper) {
15037 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15038 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15039 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15043 return TargetLowering::isGAPlusOffset(N, GA, Offset);
15046 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15047 /// same as extracting the high 128-bit part of 256-bit vector and then
15048 /// inserting the result into the low part of a new 256-bit vector
15049 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15050 EVT VT = SVOp->getValueType(0);
15051 unsigned NumElems = VT.getVectorNumElements();
15053 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15054 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15055 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15056 SVOp->getMaskElt(j) >= 0)
15062 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15063 /// same as extracting the low 128-bit part of 256-bit vector and then
15064 /// inserting the result into the high part of a new 256-bit vector
15065 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15066 EVT VT = SVOp->getValueType(0);
15067 unsigned NumElems = VT.getVectorNumElements();
15069 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15070 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15071 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15072 SVOp->getMaskElt(j) >= 0)
15078 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15079 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15080 TargetLowering::DAGCombinerInfo &DCI,
15081 const X86Subtarget* Subtarget) {
15082 DebugLoc dl = N->getDebugLoc();
15083 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15084 SDValue V1 = SVOp->getOperand(0);
15085 SDValue V2 = SVOp->getOperand(1);
15086 EVT VT = SVOp->getValueType(0);
15087 unsigned NumElems = VT.getVectorNumElements();
15089 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15090 V2.getOpcode() == ISD::CONCAT_VECTORS) {
15094 // V UNDEF BUILD_VECTOR UNDEF
15096 // CONCAT_VECTOR CONCAT_VECTOR
15099 // RESULT: V + zero extended
15101 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15102 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15103 V1.getOperand(1).getOpcode() != ISD::UNDEF)
15106 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15109 // To match the shuffle mask, the first half of the mask should
15110 // be exactly the first vector, and all the rest a splat with the
15111 // first element of the second one.
15112 for (unsigned i = 0; i != NumElems/2; ++i)
15113 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15114 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15117 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15118 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15119 if (Ld->hasNUsesOfValue(1, 0)) {
15120 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15121 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15123 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
15125 Ld->getPointerInfo(),
15126 Ld->getAlignment(),
15127 false/*isVolatile*/, true/*ReadMem*/,
15128 false/*WriteMem*/);
15130 // Make sure the newly-created LOAD is in the same position as Ld in
15131 // terms of dependency. We create a TokenFactor for Ld and ResNode,
15132 // and update uses of Ld's output chain to use the TokenFactor.
15133 if (Ld->hasAnyUseOfValue(1)) {
15134 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15135 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15136 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15137 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15138 SDValue(ResNode.getNode(), 1));
15141 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15145 // Emit a zeroed vector and insert the desired subvector on its
15147 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15148 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15149 return DCI.CombineTo(N, InsV);
15152 //===--------------------------------------------------------------------===//
15153 // Combine some shuffles into subvector extracts and inserts:
15156 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15157 if (isShuffleHigh128VectorInsertLow(SVOp)) {
15158 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15159 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15160 return DCI.CombineTo(N, InsV);
15163 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15164 if (isShuffleLow128VectorInsertHigh(SVOp)) {
15165 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15166 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15167 return DCI.CombineTo(N, InsV);
15173 /// PerformShuffleCombine - Performs several different shuffle combines.
15174 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15175 TargetLowering::DAGCombinerInfo &DCI,
15176 const X86Subtarget *Subtarget) {
15177 DebugLoc dl = N->getDebugLoc();
15178 EVT VT = N->getValueType(0);
15180 // Don't create instructions with illegal types after legalize types has run.
15181 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15182 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15185 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15186 if (Subtarget->hasFp256() && VT.is256BitVector() &&
15187 N->getOpcode() == ISD::VECTOR_SHUFFLE)
15188 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15190 // Only handle 128 wide vector from here on.
15191 if (!VT.is128BitVector())
15194 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15195 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15196 // consecutive, non-overlapping, and in the right order.
15197 SmallVector<SDValue, 16> Elts;
15198 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15199 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15201 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15204 /// PerformTruncateCombine - Converts truncate operation to
15205 /// a sequence of vector shuffle operations.
15206 /// It is possible when we truncate 256-bit vector to 128-bit vector
15207 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15208 TargetLowering::DAGCombinerInfo &DCI,
15209 const X86Subtarget *Subtarget) {
15213 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15214 /// specific shuffle of a load can be folded into a single element load.
15215 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15216 /// shuffles have been customed lowered so we need to handle those here.
15217 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15218 TargetLowering::DAGCombinerInfo &DCI) {
15219 if (DCI.isBeforeLegalizeOps())
15222 SDValue InVec = N->getOperand(0);
15223 SDValue EltNo = N->getOperand(1);
15225 if (!isa<ConstantSDNode>(EltNo))
15228 EVT VT = InVec.getValueType();
15230 bool HasShuffleIntoBitcast = false;
15231 if (InVec.getOpcode() == ISD::BITCAST) {
15232 // Don't duplicate a load with other uses.
15233 if (!InVec.hasOneUse())
15235 EVT BCVT = InVec.getOperand(0).getValueType();
15236 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15238 InVec = InVec.getOperand(0);
15239 HasShuffleIntoBitcast = true;
15242 if (!isTargetShuffle(InVec.getOpcode()))
15245 // Don't duplicate a load with other uses.
15246 if (!InVec.hasOneUse())
15249 SmallVector<int, 16> ShuffleMask;
15251 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15255 // Select the input vector, guarding against out of range extract vector.
15256 unsigned NumElems = VT.getVectorNumElements();
15257 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15258 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15259 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15260 : InVec.getOperand(1);
15262 // If inputs to shuffle are the same for both ops, then allow 2 uses
15263 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15265 if (LdNode.getOpcode() == ISD::BITCAST) {
15266 // Don't duplicate a load with other uses.
15267 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15270 AllowedUses = 1; // only allow 1 load use if we have a bitcast
15271 LdNode = LdNode.getOperand(0);
15274 if (!ISD::isNormalLoad(LdNode.getNode()))
15277 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15279 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15282 if (HasShuffleIntoBitcast) {
15283 // If there's a bitcast before the shuffle, check if the load type and
15284 // alignment is valid.
15285 unsigned Align = LN0->getAlignment();
15286 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15287 unsigned NewAlign = TLI.getDataLayout()->
15288 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15290 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15294 // All checks match so transform back to vector_shuffle so that DAG combiner
15295 // can finish the job
15296 DebugLoc dl = N->getDebugLoc();
15298 // Create shuffle node taking into account the case that its a unary shuffle
15299 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15300 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15301 InVec.getOperand(0), Shuffle,
15303 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15304 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15308 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15309 /// generation and convert it from being a bunch of shuffles and extracts
15310 /// to a simple store and scalar loads to extract the elements.
15311 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15312 TargetLowering::DAGCombinerInfo &DCI) {
15313 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15314 if (NewOp.getNode())
15317 SDValue InputVector = N->getOperand(0);
15318 // Detect whether we are trying to convert from mmx to i32 and the bitcast
15319 // from mmx to v2i32 has a single usage.
15320 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15321 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15322 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15323 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15324 N->getValueType(0),
15325 InputVector.getNode()->getOperand(0));
15327 // Only operate on vectors of 4 elements, where the alternative shuffling
15328 // gets to be more expensive.
15329 if (InputVector.getValueType() != MVT::v4i32)
15332 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15333 // single use which is a sign-extend or zero-extend, and all elements are
15335 SmallVector<SDNode *, 4> Uses;
15336 unsigned ExtractedElements = 0;
15337 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15338 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15339 if (UI.getUse().getResNo() != InputVector.getResNo())
15342 SDNode *Extract = *UI;
15343 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15346 if (Extract->getValueType(0) != MVT::i32)
15348 if (!Extract->hasOneUse())
15350 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15351 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15353 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15356 // Record which element was extracted.
15357 ExtractedElements |=
15358 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15360 Uses.push_back(Extract);
15363 // If not all the elements were used, this may not be worthwhile.
15364 if (ExtractedElements != 15)
15367 // Ok, we've now decided to do the transformation.
15368 DebugLoc dl = InputVector.getDebugLoc();
15370 // Store the value to a temporary stack slot.
15371 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15372 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15373 MachinePointerInfo(), false, false, 0);
15375 // Replace each use (extract) with a load of the appropriate element.
15376 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15377 UE = Uses.end(); UI != UE; ++UI) {
15378 SDNode *Extract = *UI;
15380 // cOMpute the element's address.
15381 SDValue Idx = Extract->getOperand(1);
15383 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15384 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15385 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15386 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15388 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15389 StackPtr, OffsetVal);
15391 // Load the scalar.
15392 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15393 ScalarAddr, MachinePointerInfo(),
15394 false, false, false, 0);
15396 // Replace the exact with the load.
15397 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15400 // The replacement was made in place; don't return anything.
15404 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15405 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15406 SDValue RHS, SelectionDAG &DAG,
15407 const X86Subtarget *Subtarget) {
15408 if (!VT.isVector())
15411 switch (VT.getSimpleVT().SimpleTy) {
15416 if (!Subtarget->hasAVX2())
15421 if (!Subtarget->hasSSE2())
15425 // SSE2 has only a small subset of the operations.
15426 bool hasUnsigned = Subtarget->hasSSE41() ||
15427 (Subtarget->hasSSE2() && VT == MVT::v16i8);
15428 bool hasSigned = Subtarget->hasSSE41() ||
15429 (Subtarget->hasSSE2() && VT == MVT::v8i16);
15431 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15433 // Check for x CC y ? x : y.
15434 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15435 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15440 return hasUnsigned ? X86ISD::UMIN : 0;
15443 return hasUnsigned ? X86ISD::UMAX : 0;
15446 return hasSigned ? X86ISD::SMIN : 0;
15449 return hasSigned ? X86ISD::SMAX : 0;
15451 // Check for x CC y ? y : x -- a min/max with reversed arms.
15452 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15453 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15458 return hasUnsigned ? X86ISD::UMAX : 0;
15461 return hasUnsigned ? X86ISD::UMIN : 0;
15464 return hasSigned ? X86ISD::SMAX : 0;
15467 return hasSigned ? X86ISD::SMIN : 0;
15474 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15476 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15477 TargetLowering::DAGCombinerInfo &DCI,
15478 const X86Subtarget *Subtarget) {
15479 DebugLoc DL = N->getDebugLoc();
15480 SDValue Cond = N->getOperand(0);
15481 // Get the LHS/RHS of the select.
15482 SDValue LHS = N->getOperand(1);
15483 SDValue RHS = N->getOperand(2);
15484 EVT VT = LHS.getValueType();
15486 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15487 // instructions match the semantics of the common C idiom x<y?x:y but not
15488 // x<=y?x:y, because of how they handle negative zero (which can be
15489 // ignored in unsafe-math mode).
15490 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15491 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15492 (Subtarget->hasSSE2() ||
15493 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15494 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15496 unsigned Opcode = 0;
15497 // Check for x CC y ? x : y.
15498 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15499 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15503 // Converting this to a min would handle NaNs incorrectly, and swapping
15504 // the operands would cause it to handle comparisons between positive
15505 // and negative zero incorrectly.
15506 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15507 if (!DAG.getTarget().Options.UnsafeFPMath &&
15508 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15510 std::swap(LHS, RHS);
15512 Opcode = X86ISD::FMIN;
15515 // Converting this to a min would handle comparisons between positive
15516 // and negative zero incorrectly.
15517 if (!DAG.getTarget().Options.UnsafeFPMath &&
15518 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15520 Opcode = X86ISD::FMIN;
15523 // Converting this to a min would handle both negative zeros and NaNs
15524 // incorrectly, but we can swap the operands to fix both.
15525 std::swap(LHS, RHS);
15529 Opcode = X86ISD::FMIN;
15533 // Converting this to a max would handle comparisons between positive
15534 // and negative zero incorrectly.
15535 if (!DAG.getTarget().Options.UnsafeFPMath &&
15536 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15538 Opcode = X86ISD::FMAX;
15541 // Converting this to a max would handle NaNs incorrectly, and swapping
15542 // the operands would cause it to handle comparisons between positive
15543 // and negative zero incorrectly.
15544 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15545 if (!DAG.getTarget().Options.UnsafeFPMath &&
15546 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15548 std::swap(LHS, RHS);
15550 Opcode = X86ISD::FMAX;
15553 // Converting this to a max would handle both negative zeros and NaNs
15554 // incorrectly, but we can swap the operands to fix both.
15555 std::swap(LHS, RHS);
15559 Opcode = X86ISD::FMAX;
15562 // Check for x CC y ? y : x -- a min/max with reversed arms.
15563 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15564 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15568 // Converting this to a min would handle comparisons between positive
15569 // and negative zero incorrectly, and swapping the operands would
15570 // cause it to handle NaNs incorrectly.
15571 if (!DAG.getTarget().Options.UnsafeFPMath &&
15572 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15573 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15575 std::swap(LHS, RHS);
15577 Opcode = X86ISD::FMIN;
15580 // Converting this to a min would handle NaNs incorrectly.
15581 if (!DAG.getTarget().Options.UnsafeFPMath &&
15582 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15584 Opcode = X86ISD::FMIN;
15587 // Converting this to a min would handle both negative zeros and NaNs
15588 // incorrectly, but we can swap the operands to fix both.
15589 std::swap(LHS, RHS);
15593 Opcode = X86ISD::FMIN;
15597 // Converting this to a max would handle NaNs incorrectly.
15598 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15600 Opcode = X86ISD::FMAX;
15603 // Converting this to a max would handle comparisons between positive
15604 // and negative zero incorrectly, and swapping the operands would
15605 // cause it to handle NaNs incorrectly.
15606 if (!DAG.getTarget().Options.UnsafeFPMath &&
15607 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15608 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15610 std::swap(LHS, RHS);
15612 Opcode = X86ISD::FMAX;
15615 // Converting this to a max would handle both negative zeros and NaNs
15616 // incorrectly, but we can swap the operands to fix both.
15617 std::swap(LHS, RHS);
15621 Opcode = X86ISD::FMAX;
15627 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15630 // If this is a select between two integer constants, try to do some
15632 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15633 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15634 // Don't do this for crazy integer types.
15635 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15636 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15637 // so that TrueC (the true value) is larger than FalseC.
15638 bool NeedsCondInvert = false;
15640 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15641 // Efficiently invertible.
15642 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15643 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15644 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15645 NeedsCondInvert = true;
15646 std::swap(TrueC, FalseC);
15649 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15650 if (FalseC->getAPIntValue() == 0 &&
15651 TrueC->getAPIntValue().isPowerOf2()) {
15652 if (NeedsCondInvert) // Invert the condition if needed.
15653 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15654 DAG.getConstant(1, Cond.getValueType()));
15656 // Zero extend the condition if needed.
15657 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15659 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15660 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15661 DAG.getConstant(ShAmt, MVT::i8));
15664 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15665 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15666 if (NeedsCondInvert) // Invert the condition if needed.
15667 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15668 DAG.getConstant(1, Cond.getValueType()));
15670 // Zero extend the condition if needed.
15671 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15672 FalseC->getValueType(0), Cond);
15673 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15674 SDValue(FalseC, 0));
15677 // Optimize cases that will turn into an LEA instruction. This requires
15678 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15679 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15680 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15681 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15683 bool isFastMultiplier = false;
15685 switch ((unsigned char)Diff) {
15687 case 1: // result = add base, cond
15688 case 2: // result = lea base( , cond*2)
15689 case 3: // result = lea base(cond, cond*2)
15690 case 4: // result = lea base( , cond*4)
15691 case 5: // result = lea base(cond, cond*4)
15692 case 8: // result = lea base( , cond*8)
15693 case 9: // result = lea base(cond, cond*8)
15694 isFastMultiplier = true;
15699 if (isFastMultiplier) {
15700 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15701 if (NeedsCondInvert) // Invert the condition if needed.
15702 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15703 DAG.getConstant(1, Cond.getValueType()));
15705 // Zero extend the condition if needed.
15706 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15708 // Scale the condition by the difference.
15710 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15711 DAG.getConstant(Diff, Cond.getValueType()));
15713 // Add the base if non-zero.
15714 if (FalseC->getAPIntValue() != 0)
15715 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15716 SDValue(FalseC, 0));
15723 // Canonicalize max and min:
15724 // (x > y) ? x : y -> (x >= y) ? x : y
15725 // (x < y) ? x : y -> (x <= y) ? x : y
15726 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15727 // the need for an extra compare
15728 // against zero. e.g.
15729 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15731 // testl %edi, %edi
15733 // cmovgl %edi, %eax
15737 // cmovsl %eax, %edi
15738 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15739 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15740 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15741 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15746 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15747 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15748 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15749 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15754 // Match VSELECTs into subs with unsigned saturation.
15755 if (!DCI.isBeforeLegalize() &&
15756 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15757 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15758 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15759 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15760 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15762 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15763 // left side invert the predicate to simplify logic below.
15765 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15767 CC = ISD::getSetCCInverse(CC, true);
15768 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15772 if (Other.getNode() && Other->getNumOperands() == 2 &&
15773 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15774 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15775 SDValue CondRHS = Cond->getOperand(1);
15777 // Look for a general sub with unsigned saturation first.
15778 // x >= y ? x-y : 0 --> subus x, y
15779 // x > y ? x-y : 0 --> subus x, y
15780 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15781 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15782 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15784 // If the RHS is a constant we have to reverse the const canonicalization.
15785 // x > C-1 ? x+-C : 0 --> subus x, C
15786 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15787 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15788 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15789 if (CondRHS.getConstantOperandVal(0) == -A-1)
15790 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15791 DAG.getConstant(-A, VT));
15794 // Another special case: If C was a sign bit, the sub has been
15795 // canonicalized into a xor.
15796 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15797 // it's safe to decanonicalize the xor?
15798 // x s< 0 ? x^C : 0 --> subus x, C
15799 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15800 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15801 isSplatVector(OpRHS.getNode())) {
15802 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15804 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15809 // Try to match a min/max vector operation.
15810 if (!DCI.isBeforeLegalize() &&
15811 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15812 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15813 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15815 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15816 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15817 Cond.getOpcode() == ISD::SETCC) {
15819 assert(Cond.getValueType().isVector() &&
15820 "vector select expects a vector selector!");
15822 EVT IntVT = Cond.getValueType();
15823 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15824 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15826 if (!TValIsAllOnes && !FValIsAllZeros) {
15827 // Try invert the condition if true value is not all 1s and false value
15829 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15830 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15832 if (TValIsAllZeros || FValIsAllOnes) {
15833 SDValue CC = Cond.getOperand(2);
15834 ISD::CondCode NewCC =
15835 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15836 Cond.getOperand(0).getValueType().isInteger());
15837 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15838 std::swap(LHS, RHS);
15839 TValIsAllOnes = FValIsAllOnes;
15840 FValIsAllZeros = TValIsAllZeros;
15844 if (TValIsAllOnes || FValIsAllZeros) {
15847 if (TValIsAllOnes && FValIsAllZeros)
15849 else if (TValIsAllOnes)
15850 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15851 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15852 else if (FValIsAllZeros)
15853 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15854 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15856 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15860 // If we know that this node is legal then we know that it is going to be
15861 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15862 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15863 // to simplify previous instructions.
15864 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15865 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15866 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15867 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15869 // Don't optimize vector selects that map to mask-registers.
15873 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15874 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15876 APInt KnownZero, KnownOne;
15877 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15878 DCI.isBeforeLegalizeOps());
15879 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15880 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15881 DCI.CommitTargetLoweringOpt(TLO);
15887 // Check whether a boolean test is testing a boolean value generated by
15888 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15891 // Simplify the following patterns:
15892 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15893 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15894 // to (Op EFLAGS Cond)
15896 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15897 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15898 // to (Op EFLAGS !Cond)
15900 // where Op could be BRCOND or CMOV.
15902 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15903 // Quit if not CMP and SUB with its value result used.
15904 if (Cmp.getOpcode() != X86ISD::CMP &&
15905 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15908 // Quit if not used as a boolean value.
15909 if (CC != X86::COND_E && CC != X86::COND_NE)
15912 // Check CMP operands. One of them should be 0 or 1 and the other should be
15913 // an SetCC or extended from it.
15914 SDValue Op1 = Cmp.getOperand(0);
15915 SDValue Op2 = Cmp.getOperand(1);
15918 const ConstantSDNode* C = 0;
15919 bool needOppositeCond = (CC == X86::COND_E);
15920 bool checkAgainstTrue = false; // Is it a comparison against 1?
15922 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15924 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15926 else // Quit if all operands are not constants.
15929 if (C->getZExtValue() == 1) {
15930 needOppositeCond = !needOppositeCond;
15931 checkAgainstTrue = true;
15932 } else if (C->getZExtValue() != 0)
15933 // Quit if the constant is neither 0 or 1.
15936 bool truncatedToBoolWithAnd = false;
15937 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15938 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15939 SetCC.getOpcode() == ISD::TRUNCATE ||
15940 SetCC.getOpcode() == ISD::AND) {
15941 if (SetCC.getOpcode() == ISD::AND) {
15943 ConstantSDNode *CS;
15944 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15945 CS->getZExtValue() == 1)
15947 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15948 CS->getZExtValue() == 1)
15952 SetCC = SetCC.getOperand(OpIdx);
15953 truncatedToBoolWithAnd = true;
15955 SetCC = SetCC.getOperand(0);
15958 switch (SetCC.getOpcode()) {
15959 case X86ISD::SETCC_CARRY:
15960 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15961 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15962 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15963 // truncated to i1 using 'and'.
15964 if (checkAgainstTrue && !truncatedToBoolWithAnd)
15966 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15967 "Invalid use of SETCC_CARRY!");
15969 case X86ISD::SETCC:
15970 // Set the condition code or opposite one if necessary.
15971 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15972 if (needOppositeCond)
15973 CC = X86::GetOppositeBranchCondition(CC);
15974 return SetCC.getOperand(1);
15975 case X86ISD::CMOV: {
15976 // Check whether false/true value has canonical one, i.e. 0 or 1.
15977 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15978 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15979 // Quit if true value is not a constant.
15982 // Quit if false value is not a constant.
15984 SDValue Op = SetCC.getOperand(0);
15985 // Skip 'zext' or 'trunc' node.
15986 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15987 Op.getOpcode() == ISD::TRUNCATE)
15988 Op = Op.getOperand(0);
15989 // A special case for rdrand/rdseed, where 0 is set if false cond is
15991 if ((Op.getOpcode() != X86ISD::RDRAND &&
15992 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15995 // Quit if false value is not the constant 0 or 1.
15996 bool FValIsFalse = true;
15997 if (FVal && FVal->getZExtValue() != 0) {
15998 if (FVal->getZExtValue() != 1)
16000 // If FVal is 1, opposite cond is needed.
16001 needOppositeCond = !needOppositeCond;
16002 FValIsFalse = false;
16004 // Quit if TVal is not the constant opposite of FVal.
16005 if (FValIsFalse && TVal->getZExtValue() != 1)
16007 if (!FValIsFalse && TVal->getZExtValue() != 0)
16009 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16010 if (needOppositeCond)
16011 CC = X86::GetOppositeBranchCondition(CC);
16012 return SetCC.getOperand(3);
16019 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16020 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16021 TargetLowering::DAGCombinerInfo &DCI,
16022 const X86Subtarget *Subtarget) {
16023 DebugLoc DL = N->getDebugLoc();
16025 // If the flag operand isn't dead, don't touch this CMOV.
16026 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16029 SDValue FalseOp = N->getOperand(0);
16030 SDValue TrueOp = N->getOperand(1);
16031 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16032 SDValue Cond = N->getOperand(3);
16034 if (CC == X86::COND_E || CC == X86::COND_NE) {
16035 switch (Cond.getOpcode()) {
16039 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16040 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16041 return (CC == X86::COND_E) ? FalseOp : TrueOp;
16047 Flags = checkBoolTestSetCCCombine(Cond, CC);
16048 if (Flags.getNode() &&
16049 // Extra check as FCMOV only supports a subset of X86 cond.
16050 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16051 SDValue Ops[] = { FalseOp, TrueOp,
16052 DAG.getConstant(CC, MVT::i8), Flags };
16053 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16054 Ops, array_lengthof(Ops));
16057 // If this is a select between two integer constants, try to do some
16058 // optimizations. Note that the operands are ordered the opposite of SELECT
16060 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16061 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16062 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16063 // larger than FalseC (the false value).
16064 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16065 CC = X86::GetOppositeBranchCondition(CC);
16066 std::swap(TrueC, FalseC);
16067 std::swap(TrueOp, FalseOp);
16070 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
16071 // This is efficient for any integer data type (including i8/i16) and
16073 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16074 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16075 DAG.getConstant(CC, MVT::i8), Cond);
16077 // Zero extend the condition if needed.
16078 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16080 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16081 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16082 DAG.getConstant(ShAmt, MVT::i8));
16083 if (N->getNumValues() == 2) // Dead flag value?
16084 return DCI.CombineTo(N, Cond, SDValue());
16088 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
16089 // for any integer data type, including i8/i16.
16090 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16091 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16092 DAG.getConstant(CC, MVT::i8), Cond);
16094 // Zero extend the condition if needed.
16095 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16096 FalseC->getValueType(0), Cond);
16097 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16098 SDValue(FalseC, 0));
16100 if (N->getNumValues() == 2) // Dead flag value?
16101 return DCI.CombineTo(N, Cond, SDValue());
16105 // Optimize cases that will turn into an LEA instruction. This requires
16106 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16107 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16108 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16109 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16111 bool isFastMultiplier = false;
16113 switch ((unsigned char)Diff) {
16115 case 1: // result = add base, cond
16116 case 2: // result = lea base( , cond*2)
16117 case 3: // result = lea base(cond, cond*2)
16118 case 4: // result = lea base( , cond*4)
16119 case 5: // result = lea base(cond, cond*4)
16120 case 8: // result = lea base( , cond*8)
16121 case 9: // result = lea base(cond, cond*8)
16122 isFastMultiplier = true;
16127 if (isFastMultiplier) {
16128 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16129 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16130 DAG.getConstant(CC, MVT::i8), Cond);
16131 // Zero extend the condition if needed.
16132 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16134 // Scale the condition by the difference.
16136 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16137 DAG.getConstant(Diff, Cond.getValueType()));
16139 // Add the base if non-zero.
16140 if (FalseC->getAPIntValue() != 0)
16141 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16142 SDValue(FalseC, 0));
16143 if (N->getNumValues() == 2) // Dead flag value?
16144 return DCI.CombineTo(N, Cond, SDValue());
16151 // Handle these cases:
16152 // (select (x != c), e, c) -> select (x != c), e, x),
16153 // (select (x == c), c, e) -> select (x == c), x, e)
16154 // where the c is an integer constant, and the "select" is the combination
16155 // of CMOV and CMP.
16157 // The rationale for this change is that the conditional-move from a constant
16158 // needs two instructions, however, conditional-move from a register needs
16159 // only one instruction.
16161 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16162 // some instruction-combining opportunities. This opt needs to be
16163 // postponed as late as possible.
16165 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16166 // the DCI.xxxx conditions are provided to postpone the optimization as
16167 // late as possible.
16169 ConstantSDNode *CmpAgainst = 0;
16170 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16171 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16172 !isa<ConstantSDNode>(Cond.getOperand(0))) {
16174 if (CC == X86::COND_NE &&
16175 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16176 CC = X86::GetOppositeBranchCondition(CC);
16177 std::swap(TrueOp, FalseOp);
16180 if (CC == X86::COND_E &&
16181 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16182 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16183 DAG.getConstant(CC, MVT::i8), Cond };
16184 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16185 array_lengthof(Ops));
16193 /// PerformMulCombine - Optimize a single multiply with constant into two
16194 /// in order to implement it with two cheaper instructions, e.g.
16195 /// LEA + SHL, LEA + LEA.
16196 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16197 TargetLowering::DAGCombinerInfo &DCI) {
16198 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16201 EVT VT = N->getValueType(0);
16202 if (VT != MVT::i64)
16205 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16208 uint64_t MulAmt = C->getZExtValue();
16209 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16212 uint64_t MulAmt1 = 0;
16213 uint64_t MulAmt2 = 0;
16214 if ((MulAmt % 9) == 0) {
16216 MulAmt2 = MulAmt / 9;
16217 } else if ((MulAmt % 5) == 0) {
16219 MulAmt2 = MulAmt / 5;
16220 } else if ((MulAmt % 3) == 0) {
16222 MulAmt2 = MulAmt / 3;
16225 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16226 DebugLoc DL = N->getDebugLoc();
16228 if (isPowerOf2_64(MulAmt2) &&
16229 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16230 // If second multiplifer is pow2, issue it first. We want the multiply by
16231 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16233 std::swap(MulAmt1, MulAmt2);
16236 if (isPowerOf2_64(MulAmt1))
16237 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16238 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16240 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16241 DAG.getConstant(MulAmt1, VT));
16243 if (isPowerOf2_64(MulAmt2))
16244 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16245 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16247 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16248 DAG.getConstant(MulAmt2, VT));
16250 // Do not add new nodes to DAG combiner worklist.
16251 DCI.CombineTo(N, NewMul, false);
16256 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16257 SDValue N0 = N->getOperand(0);
16258 SDValue N1 = N->getOperand(1);
16259 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16260 EVT VT = N0.getValueType();
16262 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16263 // since the result of setcc_c is all zero's or all ones.
16264 if (VT.isInteger() && !VT.isVector() &&
16265 N1C && N0.getOpcode() == ISD::AND &&
16266 N0.getOperand(1).getOpcode() == ISD::Constant) {
16267 SDValue N00 = N0.getOperand(0);
16268 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16269 ((N00.getOpcode() == ISD::ANY_EXTEND ||
16270 N00.getOpcode() == ISD::ZERO_EXTEND) &&
16271 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16272 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16273 APInt ShAmt = N1C->getAPIntValue();
16274 Mask = Mask.shl(ShAmt);
16276 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16277 N00, DAG.getConstant(Mask, VT));
16281 // Hardware support for vector shifts is sparse which makes us scalarize the
16282 // vector operations in many cases. Also, on sandybridge ADD is faster than
16284 // (shl V, 1) -> add V,V
16285 if (isSplatVector(N1.getNode())) {
16286 assert(N0.getValueType().isVector() && "Invalid vector shift type");
16287 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16288 // We shift all of the values by one. In many cases we do not have
16289 // hardware support for this operation. This is better expressed as an ADD
16291 if (N1C && (1 == N1C->getZExtValue())) {
16292 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16299 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
16301 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16302 TargetLowering::DAGCombinerInfo &DCI,
16303 const X86Subtarget *Subtarget) {
16304 if (N->getOpcode() == ISD::SHL) {
16305 SDValue V = PerformSHLCombine(N, DAG);
16306 if (V.getNode()) return V;
16312 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
16313 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16314 // and friends. Likewise for OR -> CMPNEQSS.
16315 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16316 TargetLowering::DAGCombinerInfo &DCI,
16317 const X86Subtarget *Subtarget) {
16320 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16321 // we're requiring SSE2 for both.
16322 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16323 SDValue N0 = N->getOperand(0);
16324 SDValue N1 = N->getOperand(1);
16325 SDValue CMP0 = N0->getOperand(1);
16326 SDValue CMP1 = N1->getOperand(1);
16327 DebugLoc DL = N->getDebugLoc();
16329 // The SETCCs should both refer to the same CMP.
16330 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16333 SDValue CMP00 = CMP0->getOperand(0);
16334 SDValue CMP01 = CMP0->getOperand(1);
16335 EVT VT = CMP00.getValueType();
16337 if (VT == MVT::f32 || VT == MVT::f64) {
16338 bool ExpectingFlags = false;
16339 // Check for any users that want flags:
16340 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16341 !ExpectingFlags && UI != UE; ++UI)
16342 switch (UI->getOpcode()) {
16347 ExpectingFlags = true;
16349 case ISD::CopyToReg:
16350 case ISD::SIGN_EXTEND:
16351 case ISD::ZERO_EXTEND:
16352 case ISD::ANY_EXTEND:
16356 if (!ExpectingFlags) {
16357 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16358 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16360 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16361 X86::CondCode tmp = cc0;
16366 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
16367 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16368 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16369 X86ISD::NodeType NTOperator = is64BitFP ?
16370 X86ISD::FSETCCsd : X86ISD::FSETCCss;
16371 // FIXME: need symbolic constants for these magic numbers.
16372 // See X86ATTInstPrinter.cpp:printSSECC().
16373 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16374 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16375 DAG.getConstant(x86cc, MVT::i8));
16376 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16378 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16379 DAG.getConstant(1, MVT::i32));
16380 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16381 return OneBitOfTruth;
16389 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16390 /// so it can be folded inside ANDNP.
16391 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16392 EVT VT = N->getValueType(0);
16394 // Match direct AllOnes for 128 and 256-bit vectors
16395 if (ISD::isBuildVectorAllOnes(N))
16398 // Look through a bit convert.
16399 if (N->getOpcode() == ISD::BITCAST)
16400 N = N->getOperand(0).getNode();
16402 // Sometimes the operand may come from a insert_subvector building a 256-bit
16404 if (VT.is256BitVector() &&
16405 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16406 SDValue V1 = N->getOperand(0);
16407 SDValue V2 = N->getOperand(1);
16409 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16410 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16411 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16412 ISD::isBuildVectorAllOnes(V2.getNode()))
16419 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16420 // register. In most cases we actually compare or select YMM-sized registers
16421 // and mixing the two types creates horrible code. This method optimizes
16422 // some of the transition sequences.
16423 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16424 TargetLowering::DAGCombinerInfo &DCI,
16425 const X86Subtarget *Subtarget) {
16426 EVT VT = N->getValueType(0);
16427 if (!VT.is256BitVector())
16430 assert((N->getOpcode() == ISD::ANY_EXTEND ||
16431 N->getOpcode() == ISD::ZERO_EXTEND ||
16432 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16434 SDValue Narrow = N->getOperand(0);
16435 EVT NarrowVT = Narrow->getValueType(0);
16436 if (!NarrowVT.is128BitVector())
16439 if (Narrow->getOpcode() != ISD::XOR &&
16440 Narrow->getOpcode() != ISD::AND &&
16441 Narrow->getOpcode() != ISD::OR)
16444 SDValue N0 = Narrow->getOperand(0);
16445 SDValue N1 = Narrow->getOperand(1);
16446 DebugLoc DL = Narrow->getDebugLoc();
16448 // The Left side has to be a trunc.
16449 if (N0.getOpcode() != ISD::TRUNCATE)
16452 // The type of the truncated inputs.
16453 EVT WideVT = N0->getOperand(0)->getValueType(0);
16457 // The right side has to be a 'trunc' or a constant vector.
16458 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16459 bool RHSConst = (isSplatVector(N1.getNode()) &&
16460 isa<ConstantSDNode>(N1->getOperand(0)));
16461 if (!RHSTrunc && !RHSConst)
16464 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16466 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16469 // Set N0 and N1 to hold the inputs to the new wide operation.
16470 N0 = N0->getOperand(0);
16472 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16473 N1->getOperand(0));
16474 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16475 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16476 } else if (RHSTrunc) {
16477 N1 = N1->getOperand(0);
16480 // Generate the wide operation.
16481 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16482 unsigned Opcode = N->getOpcode();
16484 case ISD::ANY_EXTEND:
16486 case ISD::ZERO_EXTEND: {
16487 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16488 APInt Mask = APInt::getAllOnesValue(InBits);
16489 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16490 return DAG.getNode(ISD::AND, DL, VT,
16491 Op, DAG.getConstant(Mask, VT));
16493 case ISD::SIGN_EXTEND:
16494 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16495 Op, DAG.getValueType(NarrowVT));
16497 llvm_unreachable("Unexpected opcode");
16501 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16502 TargetLowering::DAGCombinerInfo &DCI,
16503 const X86Subtarget *Subtarget) {
16504 EVT VT = N->getValueType(0);
16505 if (DCI.isBeforeLegalizeOps())
16508 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16512 // Create BLSI, and BLSR instructions
16513 // BLSI is X & (-X)
16514 // BLSR is X & (X-1)
16515 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16516 SDValue N0 = N->getOperand(0);
16517 SDValue N1 = N->getOperand(1);
16518 DebugLoc DL = N->getDebugLoc();
16520 // Check LHS for neg
16521 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16522 isZero(N0.getOperand(0)))
16523 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16525 // Check RHS for neg
16526 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16527 isZero(N1.getOperand(0)))
16528 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16530 // Check LHS for X-1
16531 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16532 isAllOnes(N0.getOperand(1)))
16533 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16535 // Check RHS for X-1
16536 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16537 isAllOnes(N1.getOperand(1)))
16538 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16543 // Want to form ANDNP nodes:
16544 // 1) In the hopes of then easily combining them with OR and AND nodes
16545 // to form PBLEND/PSIGN.
16546 // 2) To match ANDN packed intrinsics
16547 if (VT != MVT::v2i64 && VT != MVT::v4i64)
16550 SDValue N0 = N->getOperand(0);
16551 SDValue N1 = N->getOperand(1);
16552 DebugLoc DL = N->getDebugLoc();
16554 // Check LHS for vnot
16555 if (N0.getOpcode() == ISD::XOR &&
16556 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16557 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16558 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16560 // Check RHS for vnot
16561 if (N1.getOpcode() == ISD::XOR &&
16562 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16563 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16564 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16569 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16570 TargetLowering::DAGCombinerInfo &DCI,
16571 const X86Subtarget *Subtarget) {
16572 EVT VT = N->getValueType(0);
16573 if (DCI.isBeforeLegalizeOps())
16576 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16580 SDValue N0 = N->getOperand(0);
16581 SDValue N1 = N->getOperand(1);
16583 // look for psign/blend
16584 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16585 if (!Subtarget->hasSSSE3() ||
16586 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16589 // Canonicalize pandn to RHS
16590 if (N0.getOpcode() == X86ISD::ANDNP)
16592 // or (and (m, y), (pandn m, x))
16593 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16594 SDValue Mask = N1.getOperand(0);
16595 SDValue X = N1.getOperand(1);
16597 if (N0.getOperand(0) == Mask)
16598 Y = N0.getOperand(1);
16599 if (N0.getOperand(1) == Mask)
16600 Y = N0.getOperand(0);
16602 // Check to see if the mask appeared in both the AND and ANDNP and
16606 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16607 // Look through mask bitcast.
16608 if (Mask.getOpcode() == ISD::BITCAST)
16609 Mask = Mask.getOperand(0);
16610 if (X.getOpcode() == ISD::BITCAST)
16611 X = X.getOperand(0);
16612 if (Y.getOpcode() == ISD::BITCAST)
16613 Y = Y.getOperand(0);
16615 EVT MaskVT = Mask.getValueType();
16617 // Validate that the Mask operand is a vector sra node.
16618 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16619 // there is no psrai.b
16620 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16621 unsigned SraAmt = ~0;
16622 if (Mask.getOpcode() == ISD::SRA) {
16623 SDValue Amt = Mask.getOperand(1);
16624 if (isSplatVector(Amt.getNode())) {
16625 SDValue SclrAmt = Amt->getOperand(0);
16626 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16627 SraAmt = C->getZExtValue();
16629 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16630 SDValue SraC = Mask.getOperand(1);
16631 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16633 if ((SraAmt + 1) != EltBits)
16636 DebugLoc DL = N->getDebugLoc();
16638 // Now we know we at least have a plendvb with the mask val. See if
16639 // we can form a psignb/w/d.
16640 // psign = x.type == y.type == mask.type && y = sub(0, x);
16641 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16642 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16643 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16644 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16645 "Unsupported VT for PSIGN");
16646 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16647 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16649 // PBLENDVB only available on SSE 4.1
16650 if (!Subtarget->hasSSE41())
16653 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16655 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16656 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16657 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16658 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16659 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16663 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16666 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16667 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16669 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16671 if (!N0.hasOneUse() || !N1.hasOneUse())
16674 SDValue ShAmt0 = N0.getOperand(1);
16675 if (ShAmt0.getValueType() != MVT::i8)
16677 SDValue ShAmt1 = N1.getOperand(1);
16678 if (ShAmt1.getValueType() != MVT::i8)
16680 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16681 ShAmt0 = ShAmt0.getOperand(0);
16682 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16683 ShAmt1 = ShAmt1.getOperand(0);
16685 DebugLoc DL = N->getDebugLoc();
16686 unsigned Opc = X86ISD::SHLD;
16687 SDValue Op0 = N0.getOperand(0);
16688 SDValue Op1 = N1.getOperand(0);
16689 if (ShAmt0.getOpcode() == ISD::SUB) {
16690 Opc = X86ISD::SHRD;
16691 std::swap(Op0, Op1);
16692 std::swap(ShAmt0, ShAmt1);
16695 unsigned Bits = VT.getSizeInBits();
16696 if (ShAmt1.getOpcode() == ISD::SUB) {
16697 SDValue Sum = ShAmt1.getOperand(0);
16698 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16699 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16700 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16701 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16702 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16703 return DAG.getNode(Opc, DL, VT,
16705 DAG.getNode(ISD::TRUNCATE, DL,
16708 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16709 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16711 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16712 return DAG.getNode(Opc, DL, VT,
16713 N0.getOperand(0), N1.getOperand(0),
16714 DAG.getNode(ISD::TRUNCATE, DL,
16721 // Generate NEG and CMOV for integer abs.
16722 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16723 EVT VT = N->getValueType(0);
16725 // Since X86 does not have CMOV for 8-bit integer, we don't convert
16726 // 8-bit integer abs to NEG and CMOV.
16727 if (VT.isInteger() && VT.getSizeInBits() == 8)
16730 SDValue N0 = N->getOperand(0);
16731 SDValue N1 = N->getOperand(1);
16732 DebugLoc DL = N->getDebugLoc();
16734 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16735 // and change it to SUB and CMOV.
16736 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16737 N0.getOpcode() == ISD::ADD &&
16738 N0.getOperand(1) == N1 &&
16739 N1.getOpcode() == ISD::SRA &&
16740 N1.getOperand(0) == N0.getOperand(0))
16741 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16742 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16743 // Generate SUB & CMOV.
16744 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16745 DAG.getConstant(0, VT), N0.getOperand(0));
16747 SDValue Ops[] = { N0.getOperand(0), Neg,
16748 DAG.getConstant(X86::COND_GE, MVT::i8),
16749 SDValue(Neg.getNode(), 1) };
16750 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16751 Ops, array_lengthof(Ops));
16756 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16757 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16758 TargetLowering::DAGCombinerInfo &DCI,
16759 const X86Subtarget *Subtarget) {
16760 EVT VT = N->getValueType(0);
16761 if (DCI.isBeforeLegalizeOps())
16764 if (Subtarget->hasCMov()) {
16765 SDValue RV = performIntegerAbsCombine(N, DAG);
16770 // Try forming BMI if it is available.
16771 if (!Subtarget->hasBMI())
16774 if (VT != MVT::i32 && VT != MVT::i64)
16777 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16779 // Create BLSMSK instructions by finding X ^ (X-1)
16780 SDValue N0 = N->getOperand(0);
16781 SDValue N1 = N->getOperand(1);
16782 DebugLoc DL = N->getDebugLoc();
16784 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16785 isAllOnes(N0.getOperand(1)))
16786 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16788 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16789 isAllOnes(N1.getOperand(1)))
16790 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16795 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16796 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16797 TargetLowering::DAGCombinerInfo &DCI,
16798 const X86Subtarget *Subtarget) {
16799 LoadSDNode *Ld = cast<LoadSDNode>(N);
16800 EVT RegVT = Ld->getValueType(0);
16801 EVT MemVT = Ld->getMemoryVT();
16802 DebugLoc dl = Ld->getDebugLoc();
16803 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16804 unsigned RegSz = RegVT.getSizeInBits();
16806 // On Sandybridge unaligned 256bit loads are inefficient.
16807 ISD::LoadExtType Ext = Ld->getExtensionType();
16808 unsigned Alignment = Ld->getAlignment();
16809 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16810 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16811 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16812 unsigned NumElems = RegVT.getVectorNumElements();
16816 SDValue Ptr = Ld->getBasePtr();
16817 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16819 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16821 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16822 Ld->getPointerInfo(), Ld->isVolatile(),
16823 Ld->isNonTemporal(), Ld->isInvariant(),
16825 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16826 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16827 Ld->getPointerInfo(), Ld->isVolatile(),
16828 Ld->isNonTemporal(), Ld->isInvariant(),
16829 std::min(16U, Alignment));
16830 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16832 Load2.getValue(1));
16834 SDValue NewVec = DAG.getUNDEF(RegVT);
16835 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16836 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16837 return DCI.CombineTo(N, NewVec, TF, true);
16840 // If this is a vector EXT Load then attempt to optimize it using a
16841 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16842 // expansion is still better than scalar code.
16843 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16844 // emit a shuffle and a arithmetic shift.
16845 // TODO: It is possible to support ZExt by zeroing the undef values
16846 // during the shuffle phase or after the shuffle.
16847 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16848 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16849 assert(MemVT != RegVT && "Cannot extend to the same type");
16850 assert(MemVT.isVector() && "Must load a vector from memory");
16852 unsigned NumElems = RegVT.getVectorNumElements();
16853 unsigned MemSz = MemVT.getSizeInBits();
16854 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16856 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16859 // All sizes must be a power of two.
16860 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16863 // Attempt to load the original value using scalar loads.
16864 // Find the largest scalar type that divides the total loaded size.
16865 MVT SclrLoadTy = MVT::i8;
16866 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16867 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16868 MVT Tp = (MVT::SimpleValueType)tp;
16869 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16874 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16875 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16877 SclrLoadTy = MVT::f64;
16879 // Calculate the number of scalar loads that we need to perform
16880 // in order to load our vector from memory.
16881 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16882 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16885 unsigned loadRegZize = RegSz;
16886 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16889 // Represent our vector as a sequence of elements which are the
16890 // largest scalar that we can load.
16891 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16892 loadRegZize/SclrLoadTy.getSizeInBits());
16894 // Represent the data using the same element type that is stored in
16895 // memory. In practice, we ''widen'' MemVT.
16897 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16898 loadRegZize/MemVT.getScalarType().getSizeInBits());
16900 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16901 "Invalid vector type");
16903 // We can't shuffle using an illegal type.
16904 if (!TLI.isTypeLegal(WideVecVT))
16907 SmallVector<SDValue, 8> Chains;
16908 SDValue Ptr = Ld->getBasePtr();
16909 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16910 TLI.getPointerTy());
16911 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16913 for (unsigned i = 0; i < NumLoads; ++i) {
16914 // Perform a single load.
16915 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16916 Ptr, Ld->getPointerInfo(),
16917 Ld->isVolatile(), Ld->isNonTemporal(),
16918 Ld->isInvariant(), Ld->getAlignment());
16919 Chains.push_back(ScalarLoad.getValue(1));
16920 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16921 // another round of DAGCombining.
16923 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16925 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16926 ScalarLoad, DAG.getIntPtrConstant(i));
16928 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16931 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16934 // Bitcast the loaded value to a vector of the original element type, in
16935 // the size of the target vector type.
16936 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16937 unsigned SizeRatio = RegSz/MemSz;
16939 if (Ext == ISD::SEXTLOAD) {
16940 // If we have SSE4.1 we can directly emit a VSEXT node.
16941 if (Subtarget->hasSSE41()) {
16942 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16943 return DCI.CombineTo(N, Sext, TF, true);
16946 // Otherwise we'll shuffle the small elements in the high bits of the
16947 // larger type and perform an arithmetic shift. If the shift is not legal
16948 // it's better to scalarize.
16949 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16952 // Redistribute the loaded elements into the different locations.
16953 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16954 for (unsigned i = 0; i != NumElems; ++i)
16955 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16957 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16958 DAG.getUNDEF(WideVecVT),
16961 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16963 // Build the arithmetic shift.
16964 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16965 MemVT.getVectorElementType().getSizeInBits();
16966 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16967 DAG.getConstant(Amt, RegVT));
16969 return DCI.CombineTo(N, Shuff, TF, true);
16972 // Redistribute the loaded elements into the different locations.
16973 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16974 for (unsigned i = 0; i != NumElems; ++i)
16975 ShuffleVec[i*SizeRatio] = i;
16977 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16978 DAG.getUNDEF(WideVecVT),
16981 // Bitcast to the requested type.
16982 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16983 // Replace the original load with the new sequence
16984 // and return the new chain.
16985 return DCI.CombineTo(N, Shuff, TF, true);
16991 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16992 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16993 const X86Subtarget *Subtarget) {
16994 StoreSDNode *St = cast<StoreSDNode>(N);
16995 EVT VT = St->getValue().getValueType();
16996 EVT StVT = St->getMemoryVT();
16997 DebugLoc dl = St->getDebugLoc();
16998 SDValue StoredVal = St->getOperand(1);
16999 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17001 // If we are saving a concatenation of two XMM registers, perform two stores.
17002 // On Sandy Bridge, 256-bit memory operations are executed by two
17003 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17004 // memory operation.
17005 unsigned Alignment = St->getAlignment();
17006 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17007 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17008 StVT == VT && !IsAligned) {
17009 unsigned NumElems = VT.getVectorNumElements();
17013 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17014 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17016 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17017 SDValue Ptr0 = St->getBasePtr();
17018 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17020 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17021 St->getPointerInfo(), St->isVolatile(),
17022 St->isNonTemporal(), Alignment);
17023 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17024 St->getPointerInfo(), St->isVolatile(),
17025 St->isNonTemporal(),
17026 std::min(16U, Alignment));
17027 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17030 // Optimize trunc store (of multiple scalars) to shuffle and store.
17031 // First, pack all of the elements in one place. Next, store to memory
17032 // in fewer chunks.
17033 if (St->isTruncatingStore() && VT.isVector()) {
17034 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17035 unsigned NumElems = VT.getVectorNumElements();
17036 assert(StVT != VT && "Cannot truncate to the same type");
17037 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17038 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17040 // From, To sizes and ElemCount must be pow of two
17041 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17042 // We are going to use the original vector elt for storing.
17043 // Accumulated smaller vector elements must be a multiple of the store size.
17044 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17046 unsigned SizeRatio = FromSz / ToSz;
17048 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17050 // Create a type on which we perform the shuffle
17051 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17052 StVT.getScalarType(), NumElems*SizeRatio);
17054 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17056 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17057 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17058 for (unsigned i = 0; i != NumElems; ++i)
17059 ShuffleVec[i] = i * SizeRatio;
17061 // Can't shuffle using an illegal type.
17062 if (!TLI.isTypeLegal(WideVecVT))
17065 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17066 DAG.getUNDEF(WideVecVT),
17068 // At this point all of the data is stored at the bottom of the
17069 // register. We now need to save it to mem.
17071 // Find the largest store unit
17072 MVT StoreType = MVT::i8;
17073 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17074 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17075 MVT Tp = (MVT::SimpleValueType)tp;
17076 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17080 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17081 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17082 (64 <= NumElems * ToSz))
17083 StoreType = MVT::f64;
17085 // Bitcast the original vector into a vector of store-size units
17086 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17087 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17088 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17089 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17090 SmallVector<SDValue, 8> Chains;
17091 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17092 TLI.getPointerTy());
17093 SDValue Ptr = St->getBasePtr();
17095 // Perform one or more big stores into memory.
17096 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17097 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17098 StoreType, ShuffWide,
17099 DAG.getIntPtrConstant(i));
17100 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17101 St->getPointerInfo(), St->isVolatile(),
17102 St->isNonTemporal(), St->getAlignment());
17103 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17104 Chains.push_back(Ch);
17107 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17111 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
17112 // the FP state in cases where an emms may be missing.
17113 // A preferable solution to the general problem is to figure out the right
17114 // places to insert EMMS. This qualifies as a quick hack.
17116 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17117 if (VT.getSizeInBits() != 64)
17120 const Function *F = DAG.getMachineFunction().getFunction();
17121 bool NoImplicitFloatOps = F->getAttributes().
17122 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17123 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17124 && Subtarget->hasSSE2();
17125 if ((VT.isVector() ||
17126 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17127 isa<LoadSDNode>(St->getValue()) &&
17128 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17129 St->getChain().hasOneUse() && !St->isVolatile()) {
17130 SDNode* LdVal = St->getValue().getNode();
17131 LoadSDNode *Ld = 0;
17132 int TokenFactorIndex = -1;
17133 SmallVector<SDValue, 8> Ops;
17134 SDNode* ChainVal = St->getChain().getNode();
17135 // Must be a store of a load. We currently handle two cases: the load
17136 // is a direct child, and it's under an intervening TokenFactor. It is
17137 // possible to dig deeper under nested TokenFactors.
17138 if (ChainVal == LdVal)
17139 Ld = cast<LoadSDNode>(St->getChain());
17140 else if (St->getValue().hasOneUse() &&
17141 ChainVal->getOpcode() == ISD::TokenFactor) {
17142 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17143 if (ChainVal->getOperand(i).getNode() == LdVal) {
17144 TokenFactorIndex = i;
17145 Ld = cast<LoadSDNode>(St->getValue());
17147 Ops.push_back(ChainVal->getOperand(i));
17151 if (!Ld || !ISD::isNormalLoad(Ld))
17154 // If this is not the MMX case, i.e. we are just turning i64 load/store
17155 // into f64 load/store, avoid the transformation if there are multiple
17156 // uses of the loaded value.
17157 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17160 DebugLoc LdDL = Ld->getDebugLoc();
17161 DebugLoc StDL = N->getDebugLoc();
17162 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17163 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17165 if (Subtarget->is64Bit() || F64IsLegal) {
17166 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17167 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17168 Ld->getPointerInfo(), Ld->isVolatile(),
17169 Ld->isNonTemporal(), Ld->isInvariant(),
17170 Ld->getAlignment());
17171 SDValue NewChain = NewLd.getValue(1);
17172 if (TokenFactorIndex != -1) {
17173 Ops.push_back(NewChain);
17174 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17177 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17178 St->getPointerInfo(),
17179 St->isVolatile(), St->isNonTemporal(),
17180 St->getAlignment());
17183 // Otherwise, lower to two pairs of 32-bit loads / stores.
17184 SDValue LoAddr = Ld->getBasePtr();
17185 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17186 DAG.getConstant(4, MVT::i32));
17188 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17189 Ld->getPointerInfo(),
17190 Ld->isVolatile(), Ld->isNonTemporal(),
17191 Ld->isInvariant(), Ld->getAlignment());
17192 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17193 Ld->getPointerInfo().getWithOffset(4),
17194 Ld->isVolatile(), Ld->isNonTemporal(),
17196 MinAlign(Ld->getAlignment(), 4));
17198 SDValue NewChain = LoLd.getValue(1);
17199 if (TokenFactorIndex != -1) {
17200 Ops.push_back(LoLd);
17201 Ops.push_back(HiLd);
17202 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17206 LoAddr = St->getBasePtr();
17207 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17208 DAG.getConstant(4, MVT::i32));
17210 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17211 St->getPointerInfo(),
17212 St->isVolatile(), St->isNonTemporal(),
17213 St->getAlignment());
17214 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17215 St->getPointerInfo().getWithOffset(4),
17217 St->isNonTemporal(),
17218 MinAlign(St->getAlignment(), 4));
17219 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17224 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17225 /// and return the operands for the horizontal operation in LHS and RHS. A
17226 /// horizontal operation performs the binary operation on successive elements
17227 /// of its first operand, then on successive elements of its second operand,
17228 /// returning the resulting values in a vector. For example, if
17229 /// A = < float a0, float a1, float a2, float a3 >
17231 /// B = < float b0, float b1, float b2, float b3 >
17232 /// then the result of doing a horizontal operation on A and B is
17233 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17234 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17235 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17236 /// set to A, RHS to B, and the routine returns 'true'.
17237 /// Note that the binary operation should have the property that if one of the
17238 /// operands is UNDEF then the result is UNDEF.
17239 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17240 // Look for the following pattern: if
17241 // A = < float a0, float a1, float a2, float a3 >
17242 // B = < float b0, float b1, float b2, float b3 >
17244 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17245 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17246 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17247 // which is A horizontal-op B.
17249 // At least one of the operands should be a vector shuffle.
17250 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17251 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17254 EVT VT = LHS.getValueType();
17256 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17257 "Unsupported vector type for horizontal add/sub");
17259 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17260 // operate independently on 128-bit lanes.
17261 unsigned NumElts = VT.getVectorNumElements();
17262 unsigned NumLanes = VT.getSizeInBits()/128;
17263 unsigned NumLaneElts = NumElts / NumLanes;
17264 assert((NumLaneElts % 2 == 0) &&
17265 "Vector type should have an even number of elements in each lane");
17266 unsigned HalfLaneElts = NumLaneElts/2;
17268 // View LHS in the form
17269 // LHS = VECTOR_SHUFFLE A, B, LMask
17270 // If LHS is not a shuffle then pretend it is the shuffle
17271 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17272 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17275 SmallVector<int, 16> LMask(NumElts);
17276 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17277 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17278 A = LHS.getOperand(0);
17279 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17280 B = LHS.getOperand(1);
17281 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17282 std::copy(Mask.begin(), Mask.end(), LMask.begin());
17284 if (LHS.getOpcode() != ISD::UNDEF)
17286 for (unsigned i = 0; i != NumElts; ++i)
17290 // Likewise, view RHS in the form
17291 // RHS = VECTOR_SHUFFLE C, D, RMask
17293 SmallVector<int, 16> RMask(NumElts);
17294 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17295 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17296 C = RHS.getOperand(0);
17297 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17298 D = RHS.getOperand(1);
17299 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17300 std::copy(Mask.begin(), Mask.end(), RMask.begin());
17302 if (RHS.getOpcode() != ISD::UNDEF)
17304 for (unsigned i = 0; i != NumElts; ++i)
17308 // Check that the shuffles are both shuffling the same vectors.
17309 if (!(A == C && B == D) && !(A == D && B == C))
17312 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17313 if (!A.getNode() && !B.getNode())
17316 // If A and B occur in reverse order in RHS, then "swap" them (which means
17317 // rewriting the mask).
17319 CommuteVectorShuffleMask(RMask, NumElts);
17321 // At this point LHS and RHS are equivalent to
17322 // LHS = VECTOR_SHUFFLE A, B, LMask
17323 // RHS = VECTOR_SHUFFLE A, B, RMask
17324 // Check that the masks correspond to performing a horizontal operation.
17325 for (unsigned i = 0; i != NumElts; ++i) {
17326 int LIdx = LMask[i], RIdx = RMask[i];
17328 // Ignore any UNDEF components.
17329 if (LIdx < 0 || RIdx < 0 ||
17330 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17331 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17334 // Check that successive elements are being operated on. If not, this is
17335 // not a horizontal operation.
17336 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17337 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17338 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17339 if (!(LIdx == Index && RIdx == Index + 1) &&
17340 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17344 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17345 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17349 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17350 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17351 const X86Subtarget *Subtarget) {
17352 EVT VT = N->getValueType(0);
17353 SDValue LHS = N->getOperand(0);
17354 SDValue RHS = N->getOperand(1);
17356 // Try to synthesize horizontal adds from adds of shuffles.
17357 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17358 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17359 isHorizontalBinOp(LHS, RHS, true))
17360 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17364 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17365 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17366 const X86Subtarget *Subtarget) {
17367 EVT VT = N->getValueType(0);
17368 SDValue LHS = N->getOperand(0);
17369 SDValue RHS = N->getOperand(1);
17371 // Try to synthesize horizontal subs from subs of shuffles.
17372 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17373 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17374 isHorizontalBinOp(LHS, RHS, false))
17375 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17379 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17380 /// X86ISD::FXOR nodes.
17381 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17382 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17383 // F[X]OR(0.0, x) -> x
17384 // F[X]OR(x, 0.0) -> x
17385 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17386 if (C->getValueAPF().isPosZero())
17387 return N->getOperand(1);
17388 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17389 if (C->getValueAPF().isPosZero())
17390 return N->getOperand(0);
17394 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17395 /// X86ISD::FMAX nodes.
17396 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17397 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17399 // Only perform optimizations if UnsafeMath is used.
17400 if (!DAG.getTarget().Options.UnsafeFPMath)
17403 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17404 // into FMINC and FMAXC, which are Commutative operations.
17405 unsigned NewOp = 0;
17406 switch (N->getOpcode()) {
17407 default: llvm_unreachable("unknown opcode");
17408 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
17409 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
17412 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17413 N->getOperand(0), N->getOperand(1));
17416 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17417 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17418 // FAND(0.0, x) -> 0.0
17419 // FAND(x, 0.0) -> 0.0
17420 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17421 if (C->getValueAPF().isPosZero())
17422 return N->getOperand(0);
17423 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17424 if (C->getValueAPF().isPosZero())
17425 return N->getOperand(1);
17429 static SDValue PerformBTCombine(SDNode *N,
17431 TargetLowering::DAGCombinerInfo &DCI) {
17432 // BT ignores high bits in the bit index operand.
17433 SDValue Op1 = N->getOperand(1);
17434 if (Op1.hasOneUse()) {
17435 unsigned BitWidth = Op1.getValueSizeInBits();
17436 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17437 APInt KnownZero, KnownOne;
17438 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17439 !DCI.isBeforeLegalizeOps());
17440 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17441 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17442 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17443 DCI.CommitTargetLoweringOpt(TLO);
17448 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17449 SDValue Op = N->getOperand(0);
17450 if (Op.getOpcode() == ISD::BITCAST)
17451 Op = Op.getOperand(0);
17452 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17453 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17454 VT.getVectorElementType().getSizeInBits() ==
17455 OpVT.getVectorElementType().getSizeInBits()) {
17456 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17461 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17462 const X86Subtarget *Subtarget) {
17463 EVT VT = N->getValueType(0);
17464 if (!VT.isVector())
17467 SDValue N0 = N->getOperand(0);
17468 SDValue N1 = N->getOperand(1);
17469 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17470 DebugLoc dl = N->getDebugLoc();
17472 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17473 // both SSE and AVX2 since there is no sign-extended shift right
17474 // operation on a vector with 64-bit elements.
17475 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17476 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17477 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17478 N0.getOpcode() == ISD::SIGN_EXTEND)) {
17479 SDValue N00 = N0.getOperand(0);
17481 // EXTLOAD has a better solution on AVX2,
17482 // it may be replaced with X86ISD::VSEXT node.
17483 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17484 if (!ISD::isNormalLoad(N00.getNode()))
17487 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17488 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17490 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17496 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17497 TargetLowering::DAGCombinerInfo &DCI,
17498 const X86Subtarget *Subtarget) {
17499 if (!DCI.isBeforeLegalizeOps())
17502 if (!Subtarget->hasFp256())
17505 EVT VT = N->getValueType(0);
17506 if (VT.isVector() && VT.getSizeInBits() == 256) {
17507 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17515 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17516 const X86Subtarget* Subtarget) {
17517 DebugLoc dl = N->getDebugLoc();
17518 EVT VT = N->getValueType(0);
17520 // Let legalize expand this if it isn't a legal type yet.
17521 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17524 EVT ScalarVT = VT.getScalarType();
17525 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17526 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17529 SDValue A = N->getOperand(0);
17530 SDValue B = N->getOperand(1);
17531 SDValue C = N->getOperand(2);
17533 bool NegA = (A.getOpcode() == ISD::FNEG);
17534 bool NegB = (B.getOpcode() == ISD::FNEG);
17535 bool NegC = (C.getOpcode() == ISD::FNEG);
17537 // Negative multiplication when NegA xor NegB
17538 bool NegMul = (NegA != NegB);
17540 A = A.getOperand(0);
17542 B = B.getOperand(0);
17544 C = C.getOperand(0);
17548 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17550 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17552 return DAG.getNode(Opcode, dl, VT, A, B, C);
17555 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17556 TargetLowering::DAGCombinerInfo &DCI,
17557 const X86Subtarget *Subtarget) {
17558 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
17559 // (and (i32 x86isd::setcc_carry), 1)
17560 // This eliminates the zext. This transformation is necessary because
17561 // ISD::SETCC is always legalized to i8.
17562 DebugLoc dl = N->getDebugLoc();
17563 SDValue N0 = N->getOperand(0);
17564 EVT VT = N->getValueType(0);
17566 if (N0.getOpcode() == ISD::AND &&
17568 N0.getOperand(0).hasOneUse()) {
17569 SDValue N00 = N0.getOperand(0);
17570 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17571 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17572 if (!C || C->getZExtValue() != 1)
17574 return DAG.getNode(ISD::AND, dl, VT,
17575 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17576 N00.getOperand(0), N00.getOperand(1)),
17577 DAG.getConstant(1, VT));
17581 if (VT.is256BitVector()) {
17582 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17590 // Optimize x == -y --> x+y == 0
17591 // x != -y --> x+y != 0
17592 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17593 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17594 SDValue LHS = N->getOperand(0);
17595 SDValue RHS = N->getOperand(1);
17597 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17598 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17599 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17600 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17601 LHS.getValueType(), RHS, LHS.getOperand(1));
17602 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17603 addV, DAG.getConstant(0, addV.getValueType()), CC);
17605 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17606 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17607 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17608 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17609 RHS.getValueType(), LHS, RHS.getOperand(1));
17610 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17611 addV, DAG.getConstant(0, addV.getValueType()), CC);
17616 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17617 // as "sbb reg,reg", since it can be extended without zext and produces
17618 // an all-ones bit which is more useful than 0/1 in some cases.
17619 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17620 return DAG.getNode(ISD::AND, DL, MVT::i8,
17621 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17622 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17623 DAG.getConstant(1, MVT::i8));
17626 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17627 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17628 TargetLowering::DAGCombinerInfo &DCI,
17629 const X86Subtarget *Subtarget) {
17630 DebugLoc DL = N->getDebugLoc();
17631 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17632 SDValue EFLAGS = N->getOperand(1);
17634 if (CC == X86::COND_A) {
17635 // Try to convert COND_A into COND_B in an attempt to facilitate
17636 // materializing "setb reg".
17638 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17639 // cannot take an immediate as its first operand.
17641 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17642 EFLAGS.getValueType().isInteger() &&
17643 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17644 SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17645 EFLAGS.getNode()->getVTList(),
17646 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17647 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17648 return MaterializeSETB(DL, NewEFLAGS, DAG);
17652 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17653 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17655 if (CC == X86::COND_B)
17656 return MaterializeSETB(DL, EFLAGS, DAG);
17660 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17661 if (Flags.getNode()) {
17662 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17663 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17669 // Optimize branch condition evaluation.
17671 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17672 TargetLowering::DAGCombinerInfo &DCI,
17673 const X86Subtarget *Subtarget) {
17674 DebugLoc DL = N->getDebugLoc();
17675 SDValue Chain = N->getOperand(0);
17676 SDValue Dest = N->getOperand(1);
17677 SDValue EFLAGS = N->getOperand(3);
17678 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17682 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17683 if (Flags.getNode()) {
17684 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17685 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17692 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17693 const X86TargetLowering *XTLI) {
17694 SDValue Op0 = N->getOperand(0);
17695 EVT InVT = Op0->getValueType(0);
17697 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17698 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17699 DebugLoc dl = N->getDebugLoc();
17700 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17701 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17702 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17705 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17706 // a 32-bit target where SSE doesn't support i64->FP operations.
17707 if (Op0.getOpcode() == ISD::LOAD) {
17708 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17709 EVT VT = Ld->getValueType(0);
17710 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17711 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17712 !XTLI->getSubtarget()->is64Bit() &&
17713 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17714 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17715 Ld->getChain(), Op0, DAG);
17716 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17723 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17724 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17725 X86TargetLowering::DAGCombinerInfo &DCI) {
17726 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17727 // the result is either zero or one (depending on the input carry bit).
17728 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17729 if (X86::isZeroNode(N->getOperand(0)) &&
17730 X86::isZeroNode(N->getOperand(1)) &&
17731 // We don't have a good way to replace an EFLAGS use, so only do this when
17733 SDValue(N, 1).use_empty()) {
17734 DebugLoc DL = N->getDebugLoc();
17735 EVT VT = N->getValueType(0);
17736 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17737 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17738 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17739 DAG.getConstant(X86::COND_B,MVT::i8),
17741 DAG.getConstant(1, VT));
17742 return DCI.CombineTo(N, Res1, CarryOut);
17748 // fold (add Y, (sete X, 0)) -> adc 0, Y
17749 // (add Y, (setne X, 0)) -> sbb -1, Y
17750 // (sub (sete X, 0), Y) -> sbb 0, Y
17751 // (sub (setne X, 0), Y) -> adc -1, Y
17752 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17753 DebugLoc DL = N->getDebugLoc();
17755 // Look through ZExts.
17756 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17757 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17760 SDValue SetCC = Ext.getOperand(0);
17761 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17764 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17765 if (CC != X86::COND_E && CC != X86::COND_NE)
17768 SDValue Cmp = SetCC.getOperand(1);
17769 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17770 !X86::isZeroNode(Cmp.getOperand(1)) ||
17771 !Cmp.getOperand(0).getValueType().isInteger())
17774 SDValue CmpOp0 = Cmp.getOperand(0);
17775 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17776 DAG.getConstant(1, CmpOp0.getValueType()));
17778 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17779 if (CC == X86::COND_NE)
17780 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17781 DL, OtherVal.getValueType(), OtherVal,
17782 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17783 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17784 DL, OtherVal.getValueType(), OtherVal,
17785 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17788 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17789 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17790 const X86Subtarget *Subtarget) {
17791 EVT VT = N->getValueType(0);
17792 SDValue Op0 = N->getOperand(0);
17793 SDValue Op1 = N->getOperand(1);
17795 // Try to synthesize horizontal adds from adds of shuffles.
17796 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17797 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17798 isHorizontalBinOp(Op0, Op1, true))
17799 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17801 return OptimizeConditionalInDecrement(N, DAG);
17804 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17805 const X86Subtarget *Subtarget) {
17806 SDValue Op0 = N->getOperand(0);
17807 SDValue Op1 = N->getOperand(1);
17809 // X86 can't encode an immediate LHS of a sub. See if we can push the
17810 // negation into a preceding instruction.
17811 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17812 // If the RHS of the sub is a XOR with one use and a constant, invert the
17813 // immediate. Then add one to the LHS of the sub so we can turn
17814 // X-Y -> X+~Y+1, saving one register.
17815 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17816 isa<ConstantSDNode>(Op1.getOperand(1))) {
17817 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17818 EVT VT = Op0.getValueType();
17819 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17821 DAG.getConstant(~XorC, VT));
17822 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17823 DAG.getConstant(C->getAPIntValue()+1, VT));
17827 // Try to synthesize horizontal adds from adds of shuffles.
17828 EVT VT = N->getValueType(0);
17829 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17830 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17831 isHorizontalBinOp(Op0, Op1, true))
17832 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17834 return OptimizeConditionalInDecrement(N, DAG);
17837 /// performVZEXTCombine - Performs build vector combines
17838 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17839 TargetLowering::DAGCombinerInfo &DCI,
17840 const X86Subtarget *Subtarget) {
17841 // (vzext (bitcast (vzext (x)) -> (vzext x)
17842 SDValue In = N->getOperand(0);
17843 while (In.getOpcode() == ISD::BITCAST)
17844 In = In.getOperand(0);
17846 if (In.getOpcode() != X86ISD::VZEXT)
17849 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17853 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17854 DAGCombinerInfo &DCI) const {
17855 SelectionDAG &DAG = DCI.DAG;
17856 switch (N->getOpcode()) {
17858 case ISD::EXTRACT_VECTOR_ELT:
17859 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17861 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17862 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17863 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17864 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17865 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17866 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17869 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17870 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17871 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17872 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17873 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17874 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17875 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17876 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17877 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17879 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17881 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17882 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17883 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17884 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17885 case ISD::ANY_EXTEND:
17886 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17887 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17888 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17889 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17890 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17891 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17892 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17893 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17894 case X86ISD::SHUFP: // Handle all target specific shuffles
17895 case X86ISD::PALIGNR:
17896 case X86ISD::UNPCKH:
17897 case X86ISD::UNPCKL:
17898 case X86ISD::MOVHLPS:
17899 case X86ISD::MOVLHPS:
17900 case X86ISD::PSHUFD:
17901 case X86ISD::PSHUFHW:
17902 case X86ISD::PSHUFLW:
17903 case X86ISD::MOVSS:
17904 case X86ISD::MOVSD:
17905 case X86ISD::VPERMILP:
17906 case X86ISD::VPERM2X128:
17907 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17908 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17914 /// isTypeDesirableForOp - Return true if the target has native support for
17915 /// the specified value type and it is 'desirable' to use the type for the
17916 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17917 /// instruction encodings are longer and some i16 instructions are slow.
17918 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17919 if (!isTypeLegal(VT))
17921 if (VT != MVT::i16)
17928 case ISD::SIGN_EXTEND:
17929 case ISD::ZERO_EXTEND:
17930 case ISD::ANY_EXTEND:
17943 /// IsDesirableToPromoteOp - This method query the target whether it is
17944 /// beneficial for dag combiner to promote the specified node. If true, it
17945 /// should return the desired promotion type by reference.
17946 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17947 EVT VT = Op.getValueType();
17948 if (VT != MVT::i16)
17951 bool Promote = false;
17952 bool Commute = false;
17953 switch (Op.getOpcode()) {
17956 LoadSDNode *LD = cast<LoadSDNode>(Op);
17957 // If the non-extending load has a single use and it's not live out, then it
17958 // might be folded.
17959 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17960 Op.hasOneUse()*/) {
17961 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17962 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17963 // The only case where we'd want to promote LOAD (rather then it being
17964 // promoted as an operand is when it's only use is liveout.
17965 if (UI->getOpcode() != ISD::CopyToReg)
17972 case ISD::SIGN_EXTEND:
17973 case ISD::ZERO_EXTEND:
17974 case ISD::ANY_EXTEND:
17979 SDValue N0 = Op.getOperand(0);
17980 // Look out for (store (shl (load), x)).
17981 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17994 SDValue N0 = Op.getOperand(0);
17995 SDValue N1 = Op.getOperand(1);
17996 if (!Commute && MayFoldLoad(N1))
17998 // Avoid disabling potential load folding opportunities.
17999 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18001 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18011 //===----------------------------------------------------------------------===//
18012 // X86 Inline Assembly Support
18013 //===----------------------------------------------------------------------===//
18016 // Helper to match a string separated by whitespace.
18017 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18018 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18020 for (unsigned i = 0, e = args.size(); i != e; ++i) {
18021 StringRef piece(*args[i]);
18022 if (!s.startswith(piece)) // Check if the piece matches.
18025 s = s.substr(piece.size());
18026 StringRef::size_type pos = s.find_first_not_of(" \t");
18027 if (pos == 0) // We matched a prefix.
18035 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18038 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18039 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18041 std::string AsmStr = IA->getAsmString();
18043 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18044 if (!Ty || Ty->getBitWidth() % 16 != 0)
18047 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18048 SmallVector<StringRef, 4> AsmPieces;
18049 SplitString(AsmStr, AsmPieces, ";\n");
18051 switch (AsmPieces.size()) {
18052 default: return false;
18054 // FIXME: this should verify that we are targeting a 486 or better. If not,
18055 // we will turn this bswap into something that will be lowered to logical
18056 // ops instead of emitting the bswap asm. For now, we don't support 486 or
18057 // lower so don't worry about this.
18059 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18060 matchAsm(AsmPieces[0], "bswapl", "$0") ||
18061 matchAsm(AsmPieces[0], "bswapq", "$0") ||
18062 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18063 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18064 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18065 // No need to check constraints, nothing other than the equivalent of
18066 // "=r,0" would be valid here.
18067 return IntrinsicLowering::LowerToByteSwap(CI);
18070 // rorw $$8, ${0:w} --> llvm.bswap.i16
18071 if (CI->getType()->isIntegerTy(16) &&
18072 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18073 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18074 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18076 const std::string &ConstraintsStr = IA->getConstraintString();
18077 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18078 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18079 if (AsmPieces.size() == 4 &&
18080 AsmPieces[0] == "~{cc}" &&
18081 AsmPieces[1] == "~{dirflag}" &&
18082 AsmPieces[2] == "~{flags}" &&
18083 AsmPieces[3] == "~{fpsr}")
18084 return IntrinsicLowering::LowerToByteSwap(CI);
18088 if (CI->getType()->isIntegerTy(32) &&
18089 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18090 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18091 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18092 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18094 const std::string &ConstraintsStr = IA->getConstraintString();
18095 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18096 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18097 if (AsmPieces.size() == 4 &&
18098 AsmPieces[0] == "~{cc}" &&
18099 AsmPieces[1] == "~{dirflag}" &&
18100 AsmPieces[2] == "~{flags}" &&
18101 AsmPieces[3] == "~{fpsr}")
18102 return IntrinsicLowering::LowerToByteSwap(CI);
18105 if (CI->getType()->isIntegerTy(64)) {
18106 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18107 if (Constraints.size() >= 2 &&
18108 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18109 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18110 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
18111 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18112 matchAsm(AsmPieces[1], "bswap", "%edx") &&
18113 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18114 return IntrinsicLowering::LowerToByteSwap(CI);
18122 /// getConstraintType - Given a constraint letter, return the type of
18123 /// constraint it is for this target.
18124 X86TargetLowering::ConstraintType
18125 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18126 if (Constraint.size() == 1) {
18127 switch (Constraint[0]) {
18138 return C_RegisterClass;
18162 return TargetLowering::getConstraintType(Constraint);
18165 /// Examine constraint type and operand type and determine a weight value.
18166 /// This object must already have been set up with the operand type
18167 /// and the current alternative constraint selected.
18168 TargetLowering::ConstraintWeight
18169 X86TargetLowering::getSingleConstraintMatchWeight(
18170 AsmOperandInfo &info, const char *constraint) const {
18171 ConstraintWeight weight = CW_Invalid;
18172 Value *CallOperandVal = info.CallOperandVal;
18173 // If we don't have a value, we can't do a match,
18174 // but allow it at the lowest weight.
18175 if (CallOperandVal == NULL)
18177 Type *type = CallOperandVal->getType();
18178 // Look at the constraint type.
18179 switch (*constraint) {
18181 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18192 if (CallOperandVal->getType()->isIntegerTy())
18193 weight = CW_SpecificReg;
18198 if (type->isFloatingPointTy())
18199 weight = CW_SpecificReg;
18202 if (type->isX86_MMXTy() && Subtarget->hasMMX())
18203 weight = CW_SpecificReg;
18207 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18208 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18209 weight = CW_Register;
18212 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18213 if (C->getZExtValue() <= 31)
18214 weight = CW_Constant;
18218 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18219 if (C->getZExtValue() <= 63)
18220 weight = CW_Constant;
18224 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18225 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18226 weight = CW_Constant;
18230 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18231 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18232 weight = CW_Constant;
18236 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18237 if (C->getZExtValue() <= 3)
18238 weight = CW_Constant;
18242 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18243 if (C->getZExtValue() <= 0xff)
18244 weight = CW_Constant;
18249 if (dyn_cast<ConstantFP>(CallOperandVal)) {
18250 weight = CW_Constant;
18254 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18255 if ((C->getSExtValue() >= -0x80000000LL) &&
18256 (C->getSExtValue() <= 0x7fffffffLL))
18257 weight = CW_Constant;
18261 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18262 if (C->getZExtValue() <= 0xffffffff)
18263 weight = CW_Constant;
18270 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18271 /// with another that has more specific requirements based on the type of the
18272 /// corresponding operand.
18273 const char *X86TargetLowering::
18274 LowerXConstraint(EVT ConstraintVT) const {
18275 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18276 // 'f' like normal targets.
18277 if (ConstraintVT.isFloatingPoint()) {
18278 if (Subtarget->hasSSE2())
18280 if (Subtarget->hasSSE1())
18284 return TargetLowering::LowerXConstraint(ConstraintVT);
18287 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18288 /// vector. If it is invalid, don't add anything to Ops.
18289 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18290 std::string &Constraint,
18291 std::vector<SDValue>&Ops,
18292 SelectionDAG &DAG) const {
18293 SDValue Result(0, 0);
18295 // Only support length 1 constraints for now.
18296 if (Constraint.length() > 1) return;
18298 char ConstraintLetter = Constraint[0];
18299 switch (ConstraintLetter) {
18302 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18303 if (C->getZExtValue() <= 31) {
18304 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18310 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18311 if (C->getZExtValue() <= 63) {
18312 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18318 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18319 if (isInt<8>(C->getSExtValue())) {
18320 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18327 if (C->getZExtValue() <= 255) {
18328 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18334 // 32-bit signed value
18335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18336 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18337 C->getSExtValue())) {
18338 // Widen to 64 bits here to get it sign extended.
18339 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18342 // FIXME gcc accepts some relocatable values here too, but only in certain
18343 // memory models; it's complicated.
18348 // 32-bit unsigned value
18349 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18350 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18351 C->getZExtValue())) {
18352 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18356 // FIXME gcc accepts some relocatable values here too, but only in certain
18357 // memory models; it's complicated.
18361 // Literal immediates are always ok.
18362 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18363 // Widen to 64 bits here to get it sign extended.
18364 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18368 // In any sort of PIC mode addresses need to be computed at runtime by
18369 // adding in a register or some sort of table lookup. These can't
18370 // be used as immediates.
18371 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18374 // If we are in non-pic codegen mode, we allow the address of a global (with
18375 // an optional displacement) to be used with 'i'.
18376 GlobalAddressSDNode *GA = 0;
18377 int64_t Offset = 0;
18379 // Match either (GA), (GA+C), (GA+C1+C2), etc.
18381 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18382 Offset += GA->getOffset();
18384 } else if (Op.getOpcode() == ISD::ADD) {
18385 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18386 Offset += C->getZExtValue();
18387 Op = Op.getOperand(0);
18390 } else if (Op.getOpcode() == ISD::SUB) {
18391 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18392 Offset += -C->getZExtValue();
18393 Op = Op.getOperand(0);
18398 // Otherwise, this isn't something we can handle, reject it.
18402 const GlobalValue *GV = GA->getGlobal();
18403 // If we require an extra load to get this address, as in PIC mode, we
18404 // can't accept it.
18405 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18406 getTargetMachine())))
18409 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18410 GA->getValueType(0), Offset);
18415 if (Result.getNode()) {
18416 Ops.push_back(Result);
18419 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18422 std::pair<unsigned, const TargetRegisterClass*>
18423 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18425 // First, see if this is a constraint that directly corresponds to an LLVM
18427 if (Constraint.size() == 1) {
18428 // GCC Constraint Letters
18429 switch (Constraint[0]) {
18431 // TODO: Slight differences here in allocation order and leaving
18432 // RIP in the class. Do they matter any more here than they do
18433 // in the normal allocation?
18434 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18435 if (Subtarget->is64Bit()) {
18436 if (VT == MVT::i32 || VT == MVT::f32)
18437 return std::make_pair(0U, &X86::GR32RegClass);
18438 if (VT == MVT::i16)
18439 return std::make_pair(0U, &X86::GR16RegClass);
18440 if (VT == MVT::i8 || VT == MVT::i1)
18441 return std::make_pair(0U, &X86::GR8RegClass);
18442 if (VT == MVT::i64 || VT == MVT::f64)
18443 return std::make_pair(0U, &X86::GR64RegClass);
18446 // 32-bit fallthrough
18447 case 'Q': // Q_REGS
18448 if (VT == MVT::i32 || VT == MVT::f32)
18449 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18450 if (VT == MVT::i16)
18451 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18452 if (VT == MVT::i8 || VT == MVT::i1)
18453 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18454 if (VT == MVT::i64)
18455 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18457 case 'r': // GENERAL_REGS
18458 case 'l': // INDEX_REGS
18459 if (VT == MVT::i8 || VT == MVT::i1)
18460 return std::make_pair(0U, &X86::GR8RegClass);
18461 if (VT == MVT::i16)
18462 return std::make_pair(0U, &X86::GR16RegClass);
18463 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18464 return std::make_pair(0U, &X86::GR32RegClass);
18465 return std::make_pair(0U, &X86::GR64RegClass);
18466 case 'R': // LEGACY_REGS
18467 if (VT == MVT::i8 || VT == MVT::i1)
18468 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18469 if (VT == MVT::i16)
18470 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18471 if (VT == MVT::i32 || !Subtarget->is64Bit())
18472 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18473 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18474 case 'f': // FP Stack registers.
18475 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18476 // value to the correct fpstack register class.
18477 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18478 return std::make_pair(0U, &X86::RFP32RegClass);
18479 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18480 return std::make_pair(0U, &X86::RFP64RegClass);
18481 return std::make_pair(0U, &X86::RFP80RegClass);
18482 case 'y': // MMX_REGS if MMX allowed.
18483 if (!Subtarget->hasMMX()) break;
18484 return std::make_pair(0U, &X86::VR64RegClass);
18485 case 'Y': // SSE_REGS if SSE2 allowed
18486 if (!Subtarget->hasSSE2()) break;
18488 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18489 if (!Subtarget->hasSSE1()) break;
18491 switch (VT.getSimpleVT().SimpleTy) {
18493 // Scalar SSE types.
18496 return std::make_pair(0U, &X86::FR32RegClass);
18499 return std::make_pair(0U, &X86::FR64RegClass);
18507 return std::make_pair(0U, &X86::VR128RegClass);
18515 return std::make_pair(0U, &X86::VR256RegClass);
18521 // Use the default implementation in TargetLowering to convert the register
18522 // constraint into a member of a register class.
18523 std::pair<unsigned, const TargetRegisterClass*> Res;
18524 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18526 // Not found as a standard register?
18527 if (Res.second == 0) {
18528 // Map st(0) -> st(7) -> ST0
18529 if (Constraint.size() == 7 && Constraint[0] == '{' &&
18530 tolower(Constraint[1]) == 's' &&
18531 tolower(Constraint[2]) == 't' &&
18532 Constraint[3] == '(' &&
18533 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18534 Constraint[5] == ')' &&
18535 Constraint[6] == '}') {
18537 Res.first = X86::ST0+Constraint[4]-'0';
18538 Res.second = &X86::RFP80RegClass;
18542 // GCC allows "st(0)" to be called just plain "st".
18543 if (StringRef("{st}").equals_lower(Constraint)) {
18544 Res.first = X86::ST0;
18545 Res.second = &X86::RFP80RegClass;
18550 if (StringRef("{flags}").equals_lower(Constraint)) {
18551 Res.first = X86::EFLAGS;
18552 Res.second = &X86::CCRRegClass;
18556 // 'A' means EAX + EDX.
18557 if (Constraint == "A") {
18558 Res.first = X86::EAX;
18559 Res.second = &X86::GR32_ADRegClass;
18565 // Otherwise, check to see if this is a register class of the wrong value
18566 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18567 // turn into {ax},{dx}.
18568 if (Res.second->hasType(VT))
18569 return Res; // Correct type already, nothing to do.
18571 // All of the single-register GCC register classes map their values onto
18572 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
18573 // really want an 8-bit or 32-bit register, map to the appropriate register
18574 // class and return the appropriate register.
18575 if (Res.second == &X86::GR16RegClass) {
18576 if (VT == MVT::i8 || VT == MVT::i1) {
18577 unsigned DestReg = 0;
18578 switch (Res.first) {
18580 case X86::AX: DestReg = X86::AL; break;
18581 case X86::DX: DestReg = X86::DL; break;
18582 case X86::CX: DestReg = X86::CL; break;
18583 case X86::BX: DestReg = X86::BL; break;
18586 Res.first = DestReg;
18587 Res.second = &X86::GR8RegClass;
18589 } else if (VT == MVT::i32 || VT == MVT::f32) {
18590 unsigned DestReg = 0;
18591 switch (Res.first) {
18593 case X86::AX: DestReg = X86::EAX; break;
18594 case X86::DX: DestReg = X86::EDX; break;
18595 case X86::CX: DestReg = X86::ECX; break;
18596 case X86::BX: DestReg = X86::EBX; break;
18597 case X86::SI: DestReg = X86::ESI; break;
18598 case X86::DI: DestReg = X86::EDI; break;
18599 case X86::BP: DestReg = X86::EBP; break;
18600 case X86::SP: DestReg = X86::ESP; break;
18603 Res.first = DestReg;
18604 Res.second = &X86::GR32RegClass;
18606 } else if (VT == MVT::i64 || VT == MVT::f64) {
18607 unsigned DestReg = 0;
18608 switch (Res.first) {
18610 case X86::AX: DestReg = X86::RAX; break;
18611 case X86::DX: DestReg = X86::RDX; break;
18612 case X86::CX: DestReg = X86::RCX; break;
18613 case X86::BX: DestReg = X86::RBX; break;
18614 case X86::SI: DestReg = X86::RSI; break;
18615 case X86::DI: DestReg = X86::RDI; break;
18616 case X86::BP: DestReg = X86::RBP; break;
18617 case X86::SP: DestReg = X86::RSP; break;
18620 Res.first = DestReg;
18621 Res.second = &X86::GR64RegClass;
18624 } else if (Res.second == &X86::FR32RegClass ||
18625 Res.second == &X86::FR64RegClass ||
18626 Res.second == &X86::VR128RegClass) {
18627 // Handle references to XMM physical registers that got mapped into the
18628 // wrong class. This can happen with constraints like {xmm0} where the
18629 // target independent register mapper will just pick the first match it can
18630 // find, ignoring the required type.
18632 if (VT == MVT::f32 || VT == MVT::i32)
18633 Res.second = &X86::FR32RegClass;
18634 else if (VT == MVT::f64 || VT == MVT::i64)
18635 Res.second = &X86::FR64RegClass;
18636 else if (X86::VR128RegClass.hasType(VT))
18637 Res.second = &X86::VR128RegClass;
18638 else if (X86::VR256RegClass.hasType(VT))
18639 Res.second = &X86::VR256RegClass;