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/CallingConv.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/Constants.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Function.h"
37 #include "llvm/GlobalAlias.h"
38 #include "llvm/GlobalVariable.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/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 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
162 RegInfo = TM.getRegisterInfo();
163 TD = getDataLayout();
165 // Set up the TargetLowering object.
166 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168 // X86 is weird, it always uses i8 for shift amounts and setcc results.
169 setBooleanContents(ZeroOrOneBooleanContent);
170 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173 // For 64-bit since we have so many registers use the ILP scheduler, for
174 // 32-bit code use the register pressure specific scheduling.
175 // For Atom, always use ILP scheduling.
176 if (Subtarget->isAtom())
177 setSchedulingPreference(Sched::ILP);
178 else if (Subtarget->is64Bit())
179 setSchedulingPreference(Sched::ILP);
181 setSchedulingPreference(Sched::RegPressure);
182 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
184 // Bypass i32 with i8 on Atom when compiling with O2
185 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186 addBypassSlowDiv(32, 8);
188 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189 // Setup Windows compiler runtime calls.
190 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192 setLibcallName(RTLIB::SREM_I64, "_allrem");
193 setLibcallName(RTLIB::UREM_I64, "_aullrem");
194 setLibcallName(RTLIB::MUL_I64, "_allmul");
195 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201 // The _ftol2 runtime function has an unusual calling conv, which
202 // is modeled by a special pseudo-instruction.
203 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
209 if (Subtarget->isTargetDarwin()) {
210 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211 setUseUnderscoreSetJmp(false);
212 setUseUnderscoreLongJmp(false);
213 } else if (Subtarget->isTargetMingw()) {
214 // MS runtime is weird: it exports _setjmp, but longjmp!
215 setUseUnderscoreSetJmp(true);
216 setUseUnderscoreLongJmp(false);
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(true);
222 // Set up the register classes.
223 addRegisterClass(MVT::i8, &X86::GR8RegClass);
224 addRegisterClass(MVT::i16, &X86::GR16RegClass);
225 addRegisterClass(MVT::i32, &X86::GR32RegClass);
226 if (Subtarget->is64Bit())
227 addRegisterClass(MVT::i64, &X86::GR64RegClass);
229 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231 // We don't accept any truncstore of integer registers.
232 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
239 // SETOEQ and SETUNE require checking two conditions.
240 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
250 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
253 if (Subtarget->is64Bit()) {
254 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
256 } else if (!TM.Options.UseSoftFloat) {
257 // We have an algorithm for SSE2->double, and we turn this into a
258 // 64-bit FILD followed by conditional FADD for other targets.
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
260 // We have an algorithm for SSE2, and we turn this into a 64-bit
261 // FILD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
265 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
268 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
270 if (!TM.Options.UseSoftFloat) {
271 // SSE has no i16 to fp conversion, only i32
272 if (X86ScalarSSEf32) {
273 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
274 // f32 and f64 cases are Legal, f80 case is not
275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
285 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
286 // are Legal, f80 is custom lowered.
287 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
288 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
290 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
293 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
295 if (X86ScalarSSEf32) {
296 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
297 // f32 and f64 cases are Legal, f80 case is not
298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 // Handle FP_TO_UINT by promoting the destination to a larger signed
306 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
307 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
310 if (Subtarget->is64Bit()) {
311 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
313 } else if (!TM.Options.UseSoftFloat) {
314 // Since AVX is a superset of SSE3, only check for SSE here.
315 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316 // Expand FP_TO_UINT into a select.
317 // FIXME: We would like to use a Custom expander here eventually to do
318 // the optimal thing for SSE vs. the default expansion in the legalizer.
319 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
321 // With SSE3 we can use fisttpll to convert to a signed i64; without
322 // SSE, we're stuck with a fistpll.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
326 if (isTargetFTOL()) {
327 // Use the _ftol2 runtime function, which has a pseudo-instruction
328 // to handle its weird calling convention.
329 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
332 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333 if (!X86ScalarSSEf64) {
334 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
335 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
338 // Without SSE, i64->f64 goes through memory.
339 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
343 // Scalar integer divide and remainder are lowered to use operations that
344 // produce two results, to match the available instructions. This exposes
345 // the two-result form to trivial CSE, which is able to combine x/y and x%y
346 // into a single instruction.
348 // Scalar integer multiply-high is also lowered to use two-result
349 // operations, to match the available instructions. However, plain multiply
350 // (low) operations are left as Legal, as there are single-result
351 // instructions for this in x86. Using the two-result multiply instructions
352 // when both high and low results are needed must be arranged by dagcombine.
353 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355 setOperationAction(ISD::MULHS, VT, Expand);
356 setOperationAction(ISD::MULHU, VT, Expand);
357 setOperationAction(ISD::SDIV, VT, Expand);
358 setOperationAction(ISD::UDIV, VT, Expand);
359 setOperationAction(ISD::SREM, VT, Expand);
360 setOperationAction(ISD::UREM, VT, Expand);
362 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363 setOperationAction(ISD::ADDC, VT, Custom);
364 setOperationAction(ISD::ADDE, VT, Custom);
365 setOperationAction(ISD::SUBC, VT, Custom);
366 setOperationAction(ISD::SUBE, VT, Custom);
369 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
370 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
371 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
372 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
373 if (Subtarget->is64Bit())
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
378 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
379 setOperationAction(ISD::FREM , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f64 , Expand);
381 setOperationAction(ISD::FREM , MVT::f80 , Expand);
382 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
384 // Promote the i8 variants and force them on up to i32 which has a shorter
386 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
387 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
389 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
390 if (Subtarget->hasBMI()) {
391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
393 if (Subtarget->is64Bit())
394 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
397 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
398 if (Subtarget->is64Bit())
399 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
402 if (Subtarget->hasLZCNT()) {
403 // When promoting the i8 variants, force them to i32 for a shorter
405 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
406 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
408 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
411 if (Subtarget->is64Bit())
412 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
417 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
422 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
426 if (Subtarget->hasPOPCNT()) {
427 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
429 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
430 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
436 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
437 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
439 // These should be promoted to a larger select which is supported.
440 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
441 // X86 wants to expand cmov itself.
442 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
443 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
454 if (Subtarget->is64Bit()) {
455 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
456 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
458 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
459 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461 // support continuation, user-level threading, and etc.. As a result, no
462 // other SjLj exception interfaces are implemented and please don't build
463 // your own exception handling based on them.
464 // LLVM/Clang supports zero-cost DWARF exception handling.
465 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
469 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
470 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
471 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
473 if (Subtarget->is64Bit())
474 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
476 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
477 if (Subtarget->is64Bit()) {
478 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
479 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
480 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
481 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
482 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
484 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
486 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
488 if (Subtarget->is64Bit()) {
489 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
490 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
494 if (Subtarget->hasSSE1())
495 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
497 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
498 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
500 // On X86 and X86-64, atomic operations are lowered to locked instructions.
501 // Locked instructions, in turn, have implicit fence semantics (all memory
502 // operations are flushed before issuing the locked instruction, and they
503 // are not buffered), so we can fold away the common pattern of
504 // fence-atomic-fence.
505 setShouldFoldAtomicFences(true);
507 // Expand certain atomics
508 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
515 if (!Subtarget->is64Bit()) {
516 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
530 if (Subtarget->hasCmpxchg16b()) {
531 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
534 // FIXME - use subtarget debug flags
535 if (!Subtarget->isTargetDarwin() &&
536 !Subtarget->isTargetELF() &&
537 !Subtarget->isTargetCygMing()) {
538 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
541 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
543 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
545 if (Subtarget->is64Bit()) {
546 setExceptionPointerRegister(X86::RAX);
547 setExceptionSelectorRegister(X86::RDX);
549 setExceptionPointerRegister(X86::EAX);
550 setExceptionSelectorRegister(X86::EDX);
552 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558 setOperationAction(ISD::TRAP, MVT::Other, Legal);
559 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
561 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562 setOperationAction(ISD::VASTART , MVT::Other, Custom);
563 setOperationAction(ISD::VAEND , MVT::Other, Expand);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::VAARG , MVT::Other, Custom);
566 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
568 setOperationAction(ISD::VAARG , MVT::Other, Expand);
569 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
572 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
573 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
575 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577 MVT::i64 : MVT::i32, Custom);
578 else if (TM.Options.EnableSegmentedStacks)
579 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580 MVT::i64 : MVT::i32, Custom);
582 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583 MVT::i64 : MVT::i32, Expand);
585 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586 // f32 and f64 use SSE.
587 // Set up the FP register classes.
588 addRegisterClass(MVT::f32, &X86::FR32RegClass);
589 addRegisterClass(MVT::f64, &X86::FR64RegClass);
591 // Use ANDPD to simulate FABS.
592 setOperationAction(ISD::FABS , MVT::f64, Custom);
593 setOperationAction(ISD::FABS , MVT::f32, Custom);
595 // Use XORP to simulate FNEG.
596 setOperationAction(ISD::FNEG , MVT::f64, Custom);
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 // Use ANDPD and ORPD to simulate FCOPYSIGN.
600 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603 // Lower this to FGETSIGNx86 plus an AND.
604 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607 // We don't support sin/cos/fmod
608 setOperationAction(ISD::FSIN , MVT::f64, Expand);
609 setOperationAction(ISD::FCOS , MVT::f64, Expand);
610 setOperationAction(ISD::FSIN , MVT::f32, Expand);
611 setOperationAction(ISD::FCOS , MVT::f32, Expand);
613 // Expand FP immediates into loads from the stack, except for the special
615 addLegalFPImmediate(APFloat(+0.0)); // xorpd
616 addLegalFPImmediate(APFloat(+0.0f)); // xorps
617 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618 // Use SSE for f32, x87 for f64.
619 // Set up the FP register classes.
620 addRegisterClass(MVT::f32, &X86::FR32RegClass);
621 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623 // Use ANDPS to simulate FABS.
624 setOperationAction(ISD::FABS , MVT::f32, Custom);
626 // Use XORP to simulate FNEG.
627 setOperationAction(ISD::FNEG , MVT::f32, Custom);
629 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
631 // Use ANDPS and ORPS to simulate FCOPYSIGN.
632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635 // We don't support sin/cos/fmod
636 setOperationAction(ISD::FSIN , MVT::f32, Expand);
637 setOperationAction(ISD::FCOS , MVT::f32, Expand);
639 // Special cases we handle for FP constants.
640 addLegalFPImmediate(APFloat(+0.0f)); // xorps
641 addLegalFPImmediate(APFloat(+0.0)); // FLD0
642 addLegalFPImmediate(APFloat(+1.0)); // FLD1
643 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646 if (!TM.Options.UnsafeFPMath) {
647 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
648 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
650 } else if (!TM.Options.UseSoftFloat) {
651 // f32 and f64 in x87.
652 // Set up the FP register classes.
653 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
657 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661 if (!TM.Options.UnsafeFPMath) {
662 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
663 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
664 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
667 addLegalFPImmediate(APFloat(+0.0)); // FLD0
668 addLegalFPImmediate(APFloat(+1.0)); // FLD1
669 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
677 // We don't support FMA.
678 setOperationAction(ISD::FMA, MVT::f64, Expand);
679 setOperationAction(ISD::FMA, MVT::f32, Expand);
681 // Long double always uses X87.
682 if (!TM.Options.UseSoftFloat) {
683 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
685 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688 addLegalFPImmediate(TmpFlt); // FLD0
690 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
693 APFloat TmpFlt2(+1.0);
694 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696 addLegalFPImmediate(TmpFlt2); // FLD1
697 TmpFlt2.changeSign();
698 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
701 if (!TM.Options.UnsafeFPMath) {
702 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
703 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
706 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
708 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709 setOperationAction(ISD::FRINT, MVT::f80, Expand);
710 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711 setOperationAction(ISD::FMA, MVT::f80, Expand);
714 // Always use a library call for pow.
715 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
716 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
719 setOperationAction(ISD::FLOG, MVT::f80, Expand);
720 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722 setOperationAction(ISD::FEXP, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725 // First set operation action for all vector types to either promote
726 // (for widening) or expand (for scalarization). Then we will selectively
727 // turn on ones that can be effectively codegen'd.
728 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730 MVT VT = (MVT::SimpleValueType)i;
731 setOperationAction(ISD::ADD , VT, Expand);
732 setOperationAction(ISD::SUB , VT, Expand);
733 setOperationAction(ISD::FADD, VT, Expand);
734 setOperationAction(ISD::FNEG, VT, Expand);
735 setOperationAction(ISD::FSUB, VT, Expand);
736 setOperationAction(ISD::MUL , VT, Expand);
737 setOperationAction(ISD::FMUL, VT, Expand);
738 setOperationAction(ISD::SDIV, VT, Expand);
739 setOperationAction(ISD::UDIV, VT, Expand);
740 setOperationAction(ISD::FDIV, VT, Expand);
741 setOperationAction(ISD::SREM, VT, Expand);
742 setOperationAction(ISD::UREM, VT, Expand);
743 setOperationAction(ISD::LOAD, VT, Expand);
744 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749 setOperationAction(ISD::FABS, VT, Expand);
750 setOperationAction(ISD::FSIN, VT, Expand);
751 setOperationAction(ISD::FCOS, VT, Expand);
752 setOperationAction(ISD::FREM, VT, Expand);
753 setOperationAction(ISD::FMA, VT, Expand);
754 setOperationAction(ISD::FPOWI, VT, Expand);
755 setOperationAction(ISD::FSQRT, VT, Expand);
756 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757 setOperationAction(ISD::FFLOOR, VT, Expand);
758 setOperationAction(ISD::FCEIL, VT, Expand);
759 setOperationAction(ISD::FTRUNC, VT, Expand);
760 setOperationAction(ISD::FRINT, VT, Expand);
761 setOperationAction(ISD::FNEARBYINT, VT, Expand);
762 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764 setOperationAction(ISD::SDIVREM, VT, Expand);
765 setOperationAction(ISD::UDIVREM, VT, Expand);
766 setOperationAction(ISD::FPOW, VT, Expand);
767 setOperationAction(ISD::CTPOP, VT, Expand);
768 setOperationAction(ISD::CTTZ, VT, Expand);
769 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770 setOperationAction(ISD::CTLZ, VT, Expand);
771 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772 setOperationAction(ISD::SHL, VT, Expand);
773 setOperationAction(ISD::SRA, VT, Expand);
774 setOperationAction(ISD::SRL, VT, Expand);
775 setOperationAction(ISD::ROTL, VT, Expand);
776 setOperationAction(ISD::ROTR, VT, Expand);
777 setOperationAction(ISD::BSWAP, VT, Expand);
778 setOperationAction(ISD::SETCC, VT, Expand);
779 setOperationAction(ISD::FLOG, VT, Expand);
780 setOperationAction(ISD::FLOG2, VT, Expand);
781 setOperationAction(ISD::FLOG10, VT, Expand);
782 setOperationAction(ISD::FEXP, VT, Expand);
783 setOperationAction(ISD::FEXP2, VT, Expand);
784 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789 setOperationAction(ISD::TRUNCATE, VT, Expand);
790 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793 setOperationAction(ISD::VSELECT, VT, Expand);
794 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796 setTruncStoreAction(VT,
797 (MVT::SimpleValueType)InnerVT, Expand);
798 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
803 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804 // with -msoft-float, disable use of MMX as well.
805 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807 // No operations on x86mmx supported, everything uses intrinsics.
810 // MMX-sized vectors (other than x86mmx) are expected to be expanded
811 // into smaller operations.
812 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
813 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
814 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
815 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
816 setOperationAction(ISD::AND, MVT::v8i8, Expand);
817 setOperationAction(ISD::AND, MVT::v4i16, Expand);
818 setOperationAction(ISD::AND, MVT::v2i32, Expand);
819 setOperationAction(ISD::AND, MVT::v1i64, Expand);
820 setOperationAction(ISD::OR, MVT::v8i8, Expand);
821 setOperationAction(ISD::OR, MVT::v4i16, Expand);
822 setOperationAction(ISD::OR, MVT::v2i32, Expand);
823 setOperationAction(ISD::OR, MVT::v1i64, Expand);
824 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
825 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
826 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
827 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
831 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
833 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
834 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
835 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
836 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
837 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
838 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
839 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
840 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
842 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
845 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
846 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
847 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
848 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
849 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
850 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
851 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
852 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
853 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
854 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
855 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
859 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
862 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863 // registers cannot be used even for integer operations.
864 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
869 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
870 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
871 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
872 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
873 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
874 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
875 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
876 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
877 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
878 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
879 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
880 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
881 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
882 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
883 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
884 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
885 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
886 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
888 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
889 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
890 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
891 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
895 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
896 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
899 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901 MVT VT = (MVT::SimpleValueType)i;
902 // Do not attempt to custom lower non-power-of-2 vectors
903 if (!isPowerOf2_32(VT.getVectorNumElements()))
905 // Do not attempt to custom lower non-128-bit vectors
906 if (!VT.is128BitVector())
908 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
909 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
913 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
914 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
915 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
916 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
917 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
918 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
920 if (Subtarget->is64Bit()) {
921 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
925 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927 MVT VT = (MVT::SimpleValueType)i;
929 // Do not attempt to promote non-128-bit vectors
930 if (!VT.is128BitVector())
933 setOperationAction(ISD::AND, VT, Promote);
934 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
935 setOperationAction(ISD::OR, VT, Promote);
936 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
937 setOperationAction(ISD::XOR, VT, Promote);
938 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
939 setOperationAction(ISD::LOAD, VT, Promote);
940 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
941 setOperationAction(ISD::SELECT, VT, Promote);
942 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
945 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
947 // Custom lower v2i64 and v2f64 selects.
948 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
949 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
950 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
951 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
953 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
954 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
956 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
957 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
958 // As there is no 64-bit GPR available, we need build a special custom
959 // sequence to convert from v2i32 to v2f32.
960 if (!Subtarget->is64Bit())
961 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
963 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
964 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
966 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
969 if (Subtarget->hasSSE41()) {
970 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
971 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
972 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
973 setOperationAction(ISD::FRINT, MVT::f32, Legal);
974 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
975 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
976 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
977 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
978 setOperationAction(ISD::FRINT, MVT::f64, Legal);
979 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
981 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
982 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
983 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
984 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
985 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
986 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
987 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
988 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
989 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
990 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
992 // FIXME: Do we need to handle scalar-to-vector here?
993 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
995 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
996 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
997 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
998 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
999 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1001 // i8 and i16 vectors are custom , because the source register and source
1002 // source memory operand types are not the same width. f32 vectors are
1003 // custom since the immediate controlling the insert encodes additional
1005 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1006 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1007 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1008 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1010 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1015 // FIXME: these should be Legal but thats only for the case where
1016 // the index is constant. For now custom expand to deal with that.
1017 if (Subtarget->is64Bit()) {
1018 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1019 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1023 if (Subtarget->hasSSE2()) {
1024 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1025 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1027 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1028 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1030 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1031 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1033 if (Subtarget->hasInt256()) {
1034 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1035 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1037 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1038 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1040 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1042 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1043 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1045 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1046 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1048 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1052 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1053 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1054 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1055 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1056 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1057 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1058 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1060 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1061 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1062 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1064 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1065 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1066 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1067 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1068 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1069 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1070 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1071 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1072 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1073 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1074 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1075 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1077 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1078 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1079 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1080 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1081 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1082 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1083 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1084 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1085 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1086 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1087 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1088 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1090 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1091 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1093 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1095 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1096 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1097 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1099 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1100 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1101 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1103 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1105 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1106 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1108 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1109 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1111 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1112 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1114 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1115 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1116 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1117 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1119 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1120 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1121 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1123 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1124 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1125 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1126 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1128 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1129 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1130 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1131 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1132 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1133 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1135 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1136 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1138 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1139 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1140 setOperationAction(ISD::FMA, MVT::f32, Legal);
1141 setOperationAction(ISD::FMA, MVT::f64, Legal);
1144 if (Subtarget->hasInt256()) {
1145 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1146 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1147 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1148 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1150 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1151 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1152 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1153 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1155 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1156 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1157 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1158 // Don't lower v32i8 because there is no 128-bit byte mul
1160 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1162 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1163 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1165 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1166 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1168 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1170 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1171 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1172 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1173 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1176 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1177 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1178 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1180 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1181 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1182 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1183 // Don't lower v32i8 because there is no 128-bit byte mul
1185 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1186 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1188 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1189 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1191 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1194 // Custom lower several nodes for 256-bit types.
1195 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1196 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1197 MVT VT = (MVT::SimpleValueType)i;
1199 // Extract subvector is special because the value type
1200 // (result) is 128-bit but the source is 256-bit wide.
1201 if (VT.is128BitVector())
1202 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1204 // Do not attempt to custom lower other non-256-bit vectors
1205 if (!VT.is256BitVector())
1208 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1209 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1210 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1211 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1212 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1213 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1214 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1217 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1218 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1219 MVT VT = (MVT::SimpleValueType)i;
1221 // Do not attempt to promote non-256-bit vectors
1222 if (!VT.is256BitVector())
1225 setOperationAction(ISD::AND, VT, Promote);
1226 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1227 setOperationAction(ISD::OR, VT, Promote);
1228 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1229 setOperationAction(ISD::XOR, VT, Promote);
1230 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1231 setOperationAction(ISD::LOAD, VT, Promote);
1232 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1233 setOperationAction(ISD::SELECT, VT, Promote);
1234 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1238 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1239 // of this type with custom code.
1240 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1241 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1242 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1246 // We want to custom lower some of our intrinsics.
1247 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1248 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1250 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1251 // handle type legalization for these operations here.
1253 // FIXME: We really should do custom legalization for addition and
1254 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1255 // than generic legalization for 64-bit multiplication-with-overflow, though.
1256 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1257 // Add/Sub/Mul with overflow operations are custom lowered.
1259 setOperationAction(ISD::SADDO, VT, Custom);
1260 setOperationAction(ISD::UADDO, VT, Custom);
1261 setOperationAction(ISD::SSUBO, VT, Custom);
1262 setOperationAction(ISD::USUBO, VT, Custom);
1263 setOperationAction(ISD::SMULO, VT, Custom);
1264 setOperationAction(ISD::UMULO, VT, Custom);
1267 // There are no 8-bit 3-address imul/mul instructions
1268 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1269 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1271 if (!Subtarget->is64Bit()) {
1272 // These libcalls are not available in 32-bit.
1273 setLibcallName(RTLIB::SHL_I128, 0);
1274 setLibcallName(RTLIB::SRL_I128, 0);
1275 setLibcallName(RTLIB::SRA_I128, 0);
1278 // We have target-specific dag combine patterns for the following nodes:
1279 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1280 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1281 setTargetDAGCombine(ISD::VSELECT);
1282 setTargetDAGCombine(ISD::SELECT);
1283 setTargetDAGCombine(ISD::SHL);
1284 setTargetDAGCombine(ISD::SRA);
1285 setTargetDAGCombine(ISD::SRL);
1286 setTargetDAGCombine(ISD::OR);
1287 setTargetDAGCombine(ISD::AND);
1288 setTargetDAGCombine(ISD::ADD);
1289 setTargetDAGCombine(ISD::FADD);
1290 setTargetDAGCombine(ISD::FSUB);
1291 setTargetDAGCombine(ISD::FMA);
1292 setTargetDAGCombine(ISD::SUB);
1293 setTargetDAGCombine(ISD::LOAD);
1294 setTargetDAGCombine(ISD::STORE);
1295 setTargetDAGCombine(ISD::ZERO_EXTEND);
1296 setTargetDAGCombine(ISD::ANY_EXTEND);
1297 setTargetDAGCombine(ISD::SIGN_EXTEND);
1298 setTargetDAGCombine(ISD::TRUNCATE);
1299 setTargetDAGCombine(ISD::SINT_TO_FP);
1300 setTargetDAGCombine(ISD::SETCC);
1301 if (Subtarget->is64Bit())
1302 setTargetDAGCombine(ISD::MUL);
1303 setTargetDAGCombine(ISD::XOR);
1305 computeRegisterProperties();
1307 // On Darwin, -Os means optimize for size without hurting performance,
1308 // do not reduce the limit.
1309 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1310 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1311 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1312 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1313 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1314 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1315 setPrefLoopAlignment(4); // 2^4 bytes.
1316 benefitFromCodePlacementOpt = true;
1318 // Predictable cmov don't hurt on atom because it's in-order.
1319 predictableSelectIsExpensive = !Subtarget->isAtom();
1321 setPrefFunctionAlignment(4); // 2^4 bytes.
1324 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1325 if (!VT.isVector()) return MVT::i8;
1326 return VT.changeVectorElementTypeToInteger();
1329 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1330 /// the desired ByVal argument alignment.
1331 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1334 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1335 if (VTy->getBitWidth() == 128)
1337 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1338 unsigned EltAlign = 0;
1339 getMaxByValAlign(ATy->getElementType(), EltAlign);
1340 if (EltAlign > MaxAlign)
1341 MaxAlign = EltAlign;
1342 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1343 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1344 unsigned EltAlign = 0;
1345 getMaxByValAlign(STy->getElementType(i), EltAlign);
1346 if (EltAlign > MaxAlign)
1347 MaxAlign = EltAlign;
1354 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1355 /// function arguments in the caller parameter area. For X86, aggregates
1356 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1357 /// are at 4-byte boundaries.
1358 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1359 if (Subtarget->is64Bit()) {
1360 // Max of 8 and alignment of type.
1361 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1368 if (Subtarget->hasSSE1())
1369 getMaxByValAlign(Ty, Align);
1373 /// getOptimalMemOpType - Returns the target specific optimal type for load
1374 /// and store operations as a result of memset, memcpy, and memmove
1375 /// lowering. If DstAlign is zero that means it's safe to destination
1376 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1377 /// means there isn't a need to check it against alignment requirement,
1378 /// probably because the source does not need to be loaded. If 'IsMemset' is
1379 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1380 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1381 /// source is constant so it does not need to be loaded.
1382 /// It returns EVT::Other if the type should be determined using generic
1383 /// target-independent logic.
1385 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1386 unsigned DstAlign, unsigned SrcAlign,
1387 bool IsMemset, bool ZeroMemset,
1389 MachineFunction &MF) const {
1390 const Function *F = MF.getFunction();
1391 if ((!IsMemset || ZeroMemset) &&
1392 !F->getFnAttributes().hasAttribute(Attribute::NoImplicitFloat)) {
1394 (Subtarget->isUnalignedMemAccessFast() ||
1395 ((DstAlign == 0 || DstAlign >= 16) &&
1396 (SrcAlign == 0 || SrcAlign >= 16)))) {
1398 if (Subtarget->hasInt256())
1400 if (Subtarget->hasFp256())
1403 if (Subtarget->hasSSE2())
1405 if (Subtarget->hasSSE1())
1407 } else if (!MemcpyStrSrc && Size >= 8 &&
1408 !Subtarget->is64Bit() &&
1409 Subtarget->hasSSE2()) {
1410 // Do not use f64 to lower memcpy if source is string constant. It's
1411 // better to use i32 to avoid the loads.
1415 if (Subtarget->is64Bit() && Size >= 8)
1420 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1422 return X86ScalarSSEf32;
1423 else if (VT == MVT::f64)
1424 return X86ScalarSSEf64;
1429 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1431 *Fast = Subtarget->isUnalignedMemAccessFast();
1435 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1436 /// current function. The returned value is a member of the
1437 /// MachineJumpTableInfo::JTEntryKind enum.
1438 unsigned X86TargetLowering::getJumpTableEncoding() const {
1439 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1441 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1442 Subtarget->isPICStyleGOT())
1443 return MachineJumpTableInfo::EK_Custom32;
1445 // Otherwise, use the normal jump table encoding heuristics.
1446 return TargetLowering::getJumpTableEncoding();
1450 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1451 const MachineBasicBlock *MBB,
1452 unsigned uid,MCContext &Ctx) const{
1453 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1454 Subtarget->isPICStyleGOT());
1455 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1457 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1458 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1461 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1463 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1464 SelectionDAG &DAG) const {
1465 if (!Subtarget->is64Bit())
1466 // This doesn't have DebugLoc associated with it, but is not really the
1467 // same as a Register.
1468 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1472 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1473 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1475 const MCExpr *X86TargetLowering::
1476 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1477 MCContext &Ctx) const {
1478 // X86-64 uses RIP relative addressing based on the jump table label.
1479 if (Subtarget->isPICStyleRIPRel())
1480 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1482 // Otherwise, the reference is relative to the PIC base.
1483 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1486 // FIXME: Why this routine is here? Move to RegInfo!
1487 std::pair<const TargetRegisterClass*, uint8_t>
1488 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1489 const TargetRegisterClass *RRC = 0;
1491 switch (VT.SimpleTy) {
1493 return TargetLowering::findRepresentativeClass(VT);
1494 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1495 RRC = Subtarget->is64Bit() ?
1496 (const TargetRegisterClass*)&X86::GR64RegClass :
1497 (const TargetRegisterClass*)&X86::GR32RegClass;
1500 RRC = &X86::VR64RegClass;
1502 case MVT::f32: case MVT::f64:
1503 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1504 case MVT::v4f32: case MVT::v2f64:
1505 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1507 RRC = &X86::VR128RegClass;
1510 return std::make_pair(RRC, Cost);
1513 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1514 unsigned &Offset) const {
1515 if (!Subtarget->isTargetLinux())
1518 if (Subtarget->is64Bit()) {
1519 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1521 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1533 //===----------------------------------------------------------------------===//
1534 // Return Value Calling Convention Implementation
1535 //===----------------------------------------------------------------------===//
1537 #include "X86GenCallingConv.inc"
1540 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1541 MachineFunction &MF, bool isVarArg,
1542 const SmallVectorImpl<ISD::OutputArg> &Outs,
1543 LLVMContext &Context) const {
1544 SmallVector<CCValAssign, 16> RVLocs;
1545 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1547 return CCInfo.CheckReturn(Outs, RetCC_X86);
1551 X86TargetLowering::LowerReturn(SDValue Chain,
1552 CallingConv::ID CallConv, bool isVarArg,
1553 const SmallVectorImpl<ISD::OutputArg> &Outs,
1554 const SmallVectorImpl<SDValue> &OutVals,
1555 DebugLoc dl, SelectionDAG &DAG) const {
1556 MachineFunction &MF = DAG.getMachineFunction();
1557 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1559 SmallVector<CCValAssign, 16> RVLocs;
1560 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1561 RVLocs, *DAG.getContext());
1562 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1564 // Add the regs to the liveout set for the function.
1565 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1566 for (unsigned i = 0; i != RVLocs.size(); ++i)
1567 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1568 MRI.addLiveOut(RVLocs[i].getLocReg());
1572 SmallVector<SDValue, 6> RetOps;
1573 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1574 // Operand #1 = Bytes To Pop
1575 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1578 // Copy the result values into the output registers.
1579 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1580 CCValAssign &VA = RVLocs[i];
1581 assert(VA.isRegLoc() && "Can only return in registers!");
1582 SDValue ValToCopy = OutVals[i];
1583 EVT ValVT = ValToCopy.getValueType();
1585 // Promote values to the appropriate types
1586 if (VA.getLocInfo() == CCValAssign::SExt)
1587 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1588 else if (VA.getLocInfo() == CCValAssign::ZExt)
1589 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1590 else if (VA.getLocInfo() == CCValAssign::AExt)
1591 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1592 else if (VA.getLocInfo() == CCValAssign::BCvt)
1593 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1595 // If this is x86-64, and we disabled SSE, we can't return FP values,
1596 // or SSE or MMX vectors.
1597 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1598 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1599 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1600 report_fatal_error("SSE register return with SSE disabled");
1602 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1603 // llvm-gcc has never done it right and no one has noticed, so this
1604 // should be OK for now.
1605 if (ValVT == MVT::f64 &&
1606 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1607 report_fatal_error("SSE2 register return with SSE2 disabled");
1609 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1610 // the RET instruction and handled by the FP Stackifier.
1611 if (VA.getLocReg() == X86::ST0 ||
1612 VA.getLocReg() == X86::ST1) {
1613 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1614 // change the value to the FP stack register class.
1615 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1616 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1617 RetOps.push_back(ValToCopy);
1618 // Don't emit a copytoreg.
1622 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1623 // which is returned in RAX / RDX.
1624 if (Subtarget->is64Bit()) {
1625 if (ValVT == MVT::x86mmx) {
1626 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1627 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1628 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1630 // If we don't have SSE2 available, convert to v4f32 so the generated
1631 // register is legal.
1632 if (!Subtarget->hasSSE2())
1633 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1638 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1639 Flag = Chain.getValue(1);
1642 // The x86-64 ABI for returning structs by value requires that we copy
1643 // the sret argument into %rax for the return. We saved the argument into
1644 // a virtual register in the entry block, so now we copy the value out
1646 if (Subtarget->is64Bit() &&
1647 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1648 MachineFunction &MF = DAG.getMachineFunction();
1649 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1650 unsigned Reg = FuncInfo->getSRetReturnReg();
1652 "SRetReturnReg should have been set in LowerFormalArguments().");
1653 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1655 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1656 Flag = Chain.getValue(1);
1658 // RAX now acts like a return value.
1659 MRI.addLiveOut(X86::RAX);
1662 RetOps[0] = Chain; // Update chain.
1664 // Add the flag if we have it.
1666 RetOps.push_back(Flag);
1668 return DAG.getNode(X86ISD::RET_FLAG, dl,
1669 MVT::Other, &RetOps[0], RetOps.size());
1672 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1673 if (N->getNumValues() != 1)
1675 if (!N->hasNUsesOfValue(1, 0))
1678 SDValue TCChain = Chain;
1679 SDNode *Copy = *N->use_begin();
1680 if (Copy->getOpcode() == ISD::CopyToReg) {
1681 // If the copy has a glue operand, we conservatively assume it isn't safe to
1682 // perform a tail call.
1683 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1685 TCChain = Copy->getOperand(0);
1686 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1689 bool HasRet = false;
1690 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1692 if (UI->getOpcode() != X86ISD::RET_FLAG)
1705 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1706 ISD::NodeType ExtendKind) const {
1708 // TODO: Is this also valid on 32-bit?
1709 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1710 ReturnMVT = MVT::i8;
1712 ReturnMVT = MVT::i32;
1714 MVT MinVT = getRegisterType(ReturnMVT);
1715 return VT.bitsLT(MinVT) ? MinVT : VT;
1718 /// LowerCallResult - Lower the result values of a call into the
1719 /// appropriate copies out of appropriate physical registers.
1722 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1723 CallingConv::ID CallConv, bool isVarArg,
1724 const SmallVectorImpl<ISD::InputArg> &Ins,
1725 DebugLoc dl, SelectionDAG &DAG,
1726 SmallVectorImpl<SDValue> &InVals) const {
1728 // Assign locations to each value returned by this call.
1729 SmallVector<CCValAssign, 16> RVLocs;
1730 bool Is64Bit = Subtarget->is64Bit();
1731 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1732 getTargetMachine(), RVLocs, *DAG.getContext());
1733 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1735 // Copy all of the result registers out of their specified physreg.
1736 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1737 CCValAssign &VA = RVLocs[i];
1738 EVT CopyVT = VA.getValVT();
1740 // If this is x86-64, and we disabled SSE, we can't return FP values
1741 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1742 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1743 report_fatal_error("SSE register return with SSE disabled");
1748 // If this is a call to a function that returns an fp value on the floating
1749 // point stack, we must guarantee the value is popped from the stack, so
1750 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1751 // if the return value is not used. We use the FpPOP_RETVAL instruction
1753 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1754 // If we prefer to use the value in xmm registers, copy it out as f80 and
1755 // use a truncate to move it from fp stack reg to xmm reg.
1756 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1757 SDValue Ops[] = { Chain, InFlag };
1758 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1759 MVT::Other, MVT::Glue, Ops, 2), 1);
1760 Val = Chain.getValue(0);
1762 // Round the f80 to the right size, which also moves it to the appropriate
1764 if (CopyVT != VA.getValVT())
1765 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1766 // This truncation won't change the value.
1767 DAG.getIntPtrConstant(1));
1769 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1770 CopyVT, InFlag).getValue(1);
1771 Val = Chain.getValue(0);
1773 InFlag = Chain.getValue(2);
1774 InVals.push_back(Val);
1780 //===----------------------------------------------------------------------===//
1781 // C & StdCall & Fast Calling Convention implementation
1782 //===----------------------------------------------------------------------===//
1783 // StdCall calling convention seems to be standard for many Windows' API
1784 // routines and around. It differs from C calling convention just a little:
1785 // callee should clean up the stack, not caller. Symbols should be also
1786 // decorated in some fancy way :) It doesn't support any vector arguments.
1787 // For info on fast calling convention see Fast Calling Convention (tail call)
1788 // implementation LowerX86_32FastCCCallTo.
1790 /// CallIsStructReturn - Determines whether a call uses struct return
1792 enum StructReturnType {
1797 static StructReturnType
1798 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1800 return NotStructReturn;
1802 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1803 if (!Flags.isSRet())
1804 return NotStructReturn;
1805 if (Flags.isInReg())
1806 return RegStructReturn;
1807 return StackStructReturn;
1810 /// ArgsAreStructReturn - Determines whether a function uses struct
1811 /// return semantics.
1812 static StructReturnType
1813 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1815 return NotStructReturn;
1817 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1818 if (!Flags.isSRet())
1819 return NotStructReturn;
1820 if (Flags.isInReg())
1821 return RegStructReturn;
1822 return StackStructReturn;
1825 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1826 /// by "Src" to address "Dst" with size and alignment information specified by
1827 /// the specific parameter attribute. The copy will be passed as a byval
1828 /// function parameter.
1830 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1831 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1833 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1835 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1836 /*isVolatile*/false, /*AlwaysInline=*/true,
1837 MachinePointerInfo(), MachinePointerInfo());
1840 /// IsTailCallConvention - Return true if the calling convention is one that
1841 /// supports tail call optimization.
1842 static bool IsTailCallConvention(CallingConv::ID CC) {
1843 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1844 CC == CallingConv::HiPE);
1847 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1848 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1852 CallingConv::ID CalleeCC = CS.getCallingConv();
1853 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1859 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1860 /// a tailcall target by changing its ABI.
1861 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1862 bool GuaranteedTailCallOpt) {
1863 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1867 X86TargetLowering::LowerMemArgument(SDValue Chain,
1868 CallingConv::ID CallConv,
1869 const SmallVectorImpl<ISD::InputArg> &Ins,
1870 DebugLoc dl, SelectionDAG &DAG,
1871 const CCValAssign &VA,
1872 MachineFrameInfo *MFI,
1874 // Create the nodes corresponding to a load from this parameter slot.
1875 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1876 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1877 getTargetMachine().Options.GuaranteedTailCallOpt);
1878 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1881 // If value is passed by pointer we have address passed instead of the value
1883 if (VA.getLocInfo() == CCValAssign::Indirect)
1884 ValVT = VA.getLocVT();
1886 ValVT = VA.getValVT();
1888 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1889 // changed with more analysis.
1890 // In case of tail call optimization mark all arguments mutable. Since they
1891 // could be overwritten by lowering of arguments in case of a tail call.
1892 if (Flags.isByVal()) {
1893 unsigned Bytes = Flags.getByValSize();
1894 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1895 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1896 return DAG.getFrameIndex(FI, getPointerTy());
1898 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1899 VA.getLocMemOffset(), isImmutable);
1900 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1901 return DAG.getLoad(ValVT, dl, Chain, FIN,
1902 MachinePointerInfo::getFixedStack(FI),
1903 false, false, false, 0);
1908 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1909 CallingConv::ID CallConv,
1911 const SmallVectorImpl<ISD::InputArg> &Ins,
1914 SmallVectorImpl<SDValue> &InVals)
1916 MachineFunction &MF = DAG.getMachineFunction();
1917 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1919 const Function* Fn = MF.getFunction();
1920 if (Fn->hasExternalLinkage() &&
1921 Subtarget->isTargetCygMing() &&
1922 Fn->getName() == "main")
1923 FuncInfo->setForceFramePointer(true);
1925 MachineFrameInfo *MFI = MF.getFrameInfo();
1926 bool Is64Bit = Subtarget->is64Bit();
1927 bool IsWindows = Subtarget->isTargetWindows();
1928 bool IsWin64 = Subtarget->isTargetWin64();
1930 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1931 "Var args not supported with calling convention fastcc, ghc or hipe");
1933 // Assign locations to all of the incoming arguments.
1934 SmallVector<CCValAssign, 16> ArgLocs;
1935 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1936 ArgLocs, *DAG.getContext());
1938 // Allocate shadow area for Win64
1940 CCInfo.AllocateStack(32, 8);
1943 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1945 unsigned LastVal = ~0U;
1947 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1948 CCValAssign &VA = ArgLocs[i];
1949 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1951 assert(VA.getValNo() != LastVal &&
1952 "Don't support value assigned to multiple locs yet");
1954 LastVal = VA.getValNo();
1956 if (VA.isRegLoc()) {
1957 EVT RegVT = VA.getLocVT();
1958 const TargetRegisterClass *RC;
1959 if (RegVT == MVT::i32)
1960 RC = &X86::GR32RegClass;
1961 else if (Is64Bit && RegVT == MVT::i64)
1962 RC = &X86::GR64RegClass;
1963 else if (RegVT == MVT::f32)
1964 RC = &X86::FR32RegClass;
1965 else if (RegVT == MVT::f64)
1966 RC = &X86::FR64RegClass;
1967 else if (RegVT.is256BitVector())
1968 RC = &X86::VR256RegClass;
1969 else if (RegVT.is128BitVector())
1970 RC = &X86::VR128RegClass;
1971 else if (RegVT == MVT::x86mmx)
1972 RC = &X86::VR64RegClass;
1974 llvm_unreachable("Unknown argument type!");
1976 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1977 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1979 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1980 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1982 if (VA.getLocInfo() == CCValAssign::SExt)
1983 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1984 DAG.getValueType(VA.getValVT()));
1985 else if (VA.getLocInfo() == CCValAssign::ZExt)
1986 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1987 DAG.getValueType(VA.getValVT()));
1988 else if (VA.getLocInfo() == CCValAssign::BCvt)
1989 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1991 if (VA.isExtInLoc()) {
1992 // Handle MMX values passed in XMM regs.
1993 if (RegVT.isVector())
1994 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
1996 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1999 assert(VA.isMemLoc());
2000 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2003 // If value is passed via pointer - do a load.
2004 if (VA.getLocInfo() == CCValAssign::Indirect)
2005 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2006 MachinePointerInfo(), false, false, false, 0);
2008 InVals.push_back(ArgValue);
2011 // The x86-64 ABI for returning structs by value requires that we copy
2012 // the sret argument into %rax for the return. Save the argument into
2013 // a virtual register so that we can access it from the return points.
2014 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2015 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2016 unsigned Reg = FuncInfo->getSRetReturnReg();
2018 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2019 FuncInfo->setSRetReturnReg(Reg);
2021 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2022 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2025 unsigned StackSize = CCInfo.getNextStackOffset();
2026 // Align stack specially for tail calls.
2027 if (FuncIsMadeTailCallSafe(CallConv,
2028 MF.getTarget().Options.GuaranteedTailCallOpt))
2029 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2031 // If the function takes variable number of arguments, make a frame index for
2032 // the start of the first vararg value... for expansion of llvm.va_start.
2034 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2035 CallConv != CallingConv::X86_ThisCall)) {
2036 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2039 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2041 // FIXME: We should really autogenerate these arrays
2042 static const uint16_t GPR64ArgRegsWin64[] = {
2043 X86::RCX, X86::RDX, X86::R8, X86::R9
2045 static const uint16_t GPR64ArgRegs64Bit[] = {
2046 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2048 static const uint16_t XMMArgRegs64Bit[] = {
2049 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2050 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2052 const uint16_t *GPR64ArgRegs;
2053 unsigned NumXMMRegs = 0;
2056 // The XMM registers which might contain var arg parameters are shadowed
2057 // in their paired GPR. So we only need to save the GPR to their home
2059 TotalNumIntRegs = 4;
2060 GPR64ArgRegs = GPR64ArgRegsWin64;
2062 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2063 GPR64ArgRegs = GPR64ArgRegs64Bit;
2065 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2068 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2071 bool NoImplicitFloatOps = Fn->getFnAttributes().
2072 hasAttribute(Attribute::NoImplicitFloat);
2073 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2074 "SSE register cannot be used when SSE is disabled!");
2075 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2076 NoImplicitFloatOps) &&
2077 "SSE register cannot be used when SSE is disabled!");
2078 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2079 !Subtarget->hasSSE1())
2080 // Kernel mode asks for SSE to be disabled, so don't push them
2082 TotalNumXMMRegs = 0;
2085 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2086 // Get to the caller-allocated home save location. Add 8 to account
2087 // for the return address.
2088 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2089 FuncInfo->setRegSaveFrameIndex(
2090 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2091 // Fixup to set vararg frame on shadow area (4 x i64).
2093 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2095 // For X86-64, if there are vararg parameters that are passed via
2096 // registers, then we must store them to their spots on the stack so
2097 // they may be loaded by deferencing the result of va_next.
2098 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2099 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2100 FuncInfo->setRegSaveFrameIndex(
2101 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2105 // Store the integer parameter registers.
2106 SmallVector<SDValue, 8> MemOps;
2107 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2109 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2110 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2111 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2112 DAG.getIntPtrConstant(Offset));
2113 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2114 &X86::GR64RegClass);
2115 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2117 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2118 MachinePointerInfo::getFixedStack(
2119 FuncInfo->getRegSaveFrameIndex(), Offset),
2121 MemOps.push_back(Store);
2125 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2126 // Now store the XMM (fp + vector) parameter registers.
2127 SmallVector<SDValue, 11> SaveXMMOps;
2128 SaveXMMOps.push_back(Chain);
2130 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2131 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2132 SaveXMMOps.push_back(ALVal);
2134 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2135 FuncInfo->getRegSaveFrameIndex()));
2136 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2137 FuncInfo->getVarArgsFPOffset()));
2139 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2140 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2141 &X86::VR128RegClass);
2142 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2143 SaveXMMOps.push_back(Val);
2145 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2147 &SaveXMMOps[0], SaveXMMOps.size()));
2150 if (!MemOps.empty())
2151 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2152 &MemOps[0], MemOps.size());
2156 // Some CCs need callee pop.
2157 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2158 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2159 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2161 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2162 // If this is an sret function, the return should pop the hidden pointer.
2163 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2164 argsAreStructReturn(Ins) == StackStructReturn)
2165 FuncInfo->setBytesToPopOnReturn(4);
2169 // RegSaveFrameIndex is X86-64 only.
2170 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2171 if (CallConv == CallingConv::X86_FastCall ||
2172 CallConv == CallingConv::X86_ThisCall)
2173 // fastcc functions can't have varargs.
2174 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2177 FuncInfo->setArgumentStackSize(StackSize);
2183 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2184 SDValue StackPtr, SDValue Arg,
2185 DebugLoc dl, SelectionDAG &DAG,
2186 const CCValAssign &VA,
2187 ISD::ArgFlagsTy Flags) const {
2188 unsigned LocMemOffset = VA.getLocMemOffset();
2189 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2190 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2191 if (Flags.isByVal())
2192 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2194 return DAG.getStore(Chain, dl, Arg, PtrOff,
2195 MachinePointerInfo::getStack(LocMemOffset),
2199 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2200 /// optimization is performed and it is required.
2202 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2203 SDValue &OutRetAddr, SDValue Chain,
2204 bool IsTailCall, bool Is64Bit,
2205 int FPDiff, DebugLoc dl) const {
2206 // Adjust the Return address stack slot.
2207 EVT VT = getPointerTy();
2208 OutRetAddr = getReturnAddressFrameIndex(DAG);
2210 // Load the "old" Return address.
2211 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2212 false, false, false, 0);
2213 return SDValue(OutRetAddr.getNode(), 1);
2216 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2217 /// optimization is performed and it is required (FPDiff!=0).
2219 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2220 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2221 unsigned SlotSize, int FPDiff, DebugLoc dl) {
2222 // Store the return address to the appropriate stack slot.
2223 if (!FPDiff) return Chain;
2224 // Calculate the new stack slot for the return address.
2225 int NewReturnAddrFI =
2226 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2227 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2228 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2229 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2235 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2236 SmallVectorImpl<SDValue> &InVals) const {
2237 SelectionDAG &DAG = CLI.DAG;
2238 DebugLoc &dl = CLI.DL;
2239 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2240 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2241 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2242 SDValue Chain = CLI.Chain;
2243 SDValue Callee = CLI.Callee;
2244 CallingConv::ID CallConv = CLI.CallConv;
2245 bool &isTailCall = CLI.IsTailCall;
2246 bool isVarArg = CLI.IsVarArg;
2248 MachineFunction &MF = DAG.getMachineFunction();
2249 bool Is64Bit = Subtarget->is64Bit();
2250 bool IsWin64 = Subtarget->isTargetWin64();
2251 bool IsWindows = Subtarget->isTargetWindows();
2252 StructReturnType SR = callIsStructReturn(Outs);
2253 bool IsSibcall = false;
2255 if (MF.getTarget().Options.DisableTailCalls)
2259 // Check if it's really possible to do a tail call.
2260 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2261 isVarArg, SR != NotStructReturn,
2262 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2263 Outs, OutVals, Ins, DAG);
2265 // Sibcalls are automatically detected tailcalls which do not require
2267 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2274 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2275 "Var args not supported with calling convention fastcc, ghc or hipe");
2277 // Analyze operands of the call, assigning locations to each operand.
2278 SmallVector<CCValAssign, 16> ArgLocs;
2279 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2280 ArgLocs, *DAG.getContext());
2282 // Allocate shadow area for Win64
2284 CCInfo.AllocateStack(32, 8);
2287 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2289 // Get a count of how many bytes are to be pushed on the stack.
2290 unsigned NumBytes = CCInfo.getNextStackOffset();
2292 // This is a sibcall. The memory operands are available in caller's
2293 // own caller's stack.
2295 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2296 IsTailCallConvention(CallConv))
2297 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2300 if (isTailCall && !IsSibcall) {
2301 // Lower arguments at fp - stackoffset + fpdiff.
2302 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2303 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2305 FPDiff = NumBytesCallerPushed - NumBytes;
2307 // Set the delta of movement of the returnaddr stackslot.
2308 // But only set if delta is greater than previous delta.
2309 if (FPDiff < X86Info->getTCReturnAddrDelta())
2310 X86Info->setTCReturnAddrDelta(FPDiff);
2314 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2316 SDValue RetAddrFrIdx;
2317 // Load return address for tail calls.
2318 if (isTailCall && FPDiff)
2319 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2320 Is64Bit, FPDiff, dl);
2322 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2323 SmallVector<SDValue, 8> MemOpChains;
2326 // Walk the register/memloc assignments, inserting copies/loads. In the case
2327 // of tail call optimization arguments are handle later.
2328 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2329 CCValAssign &VA = ArgLocs[i];
2330 EVT RegVT = VA.getLocVT();
2331 SDValue Arg = OutVals[i];
2332 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2333 bool isByVal = Flags.isByVal();
2335 // Promote the value if needed.
2336 switch (VA.getLocInfo()) {
2337 default: llvm_unreachable("Unknown loc info!");
2338 case CCValAssign::Full: break;
2339 case CCValAssign::SExt:
2340 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2342 case CCValAssign::ZExt:
2343 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2345 case CCValAssign::AExt:
2346 if (RegVT.is128BitVector()) {
2347 // Special case: passing MMX values in XMM registers.
2348 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2349 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2350 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2352 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2354 case CCValAssign::BCvt:
2355 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2357 case CCValAssign::Indirect: {
2358 // Store the argument.
2359 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2360 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2361 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2362 MachinePointerInfo::getFixedStack(FI),
2369 if (VA.isRegLoc()) {
2370 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2371 if (isVarArg && IsWin64) {
2372 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2373 // shadow reg if callee is a varargs function.
2374 unsigned ShadowReg = 0;
2375 switch (VA.getLocReg()) {
2376 case X86::XMM0: ShadowReg = X86::RCX; break;
2377 case X86::XMM1: ShadowReg = X86::RDX; break;
2378 case X86::XMM2: ShadowReg = X86::R8; break;
2379 case X86::XMM3: ShadowReg = X86::R9; break;
2382 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2384 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2385 assert(VA.isMemLoc());
2386 if (StackPtr.getNode() == 0)
2387 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2389 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2390 dl, DAG, VA, Flags));
2394 if (!MemOpChains.empty())
2395 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2396 &MemOpChains[0], MemOpChains.size());
2398 if (Subtarget->isPICStyleGOT()) {
2399 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2402 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2403 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2405 // If we are tail calling and generating PIC/GOT style code load the
2406 // address of the callee into ECX. The value in ecx is used as target of
2407 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2408 // for tail calls on PIC/GOT architectures. Normally we would just put the
2409 // address of GOT into ebx and then call target@PLT. But for tail calls
2410 // ebx would be restored (since ebx is callee saved) before jumping to the
2413 // Note: The actual moving to ECX is done further down.
2414 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2415 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2416 !G->getGlobal()->hasProtectedVisibility())
2417 Callee = LowerGlobalAddress(Callee, DAG);
2418 else if (isa<ExternalSymbolSDNode>(Callee))
2419 Callee = LowerExternalSymbol(Callee, DAG);
2423 if (Is64Bit && isVarArg && !IsWin64) {
2424 // From AMD64 ABI document:
2425 // For calls that may call functions that use varargs or stdargs
2426 // (prototype-less calls or calls to functions containing ellipsis (...) in
2427 // the declaration) %al is used as hidden argument to specify the number
2428 // of SSE registers used. The contents of %al do not need to match exactly
2429 // the number of registers, but must be an ubound on the number of SSE
2430 // registers used and is in the range 0 - 8 inclusive.
2432 // Count the number of XMM registers allocated.
2433 static const uint16_t XMMArgRegs[] = {
2434 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2435 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2437 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2438 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2439 && "SSE registers cannot be used when SSE is disabled");
2441 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2442 DAG.getConstant(NumXMMRegs, MVT::i8)));
2445 // For tail calls lower the arguments to the 'real' stack slot.
2447 // Force all the incoming stack arguments to be loaded from the stack
2448 // before any new outgoing arguments are stored to the stack, because the
2449 // outgoing stack slots may alias the incoming argument stack slots, and
2450 // the alias isn't otherwise explicit. This is slightly more conservative
2451 // than necessary, because it means that each store effectively depends
2452 // on every argument instead of just those arguments it would clobber.
2453 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2455 SmallVector<SDValue, 8> MemOpChains2;
2458 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2459 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2460 CCValAssign &VA = ArgLocs[i];
2463 assert(VA.isMemLoc());
2464 SDValue Arg = OutVals[i];
2465 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2466 // Create frame index.
2467 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2468 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2469 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2470 FIN = DAG.getFrameIndex(FI, getPointerTy());
2472 if (Flags.isByVal()) {
2473 // Copy relative to framepointer.
2474 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2475 if (StackPtr.getNode() == 0)
2476 StackPtr = DAG.getCopyFromReg(Chain, dl,
2477 RegInfo->getStackRegister(),
2479 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2481 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2485 // Store relative to framepointer.
2486 MemOpChains2.push_back(
2487 DAG.getStore(ArgChain, dl, Arg, FIN,
2488 MachinePointerInfo::getFixedStack(FI),
2494 if (!MemOpChains2.empty())
2495 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2496 &MemOpChains2[0], MemOpChains2.size());
2498 // Store the return address to the appropriate stack slot.
2499 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2500 getPointerTy(), RegInfo->getSlotSize(),
2504 // Build a sequence of copy-to-reg nodes chained together with token chain
2505 // and flag operands which copy the outgoing args into registers.
2507 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2508 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2509 RegsToPass[i].second, InFlag);
2510 InFlag = Chain.getValue(1);
2513 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2514 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2515 // In the 64-bit large code model, we have to make all calls
2516 // through a register, since the call instruction's 32-bit
2517 // pc-relative offset may not be large enough to hold the whole
2519 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2520 // If the callee is a GlobalAddress node (quite common, every direct call
2521 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2524 // We should use extra load for direct calls to dllimported functions in
2526 const GlobalValue *GV = G->getGlobal();
2527 if (!GV->hasDLLImportLinkage()) {
2528 unsigned char OpFlags = 0;
2529 bool ExtraLoad = false;
2530 unsigned WrapperKind = ISD::DELETED_NODE;
2532 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2533 // external symbols most go through the PLT in PIC mode. If the symbol
2534 // has hidden or protected visibility, or if it is static or local, then
2535 // we don't need to use the PLT - we can directly call it.
2536 if (Subtarget->isTargetELF() &&
2537 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2538 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2539 OpFlags = X86II::MO_PLT;
2540 } else if (Subtarget->isPICStyleStubAny() &&
2541 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2542 (!Subtarget->getTargetTriple().isMacOSX() ||
2543 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2544 // PC-relative references to external symbols should go through $stub,
2545 // unless we're building with the leopard linker or later, which
2546 // automatically synthesizes these stubs.
2547 OpFlags = X86II::MO_DARWIN_STUB;
2548 } else if (Subtarget->isPICStyleRIPRel() &&
2549 isa<Function>(GV) &&
2550 cast<Function>(GV)->getFnAttributes().
2551 hasAttribute(Attribute::NonLazyBind)) {
2552 // If the function is marked as non-lazy, generate an indirect call
2553 // which loads from the GOT directly. This avoids runtime overhead
2554 // at the cost of eager binding (and one extra byte of encoding).
2555 OpFlags = X86II::MO_GOTPCREL;
2556 WrapperKind = X86ISD::WrapperRIP;
2560 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2561 G->getOffset(), OpFlags);
2563 // Add a wrapper if needed.
2564 if (WrapperKind != ISD::DELETED_NODE)
2565 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2566 // Add extra indirection if needed.
2568 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2569 MachinePointerInfo::getGOT(),
2570 false, false, false, 0);
2572 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2573 unsigned char OpFlags = 0;
2575 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2576 // external symbols should go through the PLT.
2577 if (Subtarget->isTargetELF() &&
2578 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2579 OpFlags = X86II::MO_PLT;
2580 } else if (Subtarget->isPICStyleStubAny() &&
2581 (!Subtarget->getTargetTriple().isMacOSX() ||
2582 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2583 // PC-relative references to external symbols should go through $stub,
2584 // unless we're building with the leopard linker or later, which
2585 // automatically synthesizes these stubs.
2586 OpFlags = X86II::MO_DARWIN_STUB;
2589 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2593 // Returns a chain & a flag for retval copy to use.
2594 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2595 SmallVector<SDValue, 8> Ops;
2597 if (!IsSibcall && isTailCall) {
2598 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2599 DAG.getIntPtrConstant(0, true), InFlag);
2600 InFlag = Chain.getValue(1);
2603 Ops.push_back(Chain);
2604 Ops.push_back(Callee);
2607 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2609 // Add argument registers to the end of the list so that they are known live
2611 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2612 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2613 RegsToPass[i].second.getValueType()));
2615 // Add a register mask operand representing the call-preserved registers.
2616 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2617 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2618 assert(Mask && "Missing call preserved mask for calling convention");
2619 Ops.push_back(DAG.getRegisterMask(Mask));
2621 if (InFlag.getNode())
2622 Ops.push_back(InFlag);
2626 //// If this is the first return lowered for this function, add the regs
2627 //// to the liveout set for the function.
2628 // This isn't right, although it's probably harmless on x86; liveouts
2629 // should be computed from returns not tail calls. Consider a void
2630 // function making a tail call to a function returning int.
2631 return DAG.getNode(X86ISD::TC_RETURN, dl,
2632 NodeTys, &Ops[0], Ops.size());
2635 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2636 InFlag = Chain.getValue(1);
2638 // Create the CALLSEQ_END node.
2639 unsigned NumBytesForCalleeToPush;
2640 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2641 getTargetMachine().Options.GuaranteedTailCallOpt))
2642 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2643 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2644 SR == StackStructReturn)
2645 // If this is a call to a struct-return function, the callee
2646 // pops the hidden struct pointer, so we have to push it back.
2647 // This is common for Darwin/X86, Linux & Mingw32 targets.
2648 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2649 NumBytesForCalleeToPush = 4;
2651 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2653 // Returns a flag for retval copy to use.
2655 Chain = DAG.getCALLSEQ_END(Chain,
2656 DAG.getIntPtrConstant(NumBytes, true),
2657 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2660 InFlag = Chain.getValue(1);
2663 // Handle result values, copying them out of physregs into vregs that we
2665 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2666 Ins, dl, DAG, InVals);
2669 //===----------------------------------------------------------------------===//
2670 // Fast Calling Convention (tail call) implementation
2671 //===----------------------------------------------------------------------===//
2673 // Like std call, callee cleans arguments, convention except that ECX is
2674 // reserved for storing the tail called function address. Only 2 registers are
2675 // free for argument passing (inreg). Tail call optimization is performed
2677 // * tailcallopt is enabled
2678 // * caller/callee are fastcc
2679 // On X86_64 architecture with GOT-style position independent code only local
2680 // (within module) calls are supported at the moment.
2681 // To keep the stack aligned according to platform abi the function
2682 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2683 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2684 // If a tail called function callee has more arguments than the caller the
2685 // caller needs to make sure that there is room to move the RETADDR to. This is
2686 // achieved by reserving an area the size of the argument delta right after the
2687 // original REtADDR, but before the saved framepointer or the spilled registers
2688 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2700 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2701 /// for a 16 byte align requirement.
2703 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2704 SelectionDAG& DAG) const {
2705 MachineFunction &MF = DAG.getMachineFunction();
2706 const TargetMachine &TM = MF.getTarget();
2707 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2708 unsigned StackAlignment = TFI.getStackAlignment();
2709 uint64_t AlignMask = StackAlignment - 1;
2710 int64_t Offset = StackSize;
2711 unsigned SlotSize = RegInfo->getSlotSize();
2712 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2713 // Number smaller than 12 so just add the difference.
2714 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2716 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2717 Offset = ((~AlignMask) & Offset) + StackAlignment +
2718 (StackAlignment-SlotSize);
2723 /// MatchingStackOffset - Return true if the given stack call argument is
2724 /// already available in the same position (relatively) of the caller's
2725 /// incoming argument stack.
2727 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2728 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2729 const X86InstrInfo *TII) {
2730 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2732 if (Arg.getOpcode() == ISD::CopyFromReg) {
2733 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2734 if (!TargetRegisterInfo::isVirtualRegister(VR))
2736 MachineInstr *Def = MRI->getVRegDef(VR);
2739 if (!Flags.isByVal()) {
2740 if (!TII->isLoadFromStackSlot(Def, FI))
2743 unsigned Opcode = Def->getOpcode();
2744 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2745 Def->getOperand(1).isFI()) {
2746 FI = Def->getOperand(1).getIndex();
2747 Bytes = Flags.getByValSize();
2751 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2752 if (Flags.isByVal())
2753 // ByVal argument is passed in as a pointer but it's now being
2754 // dereferenced. e.g.
2755 // define @foo(%struct.X* %A) {
2756 // tail call @bar(%struct.X* byval %A)
2759 SDValue Ptr = Ld->getBasePtr();
2760 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2763 FI = FINode->getIndex();
2764 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2765 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2766 FI = FINode->getIndex();
2767 Bytes = Flags.getByValSize();
2771 assert(FI != INT_MAX);
2772 if (!MFI->isFixedObjectIndex(FI))
2774 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2777 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2778 /// for tail call optimization. Targets which want to do tail call
2779 /// optimization should implement this function.
2781 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2782 CallingConv::ID CalleeCC,
2784 bool isCalleeStructRet,
2785 bool isCallerStructRet,
2787 const SmallVectorImpl<ISD::OutputArg> &Outs,
2788 const SmallVectorImpl<SDValue> &OutVals,
2789 const SmallVectorImpl<ISD::InputArg> &Ins,
2790 SelectionDAG& DAG) const {
2791 if (!IsTailCallConvention(CalleeCC) &&
2792 CalleeCC != CallingConv::C)
2795 // If -tailcallopt is specified, make fastcc functions tail-callable.
2796 const MachineFunction &MF = DAG.getMachineFunction();
2797 const Function *CallerF = DAG.getMachineFunction().getFunction();
2799 // If the function return type is x86_fp80 and the callee return type is not,
2800 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2801 // perform a tailcall optimization here.
2802 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2805 CallingConv::ID CallerCC = CallerF->getCallingConv();
2806 bool CCMatch = CallerCC == CalleeCC;
2808 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2809 if (IsTailCallConvention(CalleeCC) && CCMatch)
2814 // Look for obvious safe cases to perform tail call optimization that do not
2815 // require ABI changes. This is what gcc calls sibcall.
2817 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2818 // emit a special epilogue.
2819 if (RegInfo->needsStackRealignment(MF))
2822 // Also avoid sibcall optimization if either caller or callee uses struct
2823 // return semantics.
2824 if (isCalleeStructRet || isCallerStructRet)
2827 // An stdcall caller is expected to clean up its arguments; the callee
2828 // isn't going to do that.
2829 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2832 // Do not sibcall optimize vararg calls unless all arguments are passed via
2834 if (isVarArg && !Outs.empty()) {
2836 // Optimizing for varargs on Win64 is unlikely to be safe without
2837 // additional testing.
2838 if (Subtarget->isTargetWin64())
2841 SmallVector<CCValAssign, 16> ArgLocs;
2842 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2843 getTargetMachine(), ArgLocs, *DAG.getContext());
2845 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2846 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2847 if (!ArgLocs[i].isRegLoc())
2851 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2852 // stack. Therefore, if it's not used by the call it is not safe to optimize
2853 // this into a sibcall.
2854 bool Unused = false;
2855 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2862 SmallVector<CCValAssign, 16> RVLocs;
2863 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2864 getTargetMachine(), RVLocs, *DAG.getContext());
2865 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2866 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2867 CCValAssign &VA = RVLocs[i];
2868 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2873 // If the calling conventions do not match, then we'd better make sure the
2874 // results are returned in the same way as what the caller expects.
2876 SmallVector<CCValAssign, 16> RVLocs1;
2877 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2878 getTargetMachine(), RVLocs1, *DAG.getContext());
2879 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2881 SmallVector<CCValAssign, 16> RVLocs2;
2882 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2883 getTargetMachine(), RVLocs2, *DAG.getContext());
2884 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2886 if (RVLocs1.size() != RVLocs2.size())
2888 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2889 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2891 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2893 if (RVLocs1[i].isRegLoc()) {
2894 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2897 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2903 // If the callee takes no arguments then go on to check the results of the
2905 if (!Outs.empty()) {
2906 // Check if stack adjustment is needed. For now, do not do this if any
2907 // argument is passed on the stack.
2908 SmallVector<CCValAssign, 16> ArgLocs;
2909 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2910 getTargetMachine(), ArgLocs, *DAG.getContext());
2912 // Allocate shadow area for Win64
2913 if (Subtarget->isTargetWin64()) {
2914 CCInfo.AllocateStack(32, 8);
2917 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2918 if (CCInfo.getNextStackOffset()) {
2919 MachineFunction &MF = DAG.getMachineFunction();
2920 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2923 // Check if the arguments are already laid out in the right way as
2924 // the caller's fixed stack objects.
2925 MachineFrameInfo *MFI = MF.getFrameInfo();
2926 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2927 const X86InstrInfo *TII =
2928 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2929 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2930 CCValAssign &VA = ArgLocs[i];
2931 SDValue Arg = OutVals[i];
2932 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2933 if (VA.getLocInfo() == CCValAssign::Indirect)
2935 if (!VA.isRegLoc()) {
2936 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2943 // If the tailcall address may be in a register, then make sure it's
2944 // possible to register allocate for it. In 32-bit, the call address can
2945 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2946 // callee-saved registers are restored. These happen to be the same
2947 // registers used to pass 'inreg' arguments so watch out for those.
2948 if (!Subtarget->is64Bit() &&
2949 !isa<GlobalAddressSDNode>(Callee) &&
2950 !isa<ExternalSymbolSDNode>(Callee)) {
2951 unsigned NumInRegs = 0;
2952 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2953 CCValAssign &VA = ArgLocs[i];
2956 unsigned Reg = VA.getLocReg();
2959 case X86::EAX: case X86::EDX: case X86::ECX:
2960 if (++NumInRegs == 3)
2972 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2973 const TargetLibraryInfo *libInfo) const {
2974 return X86::createFastISel(funcInfo, libInfo);
2977 //===----------------------------------------------------------------------===//
2978 // Other Lowering Hooks
2979 //===----------------------------------------------------------------------===//
2981 static bool MayFoldLoad(SDValue Op) {
2982 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2985 static bool MayFoldIntoStore(SDValue Op) {
2986 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2989 static bool isTargetShuffle(unsigned Opcode) {
2991 default: return false;
2992 case X86ISD::PSHUFD:
2993 case X86ISD::PSHUFHW:
2994 case X86ISD::PSHUFLW:
2996 case X86ISD::PALIGN:
2997 case X86ISD::MOVLHPS:
2998 case X86ISD::MOVLHPD:
2999 case X86ISD::MOVHLPS:
3000 case X86ISD::MOVLPS:
3001 case X86ISD::MOVLPD:
3002 case X86ISD::MOVSHDUP:
3003 case X86ISD::MOVSLDUP:
3004 case X86ISD::MOVDDUP:
3007 case X86ISD::UNPCKL:
3008 case X86ISD::UNPCKH:
3009 case X86ISD::VPERMILP:
3010 case X86ISD::VPERM2X128:
3011 case X86ISD::VPERMI:
3016 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3017 SDValue V1, SelectionDAG &DAG) {
3019 default: llvm_unreachable("Unknown x86 shuffle node");
3020 case X86ISD::MOVSHDUP:
3021 case X86ISD::MOVSLDUP:
3022 case X86ISD::MOVDDUP:
3023 return DAG.getNode(Opc, dl, VT, V1);
3027 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3028 SDValue V1, unsigned TargetMask,
3029 SelectionDAG &DAG) {
3031 default: llvm_unreachable("Unknown x86 shuffle node");
3032 case X86ISD::PSHUFD:
3033 case X86ISD::PSHUFHW:
3034 case X86ISD::PSHUFLW:
3035 case X86ISD::VPERMILP:
3036 case X86ISD::VPERMI:
3037 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3041 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3042 SDValue V1, SDValue V2, unsigned TargetMask,
3043 SelectionDAG &DAG) {
3045 default: llvm_unreachable("Unknown x86 shuffle node");
3046 case X86ISD::PALIGN:
3048 case X86ISD::VPERM2X128:
3049 return DAG.getNode(Opc, dl, VT, V1, V2,
3050 DAG.getConstant(TargetMask, MVT::i8));
3054 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3055 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3057 default: llvm_unreachable("Unknown x86 shuffle node");
3058 case X86ISD::MOVLHPS:
3059 case X86ISD::MOVLHPD:
3060 case X86ISD::MOVHLPS:
3061 case X86ISD::MOVLPS:
3062 case X86ISD::MOVLPD:
3065 case X86ISD::UNPCKL:
3066 case X86ISD::UNPCKH:
3067 return DAG.getNode(Opc, dl, VT, V1, V2);
3071 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3072 MachineFunction &MF = DAG.getMachineFunction();
3073 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3074 int ReturnAddrIndex = FuncInfo->getRAIndex();
3076 if (ReturnAddrIndex == 0) {
3077 // Set up a frame object for the return address.
3078 unsigned SlotSize = RegInfo->getSlotSize();
3079 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3081 FuncInfo->setRAIndex(ReturnAddrIndex);
3084 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3087 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3088 bool hasSymbolicDisplacement) {
3089 // Offset should fit into 32 bit immediate field.
3090 if (!isInt<32>(Offset))
3093 // If we don't have a symbolic displacement - we don't have any extra
3095 if (!hasSymbolicDisplacement)
3098 // FIXME: Some tweaks might be needed for medium code model.
3099 if (M != CodeModel::Small && M != CodeModel::Kernel)
3102 // For small code model we assume that latest object is 16MB before end of 31
3103 // bits boundary. We may also accept pretty large negative constants knowing
3104 // that all objects are in the positive half of address space.
3105 if (M == CodeModel::Small && Offset < 16*1024*1024)
3108 // For kernel code model we know that all object resist in the negative half
3109 // of 32bits address space. We may not accept negative offsets, since they may
3110 // be just off and we may accept pretty large positive ones.
3111 if (M == CodeModel::Kernel && Offset > 0)
3117 /// isCalleePop - Determines whether the callee is required to pop its
3118 /// own arguments. Callee pop is necessary to support tail calls.
3119 bool X86::isCalleePop(CallingConv::ID CallingConv,
3120 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3124 switch (CallingConv) {
3127 case CallingConv::X86_StdCall:
3129 case CallingConv::X86_FastCall:
3131 case CallingConv::X86_ThisCall:
3133 case CallingConv::Fast:
3135 case CallingConv::GHC:
3137 case CallingConv::HiPE:
3142 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3143 /// specific condition code, returning the condition code and the LHS/RHS of the
3144 /// comparison to make.
3145 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3146 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3148 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3149 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3150 // X > -1 -> X == 0, jump !sign.
3151 RHS = DAG.getConstant(0, RHS.getValueType());
3152 return X86::COND_NS;
3154 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3155 // X < 0 -> X == 0, jump on sign.
3158 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3160 RHS = DAG.getConstant(0, RHS.getValueType());
3161 return X86::COND_LE;
3165 switch (SetCCOpcode) {
3166 default: llvm_unreachable("Invalid integer condition!");
3167 case ISD::SETEQ: return X86::COND_E;
3168 case ISD::SETGT: return X86::COND_G;
3169 case ISD::SETGE: return X86::COND_GE;
3170 case ISD::SETLT: return X86::COND_L;
3171 case ISD::SETLE: return X86::COND_LE;
3172 case ISD::SETNE: return X86::COND_NE;
3173 case ISD::SETULT: return X86::COND_B;
3174 case ISD::SETUGT: return X86::COND_A;
3175 case ISD::SETULE: return X86::COND_BE;
3176 case ISD::SETUGE: return X86::COND_AE;
3180 // First determine if it is required or is profitable to flip the operands.
3182 // If LHS is a foldable load, but RHS is not, flip the condition.
3183 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3184 !ISD::isNON_EXTLoad(RHS.getNode())) {
3185 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3186 std::swap(LHS, RHS);
3189 switch (SetCCOpcode) {
3195 std::swap(LHS, RHS);
3199 // On a floating point condition, the flags are set as follows:
3201 // 0 | 0 | 0 | X > Y
3202 // 0 | 0 | 1 | X < Y
3203 // 1 | 0 | 0 | X == Y
3204 // 1 | 1 | 1 | unordered
3205 switch (SetCCOpcode) {
3206 default: llvm_unreachable("Condcode should be pre-legalized away");
3208 case ISD::SETEQ: return X86::COND_E;
3209 case ISD::SETOLT: // flipped
3211 case ISD::SETGT: return X86::COND_A;
3212 case ISD::SETOLE: // flipped
3214 case ISD::SETGE: return X86::COND_AE;
3215 case ISD::SETUGT: // flipped
3217 case ISD::SETLT: return X86::COND_B;
3218 case ISD::SETUGE: // flipped
3220 case ISD::SETLE: return X86::COND_BE;
3222 case ISD::SETNE: return X86::COND_NE;
3223 case ISD::SETUO: return X86::COND_P;
3224 case ISD::SETO: return X86::COND_NP;
3226 case ISD::SETUNE: return X86::COND_INVALID;
3230 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3231 /// code. Current x86 isa includes the following FP cmov instructions:
3232 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3233 static bool hasFPCMov(unsigned X86CC) {
3249 /// isFPImmLegal - Returns true if the target can instruction select the
3250 /// specified FP immediate natively. If false, the legalizer will
3251 /// materialize the FP immediate as a load from a constant pool.
3252 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3253 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3254 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3260 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3261 /// the specified range (L, H].
3262 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3263 return (Val < 0) || (Val >= Low && Val < Hi);
3266 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3267 /// specified value.
3268 static bool isUndefOrEqual(int Val, int CmpVal) {
3269 return (Val < 0 || Val == CmpVal);
3272 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3273 /// from position Pos and ending in Pos+Size, falls within the specified
3274 /// sequential range (L, L+Pos]. or is undef.
3275 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3276 unsigned Pos, unsigned Size, int Low) {
3277 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3278 if (!isUndefOrEqual(Mask[i], Low))
3283 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3284 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3285 /// the second operand.
3286 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3287 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3288 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3289 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3290 return (Mask[0] < 2 && Mask[1] < 2);
3294 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3295 /// is suitable for input to PSHUFHW.
3296 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3297 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3300 // Lower quadword copied in order or undef.
3301 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3304 // Upper quadword shuffled.
3305 for (unsigned i = 4; i != 8; ++i)
3306 if (!isUndefOrInRange(Mask[i], 4, 8))
3309 if (VT == MVT::v16i16) {
3310 // Lower quadword copied in order or undef.
3311 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3314 // Upper quadword shuffled.
3315 for (unsigned i = 12; i != 16; ++i)
3316 if (!isUndefOrInRange(Mask[i], 12, 16))
3323 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3324 /// is suitable for input to PSHUFLW.
3325 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3326 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3329 // Upper quadword copied in order.
3330 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3333 // Lower quadword shuffled.
3334 for (unsigned i = 0; i != 4; ++i)
3335 if (!isUndefOrInRange(Mask[i], 0, 4))
3338 if (VT == MVT::v16i16) {
3339 // Upper quadword copied in order.
3340 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3343 // Lower quadword shuffled.
3344 for (unsigned i = 8; i != 12; ++i)
3345 if (!isUndefOrInRange(Mask[i], 8, 12))
3352 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3353 /// is suitable for input to PALIGNR.
3354 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3355 const X86Subtarget *Subtarget) {
3356 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3357 (VT.getSizeInBits() == 256 && !Subtarget->hasInt256()))
3360 unsigned NumElts = VT.getVectorNumElements();
3361 unsigned NumLanes = VT.getSizeInBits()/128;
3362 unsigned NumLaneElts = NumElts/NumLanes;
3364 // Do not handle 64-bit element shuffles with palignr.
3365 if (NumLaneElts == 2)
3368 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3370 for (i = 0; i != NumLaneElts; ++i) {
3375 // Lane is all undef, go to next lane
3376 if (i == NumLaneElts)
3379 int Start = Mask[i+l];
3381 // Make sure its in this lane in one of the sources
3382 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3383 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3386 // If not lane 0, then we must match lane 0
3387 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3390 // Correct second source to be contiguous with first source
3391 if (Start >= (int)NumElts)
3392 Start -= NumElts - NumLaneElts;
3394 // Make sure we're shifting in the right direction.
3395 if (Start <= (int)(i+l))
3400 // Check the rest of the elements to see if they are consecutive.
3401 for (++i; i != NumLaneElts; ++i) {
3402 int Idx = Mask[i+l];
3404 // Make sure its in this lane
3405 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3406 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3409 // If not lane 0, then we must match lane 0
3410 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3413 if (Idx >= (int)NumElts)
3414 Idx -= NumElts - NumLaneElts;
3416 if (!isUndefOrEqual(Idx, Start+i))
3425 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3426 /// the two vector operands have swapped position.
3427 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3428 unsigned NumElems) {
3429 for (unsigned i = 0; i != NumElems; ++i) {
3433 else if (idx < (int)NumElems)
3434 Mask[i] = idx + NumElems;
3436 Mask[i] = idx - NumElems;
3440 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3441 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3442 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3443 /// reverse of what x86 shuffles want.
3444 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3445 bool Commuted = false) {
3446 if (!HasFp256 && VT.getSizeInBits() == 256)
3449 unsigned NumElems = VT.getVectorNumElements();
3450 unsigned NumLanes = VT.getSizeInBits()/128;
3451 unsigned NumLaneElems = NumElems/NumLanes;
3453 if (NumLaneElems != 2 && NumLaneElems != 4)
3456 // VSHUFPSY divides the resulting vector into 4 chunks.
3457 // The sources are also splitted into 4 chunks, and each destination
3458 // chunk must come from a different source chunk.
3460 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3461 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3463 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3464 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3466 // VSHUFPDY divides the resulting vector into 4 chunks.
3467 // The sources are also splitted into 4 chunks, and each destination
3468 // chunk must come from a different source chunk.
3470 // SRC1 => X3 X2 X1 X0
3471 // SRC2 => Y3 Y2 Y1 Y0
3473 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3475 unsigned HalfLaneElems = NumLaneElems/2;
3476 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3477 for (unsigned i = 0; i != NumLaneElems; ++i) {
3478 int Idx = Mask[i+l];
3479 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3480 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3482 // For VSHUFPSY, the mask of the second half must be the same as the
3483 // first but with the appropriate offsets. This works in the same way as
3484 // VPERMILPS works with masks.
3485 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3487 if (!isUndefOrEqual(Idx, Mask[i]+l))
3495 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3497 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3498 if (!VT.is128BitVector())
3501 unsigned NumElems = VT.getVectorNumElements();
3506 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3507 return isUndefOrEqual(Mask[0], 6) &&
3508 isUndefOrEqual(Mask[1], 7) &&
3509 isUndefOrEqual(Mask[2], 2) &&
3510 isUndefOrEqual(Mask[3], 3);
3513 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3514 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3516 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3517 if (!VT.is128BitVector())
3520 unsigned NumElems = VT.getVectorNumElements();
3525 return isUndefOrEqual(Mask[0], 2) &&
3526 isUndefOrEqual(Mask[1], 3) &&
3527 isUndefOrEqual(Mask[2], 2) &&
3528 isUndefOrEqual(Mask[3], 3);
3531 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3532 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3533 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3534 if (!VT.is128BitVector())
3537 unsigned NumElems = VT.getVectorNumElements();
3539 if (NumElems != 2 && NumElems != 4)
3542 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3543 if (!isUndefOrEqual(Mask[i], i + NumElems))
3546 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3547 if (!isUndefOrEqual(Mask[i], i))
3553 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3554 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3555 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3556 if (!VT.is128BitVector())
3559 unsigned NumElems = VT.getVectorNumElements();
3561 if (NumElems != 2 && NumElems != 4)
3564 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3565 if (!isUndefOrEqual(Mask[i], i))
3568 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3569 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3576 // Some special combinations that can be optimized.
3579 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3580 SelectionDAG &DAG) {
3581 EVT VT = SVOp->getValueType(0);
3582 DebugLoc dl = SVOp->getDebugLoc();
3584 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3587 ArrayRef<int> Mask = SVOp->getMask();
3589 // These are the special masks that may be optimized.
3590 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3591 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3592 bool MatchEvenMask = true;
3593 bool MatchOddMask = true;
3594 for (int i=0; i<8; ++i) {
3595 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3596 MatchEvenMask = false;
3597 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3598 MatchOddMask = false;
3601 if (!MatchEvenMask && !MatchOddMask)
3604 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3606 SDValue Op0 = SVOp->getOperand(0);
3607 SDValue Op1 = SVOp->getOperand(1);
3609 if (MatchEvenMask) {
3610 // Shift the second operand right to 32 bits.
3611 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3612 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3614 // Shift the first operand left to 32 bits.
3615 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3616 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3618 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3619 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3622 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3623 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3624 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3625 bool HasInt256, bool V2IsSplat = false) {
3626 unsigned NumElts = VT.getVectorNumElements();
3628 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3629 "Unsupported vector type for unpckh");
3631 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3632 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3635 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3636 // independently on 128-bit lanes.
3637 unsigned NumLanes = VT.getSizeInBits()/128;
3638 unsigned NumLaneElts = NumElts/NumLanes;
3640 for (unsigned l = 0; l != NumLanes; ++l) {
3641 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3642 i != (l+1)*NumLaneElts;
3645 int BitI1 = Mask[i+1];
3646 if (!isUndefOrEqual(BitI, j))
3649 if (!isUndefOrEqual(BitI1, NumElts))
3652 if (!isUndefOrEqual(BitI1, j + NumElts))
3661 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3662 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3663 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3664 bool HasInt256, bool V2IsSplat = false) {
3665 unsigned NumElts = VT.getVectorNumElements();
3667 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3668 "Unsupported vector type for unpckh");
3670 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3671 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3674 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3675 // independently on 128-bit lanes.
3676 unsigned NumLanes = VT.getSizeInBits()/128;
3677 unsigned NumLaneElts = NumElts/NumLanes;
3679 for (unsigned l = 0; l != NumLanes; ++l) {
3680 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3681 i != (l+1)*NumLaneElts; i += 2, ++j) {
3683 int BitI1 = Mask[i+1];
3684 if (!isUndefOrEqual(BitI, j))
3687 if (isUndefOrEqual(BitI1, NumElts))
3690 if (!isUndefOrEqual(BitI1, j+NumElts))
3698 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3699 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3701 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3703 unsigned NumElts = VT.getVectorNumElements();
3705 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3706 "Unsupported vector type for unpckh");
3708 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3709 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3712 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3713 // FIXME: Need a better way to get rid of this, there's no latency difference
3714 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3715 // the former later. We should also remove the "_undef" special mask.
3716 if (NumElts == 4 && VT.getSizeInBits() == 256)
3719 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3720 // independently on 128-bit lanes.
3721 unsigned NumLanes = VT.getSizeInBits()/128;
3722 unsigned NumLaneElts = NumElts/NumLanes;
3724 for (unsigned l = 0; l != NumLanes; ++l) {
3725 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3726 i != (l+1)*NumLaneElts;
3729 int BitI1 = Mask[i+1];
3731 if (!isUndefOrEqual(BitI, j))
3733 if (!isUndefOrEqual(BitI1, j))
3741 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3742 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3744 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3745 unsigned NumElts = VT.getVectorNumElements();
3747 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3748 "Unsupported vector type for unpckh");
3750 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3751 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3754 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3755 // independently on 128-bit lanes.
3756 unsigned NumLanes = VT.getSizeInBits()/128;
3757 unsigned NumLaneElts = NumElts/NumLanes;
3759 for (unsigned l = 0; l != NumLanes; ++l) {
3760 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3761 i != (l+1)*NumLaneElts; i += 2, ++j) {
3763 int BitI1 = Mask[i+1];
3764 if (!isUndefOrEqual(BitI, j))
3766 if (!isUndefOrEqual(BitI1, j))
3773 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3774 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3775 /// MOVSD, and MOVD, i.e. setting the lowest element.
3776 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3777 if (VT.getVectorElementType().getSizeInBits() < 32)
3779 if (!VT.is128BitVector())
3782 unsigned NumElts = VT.getVectorNumElements();
3784 if (!isUndefOrEqual(Mask[0], NumElts))
3787 for (unsigned i = 1; i != NumElts; ++i)
3788 if (!isUndefOrEqual(Mask[i], i))
3794 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3795 /// as permutations between 128-bit chunks or halves. As an example: this
3797 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3798 /// The first half comes from the second half of V1 and the second half from the
3799 /// the second half of V2.
3800 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3801 if (!HasFp256 || !VT.is256BitVector())
3804 // The shuffle result is divided into half A and half B. In total the two
3805 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3806 // B must come from C, D, E or F.
3807 unsigned HalfSize = VT.getVectorNumElements()/2;
3808 bool MatchA = false, MatchB = false;
3810 // Check if A comes from one of C, D, E, F.
3811 for (unsigned Half = 0; Half != 4; ++Half) {
3812 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3818 // Check if B comes from one of C, D, E, F.
3819 for (unsigned Half = 0; Half != 4; ++Half) {
3820 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3826 return MatchA && MatchB;
3829 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3830 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3831 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3832 EVT VT = SVOp->getValueType(0);
3834 unsigned HalfSize = VT.getVectorNumElements()/2;
3836 unsigned FstHalf = 0, SndHalf = 0;
3837 for (unsigned i = 0; i < HalfSize; ++i) {
3838 if (SVOp->getMaskElt(i) > 0) {
3839 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3843 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3844 if (SVOp->getMaskElt(i) > 0) {
3845 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3850 return (FstHalf | (SndHalf << 4));
3853 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3854 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3855 /// Note that VPERMIL mask matching is different depending whether theunderlying
3856 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3857 /// to the same elements of the low, but to the higher half of the source.
3858 /// In VPERMILPD the two lanes could be shuffled independently of each other
3859 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3860 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3864 unsigned NumElts = VT.getVectorNumElements();
3865 // Only match 256-bit with 32/64-bit types
3866 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3869 unsigned NumLanes = VT.getSizeInBits()/128;
3870 unsigned LaneSize = NumElts/NumLanes;
3871 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3872 for (unsigned i = 0; i != LaneSize; ++i) {
3873 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3875 if (NumElts != 8 || l == 0)
3877 // VPERMILPS handling
3880 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3888 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3889 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3890 /// element of vector 2 and the other elements to come from vector 1 in order.
3891 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3892 bool V2IsSplat = false, bool V2IsUndef = false) {
3893 if (!VT.is128BitVector())
3896 unsigned NumOps = VT.getVectorNumElements();
3897 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3900 if (!isUndefOrEqual(Mask[0], 0))
3903 for (unsigned i = 1; i != NumOps; ++i)
3904 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3905 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3906 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3912 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3914 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3915 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3916 const X86Subtarget *Subtarget) {
3917 if (!Subtarget->hasSSE3())
3920 unsigned NumElems = VT.getVectorNumElements();
3922 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3923 (VT.getSizeInBits() == 256 && NumElems != 8))
3926 // "i+1" is the value the indexed mask element must have
3927 for (unsigned i = 0; i != NumElems; i += 2)
3928 if (!isUndefOrEqual(Mask[i], i+1) ||
3929 !isUndefOrEqual(Mask[i+1], i+1))
3935 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3937 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3938 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3939 const X86Subtarget *Subtarget) {
3940 if (!Subtarget->hasSSE3())
3943 unsigned NumElems = VT.getVectorNumElements();
3945 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3946 (VT.getSizeInBits() == 256 && NumElems != 8))
3949 // "i" is the value the indexed mask element must have
3950 for (unsigned i = 0; i != NumElems; i += 2)
3951 if (!isUndefOrEqual(Mask[i], i) ||
3952 !isUndefOrEqual(Mask[i+1], i))
3958 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3959 /// specifies a shuffle of elements that is suitable for input to 256-bit
3960 /// version of MOVDDUP.
3961 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3962 if (!HasFp256 || !VT.is256BitVector())
3965 unsigned NumElts = VT.getVectorNumElements();
3969 for (unsigned i = 0; i != NumElts/2; ++i)
3970 if (!isUndefOrEqual(Mask[i], 0))
3972 for (unsigned i = NumElts/2; i != NumElts; ++i)
3973 if (!isUndefOrEqual(Mask[i], NumElts/2))
3978 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3979 /// specifies a shuffle of elements that is suitable for input to 128-bit
3980 /// version of MOVDDUP.
3981 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3982 if (!VT.is128BitVector())
3985 unsigned e = VT.getVectorNumElements() / 2;
3986 for (unsigned i = 0; i != e; ++i)
3987 if (!isUndefOrEqual(Mask[i], i))
3989 for (unsigned i = 0; i != e; ++i)
3990 if (!isUndefOrEqual(Mask[e+i], i))
3995 /// isVEXTRACTF128Index - Return true if the specified
3996 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3997 /// suitable for input to VEXTRACTF128.
3998 bool X86::isVEXTRACTF128Index(SDNode *N) {
3999 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4002 // The index should be aligned on a 128-bit boundary.
4004 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4006 unsigned VL = N->getValueType(0).getVectorNumElements();
4007 unsigned VBits = N->getValueType(0).getSizeInBits();
4008 unsigned ElSize = VBits / VL;
4009 bool Result = (Index * ElSize) % 128 == 0;
4014 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4015 /// operand specifies a subvector insert that is suitable for input to
4017 bool X86::isVINSERTF128Index(SDNode *N) {
4018 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4021 // The index should be aligned on a 128-bit boundary.
4023 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4025 unsigned VL = N->getValueType(0).getVectorNumElements();
4026 unsigned VBits = N->getValueType(0).getSizeInBits();
4027 unsigned ElSize = VBits / VL;
4028 bool Result = (Index * ElSize) % 128 == 0;
4033 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4034 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4035 /// Handles 128-bit and 256-bit.
4036 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4037 EVT VT = N->getValueType(0);
4039 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4040 "Unsupported vector type for PSHUF/SHUFP");
4042 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4043 // independently on 128-bit lanes.
4044 unsigned NumElts = VT.getVectorNumElements();
4045 unsigned NumLanes = VT.getSizeInBits()/128;
4046 unsigned NumLaneElts = NumElts/NumLanes;
4048 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4049 "Only supports 2 or 4 elements per lane");
4051 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4053 for (unsigned i = 0; i != NumElts; ++i) {
4054 int Elt = N->getMaskElt(i);
4055 if (Elt < 0) continue;
4056 Elt &= NumLaneElts - 1;
4057 unsigned ShAmt = (i << Shift) % 8;
4058 Mask |= Elt << ShAmt;
4064 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4065 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4066 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4067 EVT VT = N->getValueType(0);
4069 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4070 "Unsupported vector type for PSHUFHW");
4072 unsigned NumElts = VT.getVectorNumElements();
4075 for (unsigned l = 0; l != NumElts; l += 8) {
4076 // 8 nodes per lane, but we only care about the last 4.
4077 for (unsigned i = 0; i < 4; ++i) {
4078 int Elt = N->getMaskElt(l+i+4);
4079 if (Elt < 0) continue;
4080 Elt &= 0x3; // only 2-bits.
4081 Mask |= Elt << (i * 2);
4088 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4089 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4090 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4091 EVT VT = N->getValueType(0);
4093 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4094 "Unsupported vector type for PSHUFHW");
4096 unsigned NumElts = VT.getVectorNumElements();
4099 for (unsigned l = 0; l != NumElts; l += 8) {
4100 // 8 nodes per lane, but we only care about the first 4.
4101 for (unsigned i = 0; i < 4; ++i) {
4102 int Elt = N->getMaskElt(l+i);
4103 if (Elt < 0) continue;
4104 Elt &= 0x3; // only 2-bits
4105 Mask |= Elt << (i * 2);
4112 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4113 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4114 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4115 EVT VT = SVOp->getValueType(0);
4116 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4118 unsigned NumElts = VT.getVectorNumElements();
4119 unsigned NumLanes = VT.getSizeInBits()/128;
4120 unsigned NumLaneElts = NumElts/NumLanes;
4124 for (i = 0; i != NumElts; ++i) {
4125 Val = SVOp->getMaskElt(i);
4129 if (Val >= (int)NumElts)
4130 Val -= NumElts - NumLaneElts;
4132 assert(Val - i > 0 && "PALIGNR imm should be positive");
4133 return (Val - i) * EltSize;
4136 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4137 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4139 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4140 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4141 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4144 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4146 EVT VecVT = N->getOperand(0).getValueType();
4147 EVT ElVT = VecVT.getVectorElementType();
4149 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4150 return Index / NumElemsPerChunk;
4153 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4154 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4156 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4157 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4158 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4161 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4163 EVT VecVT = N->getValueType(0);
4164 EVT ElVT = VecVT.getVectorElementType();
4166 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4167 return Index / NumElemsPerChunk;
4170 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4171 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4172 /// Handles 256-bit.
4173 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4174 EVT VT = N->getValueType(0);
4176 unsigned NumElts = VT.getVectorNumElements();
4178 assert((VT.is256BitVector() && NumElts == 4) &&
4179 "Unsupported vector type for VPERMQ/VPERMPD");
4182 for (unsigned i = 0; i != NumElts; ++i) {
4183 int Elt = N->getMaskElt(i);
4186 Mask |= Elt << (i*2);
4191 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4193 bool X86::isZeroNode(SDValue Elt) {
4194 return ((isa<ConstantSDNode>(Elt) &&
4195 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4196 (isa<ConstantFPSDNode>(Elt) &&
4197 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4200 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4201 /// their permute mask.
4202 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4203 SelectionDAG &DAG) {
4204 EVT VT = SVOp->getValueType(0);
4205 unsigned NumElems = VT.getVectorNumElements();
4206 SmallVector<int, 8> MaskVec;
4208 for (unsigned i = 0; i != NumElems; ++i) {
4209 int Idx = SVOp->getMaskElt(i);
4211 if (Idx < (int)NumElems)
4216 MaskVec.push_back(Idx);
4218 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4219 SVOp->getOperand(0), &MaskVec[0]);
4222 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4223 /// match movhlps. The lower half elements should come from upper half of
4224 /// V1 (and in order), and the upper half elements should come from the upper
4225 /// half of V2 (and in order).
4226 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4227 if (!VT.is128BitVector())
4229 if (VT.getVectorNumElements() != 4)
4231 for (unsigned i = 0, e = 2; i != e; ++i)
4232 if (!isUndefOrEqual(Mask[i], i+2))
4234 for (unsigned i = 2; i != 4; ++i)
4235 if (!isUndefOrEqual(Mask[i], i+4))
4240 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4241 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4243 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4244 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4246 N = N->getOperand(0).getNode();
4247 if (!ISD::isNON_EXTLoad(N))
4250 *LD = cast<LoadSDNode>(N);
4254 // Test whether the given value is a vector value which will be legalized
4256 static bool WillBeConstantPoolLoad(SDNode *N) {
4257 if (N->getOpcode() != ISD::BUILD_VECTOR)
4260 // Check for any non-constant elements.
4261 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4262 switch (N->getOperand(i).getNode()->getOpcode()) {
4264 case ISD::ConstantFP:
4271 // Vectors of all-zeros and all-ones are materialized with special
4272 // instructions rather than being loaded.
4273 return !ISD::isBuildVectorAllZeros(N) &&
4274 !ISD::isBuildVectorAllOnes(N);
4277 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4278 /// match movlp{s|d}. The lower half elements should come from lower half of
4279 /// V1 (and in order), and the upper half elements should come from the upper
4280 /// half of V2 (and in order). And since V1 will become the source of the
4281 /// MOVLP, it must be either a vector load or a scalar load to vector.
4282 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4283 ArrayRef<int> Mask, EVT VT) {
4284 if (!VT.is128BitVector())
4287 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4289 // Is V2 is a vector load, don't do this transformation. We will try to use
4290 // load folding shufps op.
4291 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4294 unsigned NumElems = VT.getVectorNumElements();
4296 if (NumElems != 2 && NumElems != 4)
4298 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4299 if (!isUndefOrEqual(Mask[i], i))
4301 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4302 if (!isUndefOrEqual(Mask[i], i+NumElems))
4307 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4309 static bool isSplatVector(SDNode *N) {
4310 if (N->getOpcode() != ISD::BUILD_VECTOR)
4313 SDValue SplatValue = N->getOperand(0);
4314 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4315 if (N->getOperand(i) != SplatValue)
4320 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4321 /// to an zero vector.
4322 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4323 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4324 SDValue V1 = N->getOperand(0);
4325 SDValue V2 = N->getOperand(1);
4326 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4327 for (unsigned i = 0; i != NumElems; ++i) {
4328 int Idx = N->getMaskElt(i);
4329 if (Idx >= (int)NumElems) {
4330 unsigned Opc = V2.getOpcode();
4331 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4333 if (Opc != ISD::BUILD_VECTOR ||
4334 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4336 } else if (Idx >= 0) {
4337 unsigned Opc = V1.getOpcode();
4338 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4340 if (Opc != ISD::BUILD_VECTOR ||
4341 !X86::isZeroNode(V1.getOperand(Idx)))
4348 /// getZeroVector - Returns a vector of specified type with all zero elements.
4350 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4351 SelectionDAG &DAG, DebugLoc dl) {
4352 assert(VT.isVector() && "Expected a vector type");
4353 unsigned Size = VT.getSizeInBits();
4355 // Always build SSE zero vectors as <4 x i32> bitcasted
4356 // to their dest type. This ensures they get CSE'd.
4358 if (Size == 128) { // SSE
4359 if (Subtarget->hasSSE2()) { // SSE2
4360 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4361 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4363 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4364 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4366 } else if (Size == 256) { // AVX
4367 if (Subtarget->hasInt256()) { // AVX2
4368 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4369 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4370 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4372 // 256-bit logic and arithmetic instructions in AVX are all
4373 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4374 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4375 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4376 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4379 llvm_unreachable("Unexpected vector type");
4381 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4384 /// getOnesVector - Returns a vector of specified type with all bits set.
4385 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4386 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4387 /// Then bitcast to their original type, ensuring they get CSE'd.
4388 static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG,
4390 assert(VT.isVector() && "Expected a vector type");
4391 unsigned Size = VT.getSizeInBits();
4393 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4396 if (HasInt256) { // AVX2
4397 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4398 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4400 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4401 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4403 } else if (Size == 128) {
4404 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4406 llvm_unreachable("Unexpected vector type");
4408 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4411 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4412 /// that point to V2 points to its first element.
4413 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4414 for (unsigned i = 0; i != NumElems; ++i) {
4415 if (Mask[i] > (int)NumElems) {
4421 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4422 /// operation of specified width.
4423 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4425 unsigned NumElems = VT.getVectorNumElements();
4426 SmallVector<int, 8> Mask;
4427 Mask.push_back(NumElems);
4428 for (unsigned i = 1; i != NumElems; ++i)
4430 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4433 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4434 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4436 unsigned NumElems = VT.getVectorNumElements();
4437 SmallVector<int, 8> Mask;
4438 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4440 Mask.push_back(i + NumElems);
4442 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4445 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4446 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4448 unsigned NumElems = VT.getVectorNumElements();
4449 SmallVector<int, 8> Mask;
4450 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4451 Mask.push_back(i + Half);
4452 Mask.push_back(i + NumElems + Half);
4454 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4457 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4458 // a generic shuffle instruction because the target has no such instructions.
4459 // Generate shuffles which repeat i16 and i8 several times until they can be
4460 // represented by v4f32 and then be manipulated by target suported shuffles.
4461 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4462 EVT VT = V.getValueType();
4463 int NumElems = VT.getVectorNumElements();
4464 DebugLoc dl = V.getDebugLoc();
4466 while (NumElems > 4) {
4467 if (EltNo < NumElems/2) {
4468 V = getUnpackl(DAG, dl, VT, V, V);
4470 V = getUnpackh(DAG, dl, VT, V, V);
4471 EltNo -= NumElems/2;
4478 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4479 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4480 EVT VT = V.getValueType();
4481 DebugLoc dl = V.getDebugLoc();
4482 unsigned Size = VT.getSizeInBits();
4485 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4486 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4487 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4489 } else if (Size == 256) {
4490 // To use VPERMILPS to splat scalars, the second half of indicies must
4491 // refer to the higher part, which is a duplication of the lower one,
4492 // because VPERMILPS can only handle in-lane permutations.
4493 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4494 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4496 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4497 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4500 llvm_unreachable("Vector size not supported");
4502 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4505 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4506 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4507 EVT SrcVT = SV->getValueType(0);
4508 SDValue V1 = SV->getOperand(0);
4509 DebugLoc dl = SV->getDebugLoc();
4511 int EltNo = SV->getSplatIndex();
4512 int NumElems = SrcVT.getVectorNumElements();
4513 unsigned Size = SrcVT.getSizeInBits();
4515 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4516 "Unknown how to promote splat for type");
4518 // Extract the 128-bit part containing the splat element and update
4519 // the splat element index when it refers to the higher register.
4521 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4522 if (EltNo >= NumElems/2)
4523 EltNo -= NumElems/2;
4526 // All i16 and i8 vector types can't be used directly by a generic shuffle
4527 // instruction because the target has no such instruction. Generate shuffles
4528 // which repeat i16 and i8 several times until they fit in i32, and then can
4529 // be manipulated by target suported shuffles.
4530 EVT EltVT = SrcVT.getVectorElementType();
4531 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4532 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4534 // Recreate the 256-bit vector and place the same 128-bit vector
4535 // into the low and high part. This is necessary because we want
4536 // to use VPERM* to shuffle the vectors
4538 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4541 return getLegalSplat(DAG, V1, EltNo);
4544 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4545 /// vector of zero or undef vector. This produces a shuffle where the low
4546 /// element of V2 is swizzled into the zero/undef vector, landing at element
4547 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4548 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4550 const X86Subtarget *Subtarget,
4551 SelectionDAG &DAG) {
4552 EVT VT = V2.getValueType();
4554 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4555 unsigned NumElems = VT.getVectorNumElements();
4556 SmallVector<int, 16> MaskVec;
4557 for (unsigned i = 0; i != NumElems; ++i)
4558 // If this is the insertion idx, put the low elt of V2 here.
4559 MaskVec.push_back(i == Idx ? NumElems : i);
4560 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4563 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4564 /// target specific opcode. Returns true if the Mask could be calculated.
4565 /// Sets IsUnary to true if only uses one source.
4566 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4567 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4568 unsigned NumElems = VT.getVectorNumElements();
4572 switch(N->getOpcode()) {
4574 ImmN = N->getOperand(N->getNumOperands()-1);
4575 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4577 case X86ISD::UNPCKH:
4578 DecodeUNPCKHMask(VT, Mask);
4580 case X86ISD::UNPCKL:
4581 DecodeUNPCKLMask(VT, Mask);
4583 case X86ISD::MOVHLPS:
4584 DecodeMOVHLPSMask(NumElems, Mask);
4586 case X86ISD::MOVLHPS:
4587 DecodeMOVLHPSMask(NumElems, Mask);
4589 case X86ISD::PSHUFD:
4590 case X86ISD::VPERMILP:
4591 ImmN = N->getOperand(N->getNumOperands()-1);
4592 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4595 case X86ISD::PSHUFHW:
4596 ImmN = N->getOperand(N->getNumOperands()-1);
4597 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4600 case X86ISD::PSHUFLW:
4601 ImmN = N->getOperand(N->getNumOperands()-1);
4602 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4605 case X86ISD::VPERMI:
4606 ImmN = N->getOperand(N->getNumOperands()-1);
4607 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4611 case X86ISD::MOVSD: {
4612 // The index 0 always comes from the first element of the second source,
4613 // this is why MOVSS and MOVSD are used in the first place. The other
4614 // elements come from the other positions of the first source vector
4615 Mask.push_back(NumElems);
4616 for (unsigned i = 1; i != NumElems; ++i) {
4621 case X86ISD::VPERM2X128:
4622 ImmN = N->getOperand(N->getNumOperands()-1);
4623 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4624 if (Mask.empty()) return false;
4626 case X86ISD::MOVDDUP:
4627 case X86ISD::MOVLHPD:
4628 case X86ISD::MOVLPD:
4629 case X86ISD::MOVLPS:
4630 case X86ISD::MOVSHDUP:
4631 case X86ISD::MOVSLDUP:
4632 case X86ISD::PALIGN:
4633 // Not yet implemented
4635 default: llvm_unreachable("unknown target shuffle node");
4641 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4642 /// element of the result of the vector shuffle.
4643 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4646 return SDValue(); // Limit search depth.
4648 SDValue V = SDValue(N, 0);
4649 EVT VT = V.getValueType();
4650 unsigned Opcode = V.getOpcode();
4652 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4653 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4654 int Elt = SV->getMaskElt(Index);
4657 return DAG.getUNDEF(VT.getVectorElementType());
4659 unsigned NumElems = VT.getVectorNumElements();
4660 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4661 : SV->getOperand(1);
4662 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4665 // Recurse into target specific vector shuffles to find scalars.
4666 if (isTargetShuffle(Opcode)) {
4667 MVT ShufVT = V.getValueType().getSimpleVT();
4668 unsigned NumElems = ShufVT.getVectorNumElements();
4669 SmallVector<int, 16> ShuffleMask;
4672 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4675 int Elt = ShuffleMask[Index];
4677 return DAG.getUNDEF(ShufVT.getVectorElementType());
4679 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4681 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4685 // Actual nodes that may contain scalar elements
4686 if (Opcode == ISD::BITCAST) {
4687 V = V.getOperand(0);
4688 EVT SrcVT = V.getValueType();
4689 unsigned NumElems = VT.getVectorNumElements();
4691 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4695 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4696 return (Index == 0) ? V.getOperand(0)
4697 : DAG.getUNDEF(VT.getVectorElementType());
4699 if (V.getOpcode() == ISD::BUILD_VECTOR)
4700 return V.getOperand(Index);
4705 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4706 /// shuffle operation which come from a consecutively from a zero. The
4707 /// search can start in two different directions, from left or right.
4709 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4710 bool ZerosFromLeft, SelectionDAG &DAG) {
4712 for (i = 0; i != NumElems; ++i) {
4713 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4714 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4715 if (!(Elt.getNode() &&
4716 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4723 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4724 /// correspond consecutively to elements from one of the vector operands,
4725 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4727 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4728 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4729 unsigned NumElems, unsigned &OpNum) {
4730 bool SeenV1 = false;
4731 bool SeenV2 = false;
4733 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4734 int Idx = SVOp->getMaskElt(i);
4735 // Ignore undef indicies
4739 if (Idx < (int)NumElems)
4744 // Only accept consecutive elements from the same vector
4745 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4749 OpNum = SeenV1 ? 0 : 1;
4753 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4754 /// logical left shift of a vector.
4755 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4756 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4757 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4758 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4759 false /* check zeros from right */, DAG);
4765 // Considering the elements in the mask that are not consecutive zeros,
4766 // check if they consecutively come from only one of the source vectors.
4768 // V1 = {X, A, B, C} 0
4770 // vector_shuffle V1, V2 <1, 2, 3, X>
4772 if (!isShuffleMaskConsecutive(SVOp,
4773 0, // Mask Start Index
4774 NumElems-NumZeros, // Mask End Index(exclusive)
4775 NumZeros, // Where to start looking in the src vector
4776 NumElems, // Number of elements in vector
4777 OpSrc)) // Which source operand ?
4782 ShVal = SVOp->getOperand(OpSrc);
4786 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4787 /// logical left shift of a vector.
4788 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4789 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4790 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4791 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4792 true /* check zeros from left */, DAG);
4798 // Considering the elements in the mask that are not consecutive zeros,
4799 // check if they consecutively come from only one of the source vectors.
4801 // 0 { A, B, X, X } = V2
4803 // vector_shuffle V1, V2 <X, X, 4, 5>
4805 if (!isShuffleMaskConsecutive(SVOp,
4806 NumZeros, // Mask Start Index
4807 NumElems, // Mask End Index(exclusive)
4808 0, // Where to start looking in the src vector
4809 NumElems, // Number of elements in vector
4810 OpSrc)) // Which source operand ?
4815 ShVal = SVOp->getOperand(OpSrc);
4819 /// isVectorShift - Returns true if the shuffle can be implemented as a
4820 /// logical left or right shift of a vector.
4821 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4822 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4823 // Although the logic below support any bitwidth size, there are no
4824 // shift instructions which handle more than 128-bit vectors.
4825 if (!SVOp->getValueType(0).is128BitVector())
4828 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4829 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4835 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4837 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4838 unsigned NumNonZero, unsigned NumZero,
4840 const X86Subtarget* Subtarget,
4841 const TargetLowering &TLI) {
4845 DebugLoc dl = Op.getDebugLoc();
4848 for (unsigned i = 0; i < 16; ++i) {
4849 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4850 if (ThisIsNonZero && First) {
4852 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4854 V = DAG.getUNDEF(MVT::v8i16);
4859 SDValue ThisElt(0, 0), LastElt(0, 0);
4860 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4861 if (LastIsNonZero) {
4862 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4863 MVT::i16, Op.getOperand(i-1));
4865 if (ThisIsNonZero) {
4866 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4867 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4868 ThisElt, DAG.getConstant(8, MVT::i8));
4870 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4874 if (ThisElt.getNode())
4875 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4876 DAG.getIntPtrConstant(i/2));
4880 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4883 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4885 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4886 unsigned NumNonZero, unsigned NumZero,
4888 const X86Subtarget* Subtarget,
4889 const TargetLowering &TLI) {
4893 DebugLoc dl = Op.getDebugLoc();
4896 for (unsigned i = 0; i < 8; ++i) {
4897 bool isNonZero = (NonZeros & (1 << i)) != 0;
4901 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4903 V = DAG.getUNDEF(MVT::v8i16);
4906 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4907 MVT::v8i16, V, Op.getOperand(i),
4908 DAG.getIntPtrConstant(i));
4915 /// getVShift - Return a vector logical shift node.
4917 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4918 unsigned NumBits, SelectionDAG &DAG,
4919 const TargetLowering &TLI, DebugLoc dl) {
4920 assert(VT.is128BitVector() && "Unknown type for VShift");
4921 EVT ShVT = MVT::v2i64;
4922 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4923 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4924 return DAG.getNode(ISD::BITCAST, dl, VT,
4925 DAG.getNode(Opc, dl, ShVT, SrcOp,
4926 DAG.getConstant(NumBits,
4927 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4931 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4932 SelectionDAG &DAG) const {
4934 // Check if the scalar load can be widened into a vector load. And if
4935 // the address is "base + cst" see if the cst can be "absorbed" into
4936 // the shuffle mask.
4937 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4938 SDValue Ptr = LD->getBasePtr();
4939 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4941 EVT PVT = LD->getValueType(0);
4942 if (PVT != MVT::i32 && PVT != MVT::f32)
4947 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4948 FI = FINode->getIndex();
4950 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4951 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4952 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4953 Offset = Ptr.getConstantOperandVal(1);
4954 Ptr = Ptr.getOperand(0);
4959 // FIXME: 256-bit vector instructions don't require a strict alignment,
4960 // improve this code to support it better.
4961 unsigned RequiredAlign = VT.getSizeInBits()/8;
4962 SDValue Chain = LD->getChain();
4963 // Make sure the stack object alignment is at least 16 or 32.
4964 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4965 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4966 if (MFI->isFixedObjectIndex(FI)) {
4967 // Can't change the alignment. FIXME: It's possible to compute
4968 // the exact stack offset and reference FI + adjust offset instead.
4969 // If someone *really* cares about this. That's the way to implement it.
4972 MFI->setObjectAlignment(FI, RequiredAlign);
4976 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4977 // Ptr + (Offset & ~15).
4980 if ((Offset % RequiredAlign) & 3)
4982 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4984 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4985 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4987 int EltNo = (Offset - StartOffset) >> 2;
4988 unsigned NumElems = VT.getVectorNumElements();
4990 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4991 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4992 LD->getPointerInfo().getWithOffset(StartOffset),
4993 false, false, false, 0);
4995 SmallVector<int, 8> Mask;
4996 for (unsigned i = 0; i != NumElems; ++i)
4997 Mask.push_back(EltNo);
4999 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5005 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5006 /// vector of type 'VT', see if the elements can be replaced by a single large
5007 /// load which has the same value as a build_vector whose operands are 'elts'.
5009 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5011 /// FIXME: we'd also like to handle the case where the last elements are zero
5012 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5013 /// There's even a handy isZeroNode for that purpose.
5014 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5015 DebugLoc &DL, SelectionDAG &DAG) {
5016 EVT EltVT = VT.getVectorElementType();
5017 unsigned NumElems = Elts.size();
5019 LoadSDNode *LDBase = NULL;
5020 unsigned LastLoadedElt = -1U;
5022 // For each element in the initializer, see if we've found a load or an undef.
5023 // If we don't find an initial load element, or later load elements are
5024 // non-consecutive, bail out.
5025 for (unsigned i = 0; i < NumElems; ++i) {
5026 SDValue Elt = Elts[i];
5028 if (!Elt.getNode() ||
5029 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5032 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5034 LDBase = cast<LoadSDNode>(Elt.getNode());
5038 if (Elt.getOpcode() == ISD::UNDEF)
5041 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5042 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5047 // If we have found an entire vector of loads and undefs, then return a large
5048 // load of the entire vector width starting at the base pointer. If we found
5049 // consecutive loads for the low half, generate a vzext_load node.
5050 if (LastLoadedElt == NumElems - 1) {
5051 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5052 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5053 LDBase->getPointerInfo(),
5054 LDBase->isVolatile(), LDBase->isNonTemporal(),
5055 LDBase->isInvariant(), 0);
5056 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5057 LDBase->getPointerInfo(),
5058 LDBase->isVolatile(), LDBase->isNonTemporal(),
5059 LDBase->isInvariant(), LDBase->getAlignment());
5061 if (NumElems == 4 && LastLoadedElt == 1 &&
5062 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5063 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5064 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5066 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5067 LDBase->getPointerInfo(),
5068 LDBase->getAlignment(),
5069 false/*isVolatile*/, true/*ReadMem*/,
5072 // Make sure the newly-created LOAD is in the same position as LDBase in
5073 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5074 // update uses of LDBase's output chain to use the TokenFactor.
5075 if (LDBase->hasAnyUseOfValue(1)) {
5076 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5077 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5078 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5079 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5080 SDValue(ResNode.getNode(), 1));
5083 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5088 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5089 /// to generate a splat value for the following cases:
5090 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5091 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5092 /// a scalar load, or a constant.
5093 /// The VBROADCAST node is returned when a pattern is found,
5094 /// or SDValue() otherwise.
5096 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5097 if (!Subtarget->hasFp256())
5100 EVT VT = Op.getValueType();
5101 DebugLoc dl = Op.getDebugLoc();
5103 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5104 "Unsupported vector type for broadcast.");
5109 switch (Op.getOpcode()) {
5111 // Unknown pattern found.
5114 case ISD::BUILD_VECTOR: {
5115 // The BUILD_VECTOR node must be a splat.
5116 if (!isSplatVector(Op.getNode()))
5119 Ld = Op.getOperand(0);
5120 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5121 Ld.getOpcode() == ISD::ConstantFP);
5123 // The suspected load node has several users. Make sure that all
5124 // of its users are from the BUILD_VECTOR node.
5125 // Constants may have multiple users.
5126 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5131 case ISD::VECTOR_SHUFFLE: {
5132 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5134 // Shuffles must have a splat mask where the first element is
5136 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5139 SDValue Sc = Op.getOperand(0);
5140 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5141 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5143 if (!Subtarget->hasInt256())
5146 // Use the register form of the broadcast instruction available on AVX2.
5147 if (VT.is256BitVector())
5148 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5149 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5152 Ld = Sc.getOperand(0);
5153 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5154 Ld.getOpcode() == ISD::ConstantFP);
5156 // The scalar_to_vector node and the suspected
5157 // load node must have exactly one user.
5158 // Constants may have multiple users.
5159 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5165 bool Is256 = VT.is256BitVector();
5167 // Handle the broadcasting a single constant scalar from the constant pool
5168 // into a vector. On Sandybridge it is still better to load a constant vector
5169 // from the constant pool and not to broadcast it from a scalar.
5170 if (ConstSplatVal && Subtarget->hasInt256()) {
5171 EVT CVT = Ld.getValueType();
5172 assert(!CVT.isVector() && "Must not broadcast a vector type");
5173 unsigned ScalarSize = CVT.getSizeInBits();
5175 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5176 const Constant *C = 0;
5177 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5178 C = CI->getConstantIntValue();
5179 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5180 C = CF->getConstantFPValue();
5182 assert(C && "Invalid constant type");
5184 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5185 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5186 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5187 MachinePointerInfo::getConstantPool(),
5188 false, false, false, Alignment);
5190 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5194 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5195 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5197 // Handle AVX2 in-register broadcasts.
5198 if (!IsLoad && Subtarget->hasInt256() &&
5199 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5200 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5202 // The scalar source must be a normal load.
5206 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5207 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5209 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5210 // double since there is no vbroadcastsd xmm
5211 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5212 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5213 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5216 // Unsupported broadcast.
5221 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5222 EVT VT = Op.getValueType();
5224 // Skip if insert_vec_elt is not supported.
5225 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5228 DebugLoc DL = Op.getDebugLoc();
5229 unsigned NumElems = Op.getNumOperands();
5233 SmallVector<unsigned, 4> InsertIndices;
5234 SmallVector<int, 8> Mask(NumElems, -1);
5236 for (unsigned i = 0; i != NumElems; ++i) {
5237 unsigned Opc = Op.getOperand(i).getOpcode();
5239 if (Opc == ISD::UNDEF)
5242 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5243 // Quit if more than 1 elements need inserting.
5244 if (InsertIndices.size() > 1)
5247 InsertIndices.push_back(i);
5251 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5252 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5254 // Quit if extracted from vector of different type.
5255 if (ExtractedFromVec.getValueType() != VT)
5258 // Quit if non-constant index.
5259 if (!isa<ConstantSDNode>(ExtIdx))
5262 if (VecIn1.getNode() == 0)
5263 VecIn1 = ExtractedFromVec;
5264 else if (VecIn1 != ExtractedFromVec) {
5265 if (VecIn2.getNode() == 0)
5266 VecIn2 = ExtractedFromVec;
5267 else if (VecIn2 != ExtractedFromVec)
5268 // Quit if more than 2 vectors to shuffle
5272 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5274 if (ExtractedFromVec == VecIn1)
5276 else if (ExtractedFromVec == VecIn2)
5277 Mask[i] = Idx + NumElems;
5280 if (VecIn1.getNode() == 0)
5283 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5284 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5285 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5286 unsigned Idx = InsertIndices[i];
5287 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5288 DAG.getIntPtrConstant(Idx));
5295 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5296 DebugLoc dl = Op.getDebugLoc();
5298 EVT VT = Op.getValueType();
5299 EVT ExtVT = VT.getVectorElementType();
5300 unsigned NumElems = Op.getNumOperands();
5302 // Vectors containing all zeros can be matched by pxor and xorps later
5303 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5304 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5305 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5306 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5309 return getZeroVector(VT, Subtarget, DAG, dl);
5312 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5313 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5314 // vpcmpeqd on 256-bit vectors.
5315 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5316 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5319 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5322 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5323 if (Broadcast.getNode())
5326 unsigned EVTBits = ExtVT.getSizeInBits();
5328 unsigned NumZero = 0;
5329 unsigned NumNonZero = 0;
5330 unsigned NonZeros = 0;
5331 bool IsAllConstants = true;
5332 SmallSet<SDValue, 8> Values;
5333 for (unsigned i = 0; i < NumElems; ++i) {
5334 SDValue Elt = Op.getOperand(i);
5335 if (Elt.getOpcode() == ISD::UNDEF)
5338 if (Elt.getOpcode() != ISD::Constant &&
5339 Elt.getOpcode() != ISD::ConstantFP)
5340 IsAllConstants = false;
5341 if (X86::isZeroNode(Elt))
5344 NonZeros |= (1 << i);
5349 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5350 if (NumNonZero == 0)
5351 return DAG.getUNDEF(VT);
5353 // Special case for single non-zero, non-undef, element.
5354 if (NumNonZero == 1) {
5355 unsigned Idx = CountTrailingZeros_32(NonZeros);
5356 SDValue Item = Op.getOperand(Idx);
5358 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5359 // the value are obviously zero, truncate the value to i32 and do the
5360 // insertion that way. Only do this if the value is non-constant or if the
5361 // value is a constant being inserted into element 0. It is cheaper to do
5362 // a constant pool load than it is to do a movd + shuffle.
5363 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5364 (!IsAllConstants || Idx == 0)) {
5365 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5367 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5368 EVT VecVT = MVT::v4i32;
5369 unsigned VecElts = 4;
5371 // Truncate the value (which may itself be a constant) to i32, and
5372 // convert it to a vector with movd (S2V+shuffle to zero extend).
5373 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5374 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5375 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5377 // Now we have our 32-bit value zero extended in the low element of
5378 // a vector. If Idx != 0, swizzle it into place.
5380 SmallVector<int, 4> Mask;
5381 Mask.push_back(Idx);
5382 for (unsigned i = 1; i != VecElts; ++i)
5384 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5387 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5391 // If we have a constant or non-constant insertion into the low element of
5392 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5393 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5394 // depending on what the source datatype is.
5397 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5399 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5400 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5401 if (VT.is256BitVector()) {
5402 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5403 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5404 Item, DAG.getIntPtrConstant(0));
5406 assert(VT.is128BitVector() && "Expected an SSE value type!");
5407 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5408 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5409 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5412 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5413 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5414 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5415 if (VT.is256BitVector()) {
5416 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5417 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5419 assert(VT.is128BitVector() && "Expected an SSE value type!");
5420 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5422 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5426 // Is it a vector logical left shift?
5427 if (NumElems == 2 && Idx == 1 &&
5428 X86::isZeroNode(Op.getOperand(0)) &&
5429 !X86::isZeroNode(Op.getOperand(1))) {
5430 unsigned NumBits = VT.getSizeInBits();
5431 return getVShift(true, VT,
5432 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5433 VT, Op.getOperand(1)),
5434 NumBits/2, DAG, *this, dl);
5437 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5440 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5441 // is a non-constant being inserted into an element other than the low one,
5442 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5443 // movd/movss) to move this into the low element, then shuffle it into
5445 if (EVTBits == 32) {
5446 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5448 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5449 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5450 SmallVector<int, 8> MaskVec;
5451 for (unsigned i = 0; i != NumElems; ++i)
5452 MaskVec.push_back(i == Idx ? 0 : 1);
5453 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5457 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5458 if (Values.size() == 1) {
5459 if (EVTBits == 32) {
5460 // Instead of a shuffle like this:
5461 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5462 // Check if it's possible to issue this instead.
5463 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5464 unsigned Idx = CountTrailingZeros_32(NonZeros);
5465 SDValue Item = Op.getOperand(Idx);
5466 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5467 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5472 // A vector full of immediates; various special cases are already
5473 // handled, so this is best done with a single constant-pool load.
5477 // For AVX-length vectors, build the individual 128-bit pieces and use
5478 // shuffles to put them in place.
5479 if (VT.is256BitVector()) {
5480 SmallVector<SDValue, 32> V;
5481 for (unsigned i = 0; i != NumElems; ++i)
5482 V.push_back(Op.getOperand(i));
5484 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5486 // Build both the lower and upper subvector.
5487 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5488 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5491 // Recreate the wider vector with the lower and upper part.
5492 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5495 // Let legalizer expand 2-wide build_vectors.
5496 if (EVTBits == 64) {
5497 if (NumNonZero == 1) {
5498 // One half is zero or undef.
5499 unsigned Idx = CountTrailingZeros_32(NonZeros);
5500 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5501 Op.getOperand(Idx));
5502 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5507 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5508 if (EVTBits == 8 && NumElems == 16) {
5509 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5511 if (V.getNode()) return V;
5514 if (EVTBits == 16 && NumElems == 8) {
5515 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5517 if (V.getNode()) return V;
5520 // If element VT is == 32 bits, turn it into a number of shuffles.
5521 SmallVector<SDValue, 8> V(NumElems);
5522 if (NumElems == 4 && NumZero > 0) {
5523 for (unsigned i = 0; i < 4; ++i) {
5524 bool isZero = !(NonZeros & (1 << i));
5526 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5528 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5531 for (unsigned i = 0; i < 2; ++i) {
5532 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5535 V[i] = V[i*2]; // Must be a zero vector.
5538 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5541 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5544 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5549 bool Reverse1 = (NonZeros & 0x3) == 2;
5550 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5554 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5555 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5557 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5560 if (Values.size() > 1 && VT.is128BitVector()) {
5561 // Check for a build vector of consecutive loads.
5562 for (unsigned i = 0; i < NumElems; ++i)
5563 V[i] = Op.getOperand(i);
5565 // Check for elements which are consecutive loads.
5566 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5570 // Check for a build vector from mostly shuffle plus few inserting.
5571 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5575 // For SSE 4.1, use insertps to put the high elements into the low element.
5576 if (getSubtarget()->hasSSE41()) {
5578 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5579 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5581 Result = DAG.getUNDEF(VT);
5583 for (unsigned i = 1; i < NumElems; ++i) {
5584 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5585 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5586 Op.getOperand(i), DAG.getIntPtrConstant(i));
5591 // Otherwise, expand into a number of unpckl*, start by extending each of
5592 // our (non-undef) elements to the full vector width with the element in the
5593 // bottom slot of the vector (which generates no code for SSE).
5594 for (unsigned i = 0; i < NumElems; ++i) {
5595 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5596 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5598 V[i] = DAG.getUNDEF(VT);
5601 // Next, we iteratively mix elements, e.g. for v4f32:
5602 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5603 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5604 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5605 unsigned EltStride = NumElems >> 1;
5606 while (EltStride != 0) {
5607 for (unsigned i = 0; i < EltStride; ++i) {
5608 // If V[i+EltStride] is undef and this is the first round of mixing,
5609 // then it is safe to just drop this shuffle: V[i] is already in the
5610 // right place, the one element (since it's the first round) being
5611 // inserted as undef can be dropped. This isn't safe for successive
5612 // rounds because they will permute elements within both vectors.
5613 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5614 EltStride == NumElems/2)
5617 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5626 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5627 // to create 256-bit vectors from two other 128-bit ones.
5628 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5629 DebugLoc dl = Op.getDebugLoc();
5630 EVT ResVT = Op.getValueType();
5632 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5634 SDValue V1 = Op.getOperand(0);
5635 SDValue V2 = Op.getOperand(1);
5636 unsigned NumElems = ResVT.getVectorNumElements();
5638 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5641 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5642 assert(Op.getNumOperands() == 2);
5644 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5645 // from two other 128-bit ones.
5646 return LowerAVXCONCAT_VECTORS(Op, DAG);
5649 // Try to lower a shuffle node into a simple blend instruction.
5651 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5652 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5653 SDValue V1 = SVOp->getOperand(0);
5654 SDValue V2 = SVOp->getOperand(1);
5655 DebugLoc dl = SVOp->getDebugLoc();
5656 EVT VT = SVOp->getValueType(0);
5657 EVT EltVT = VT.getVectorElementType();
5658 unsigned NumElems = VT.getVectorNumElements();
5660 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5662 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5665 // Check the mask for BLEND and build the value.
5666 unsigned MaskValue = 0;
5667 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5668 unsigned NumLanes = (NumElems-1)/8 + 1;
5669 unsigned NumElemsInLane = NumElems / NumLanes;
5671 // Blend for v16i16 should be symetric for the both lanes.
5672 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5674 int SndLaneEltIdx = (NumLanes == 2) ?
5675 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5676 int EltIdx = SVOp->getMaskElt(i);
5678 if ((EltIdx == -1 || EltIdx == (int)i) &&
5679 (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5682 if (((unsigned)EltIdx == (i + NumElems)) &&
5683 (SndLaneEltIdx == -1 ||
5684 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5685 MaskValue |= (1<<i);
5690 // Convert i32 vectors to floating point if it is not AVX2.
5691 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5693 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5694 BlendVT = EVT::getVectorVT(*DAG.getContext(),
5695 EVT::getFloatingPointVT(EltVT.getSizeInBits()),
5697 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5698 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5701 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5702 DAG.getConstant(MaskValue, MVT::i32));
5703 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5706 // v8i16 shuffles - Prefer shuffles in the following order:
5707 // 1. [all] pshuflw, pshufhw, optional move
5708 // 2. [ssse3] 1 x pshufb
5709 // 3. [ssse3] 2 x pshufb + 1 x por
5710 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5712 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5713 SelectionDAG &DAG) {
5714 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5715 SDValue V1 = SVOp->getOperand(0);
5716 SDValue V2 = SVOp->getOperand(1);
5717 DebugLoc dl = SVOp->getDebugLoc();
5718 SmallVector<int, 8> MaskVals;
5720 // Determine if more than 1 of the words in each of the low and high quadwords
5721 // of the result come from the same quadword of one of the two inputs. Undef
5722 // mask values count as coming from any quadword, for better codegen.
5723 unsigned LoQuad[] = { 0, 0, 0, 0 };
5724 unsigned HiQuad[] = { 0, 0, 0, 0 };
5725 std::bitset<4> InputQuads;
5726 for (unsigned i = 0; i < 8; ++i) {
5727 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5728 int EltIdx = SVOp->getMaskElt(i);
5729 MaskVals.push_back(EltIdx);
5738 InputQuads.set(EltIdx / 4);
5741 int BestLoQuad = -1;
5742 unsigned MaxQuad = 1;
5743 for (unsigned i = 0; i < 4; ++i) {
5744 if (LoQuad[i] > MaxQuad) {
5746 MaxQuad = LoQuad[i];
5750 int BestHiQuad = -1;
5752 for (unsigned i = 0; i < 4; ++i) {
5753 if (HiQuad[i] > MaxQuad) {
5755 MaxQuad = HiQuad[i];
5759 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5760 // of the two input vectors, shuffle them into one input vector so only a
5761 // single pshufb instruction is necessary. If There are more than 2 input
5762 // quads, disable the next transformation since it does not help SSSE3.
5763 bool V1Used = InputQuads[0] || InputQuads[1];
5764 bool V2Used = InputQuads[2] || InputQuads[3];
5765 if (Subtarget->hasSSSE3()) {
5766 if (InputQuads.count() == 2 && V1Used && V2Used) {
5767 BestLoQuad = InputQuads[0] ? 0 : 1;
5768 BestHiQuad = InputQuads[2] ? 2 : 3;
5770 if (InputQuads.count() > 2) {
5776 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5777 // the shuffle mask. If a quad is scored as -1, that means that it contains
5778 // words from all 4 input quadwords.
5780 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5782 BestLoQuad < 0 ? 0 : BestLoQuad,
5783 BestHiQuad < 0 ? 1 : BestHiQuad
5785 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5786 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5787 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5788 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5790 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5791 // source words for the shuffle, to aid later transformations.
5792 bool AllWordsInNewV = true;
5793 bool InOrder[2] = { true, true };
5794 for (unsigned i = 0; i != 8; ++i) {
5795 int idx = MaskVals[i];
5797 InOrder[i/4] = false;
5798 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5800 AllWordsInNewV = false;
5804 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5805 if (AllWordsInNewV) {
5806 for (int i = 0; i != 8; ++i) {
5807 int idx = MaskVals[i];
5810 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5811 if ((idx != i) && idx < 4)
5813 if ((idx != i) && idx > 3)
5822 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5823 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5824 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5825 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5826 unsigned TargetMask = 0;
5827 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5828 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5829 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5830 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5831 getShufflePSHUFLWImmediate(SVOp);
5832 V1 = NewV.getOperand(0);
5833 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5837 // If we have SSSE3, and all words of the result are from 1 input vector,
5838 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5839 // is present, fall back to case 4.
5840 if (Subtarget->hasSSSE3()) {
5841 SmallVector<SDValue,16> pshufbMask;
5843 // If we have elements from both input vectors, set the high bit of the
5844 // shuffle mask element to zero out elements that come from V2 in the V1
5845 // mask, and elements that come from V1 in the V2 mask, so that the two
5846 // results can be OR'd together.
5847 bool TwoInputs = V1Used && V2Used;
5848 for (unsigned i = 0; i != 8; ++i) {
5849 int EltIdx = MaskVals[i] * 2;
5850 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5851 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5852 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5853 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5855 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5856 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5857 DAG.getNode(ISD::BUILD_VECTOR, dl,
5858 MVT::v16i8, &pshufbMask[0], 16));
5860 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5862 // Calculate the shuffle mask for the second input, shuffle it, and
5863 // OR it with the first shuffled input.
5865 for (unsigned i = 0; i != 8; ++i) {
5866 int EltIdx = MaskVals[i] * 2;
5867 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5868 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5869 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5870 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5872 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5873 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5874 DAG.getNode(ISD::BUILD_VECTOR, dl,
5875 MVT::v16i8, &pshufbMask[0], 16));
5876 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5877 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5880 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5881 // and update MaskVals with new element order.
5882 std::bitset<8> InOrder;
5883 if (BestLoQuad >= 0) {
5884 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5885 for (int i = 0; i != 4; ++i) {
5886 int idx = MaskVals[i];
5889 } else if ((idx / 4) == BestLoQuad) {
5894 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5897 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5898 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5899 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5901 getShufflePSHUFLWImmediate(SVOp), DAG);
5905 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5906 // and update MaskVals with the new element order.
5907 if (BestHiQuad >= 0) {
5908 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5909 for (unsigned i = 4; i != 8; ++i) {
5910 int idx = MaskVals[i];
5913 } else if ((idx / 4) == BestHiQuad) {
5914 MaskV[i] = (idx & 3) + 4;
5918 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5921 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5922 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5923 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5925 getShufflePSHUFHWImmediate(SVOp), DAG);
5929 // In case BestHi & BestLo were both -1, which means each quadword has a word
5930 // from each of the four input quadwords, calculate the InOrder bitvector now
5931 // before falling through to the insert/extract cleanup.
5932 if (BestLoQuad == -1 && BestHiQuad == -1) {
5934 for (int i = 0; i != 8; ++i)
5935 if (MaskVals[i] < 0 || MaskVals[i] == i)
5939 // The other elements are put in the right place using pextrw and pinsrw.
5940 for (unsigned i = 0; i != 8; ++i) {
5943 int EltIdx = MaskVals[i];
5946 SDValue ExtOp = (EltIdx < 8) ?
5947 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5948 DAG.getIntPtrConstant(EltIdx)) :
5949 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5950 DAG.getIntPtrConstant(EltIdx - 8));
5951 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5952 DAG.getIntPtrConstant(i));
5957 // v16i8 shuffles - Prefer shuffles in the following order:
5958 // 1. [ssse3] 1 x pshufb
5959 // 2. [ssse3] 2 x pshufb + 1 x por
5960 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5962 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5964 const X86TargetLowering &TLI) {
5965 SDValue V1 = SVOp->getOperand(0);
5966 SDValue V2 = SVOp->getOperand(1);
5967 DebugLoc dl = SVOp->getDebugLoc();
5968 ArrayRef<int> MaskVals = SVOp->getMask();
5970 // If we have SSSE3, case 1 is generated when all result bytes come from
5971 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5972 // present, fall back to case 3.
5974 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5975 if (TLI.getSubtarget()->hasSSSE3()) {
5976 SmallVector<SDValue,16> pshufbMask;
5978 // If all result elements are from one input vector, then only translate
5979 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5981 // Otherwise, we have elements from both input vectors, and must zero out
5982 // elements that come from V2 in the first mask, and V1 in the second mask
5983 // so that we can OR them together.
5984 for (unsigned i = 0; i != 16; ++i) {
5985 int EltIdx = MaskVals[i];
5986 if (EltIdx < 0 || EltIdx >= 16)
5988 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5990 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5991 DAG.getNode(ISD::BUILD_VECTOR, dl,
5992 MVT::v16i8, &pshufbMask[0], 16));
5994 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5995 // the 2nd operand if it's undefined or zero.
5996 if (V2.getOpcode() == ISD::UNDEF ||
5997 ISD::isBuildVectorAllZeros(V2.getNode()))
6000 // Calculate the shuffle mask for the second input, shuffle it, and
6001 // OR it with the first shuffled input.
6003 for (unsigned i = 0; i != 16; ++i) {
6004 int EltIdx = MaskVals[i];
6005 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6006 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6008 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6009 DAG.getNode(ISD::BUILD_VECTOR, dl,
6010 MVT::v16i8, &pshufbMask[0], 16));
6011 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6014 // No SSSE3 - Calculate in place words and then fix all out of place words
6015 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6016 // the 16 different words that comprise the two doublequadword input vectors.
6017 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6018 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6020 for (int i = 0; i != 8; ++i) {
6021 int Elt0 = MaskVals[i*2];
6022 int Elt1 = MaskVals[i*2+1];
6024 // This word of the result is all undef, skip it.
6025 if (Elt0 < 0 && Elt1 < 0)
6028 // This word of the result is already in the correct place, skip it.
6029 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6032 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6033 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6036 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6037 // using a single extract together, load it and store it.
6038 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6039 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6040 DAG.getIntPtrConstant(Elt1 / 2));
6041 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6042 DAG.getIntPtrConstant(i));
6046 // If Elt1 is defined, extract it from the appropriate source. If the
6047 // source byte is not also odd, shift the extracted word left 8 bits
6048 // otherwise clear the bottom 8 bits if we need to do an or.
6050 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6051 DAG.getIntPtrConstant(Elt1 / 2));
6052 if ((Elt1 & 1) == 0)
6053 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6055 TLI.getShiftAmountTy(InsElt.getValueType())));
6057 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6058 DAG.getConstant(0xFF00, MVT::i16));
6060 // If Elt0 is defined, extract it from the appropriate source. If the
6061 // source byte is not also even, shift the extracted word right 8 bits. If
6062 // Elt1 was also defined, OR the extracted values together before
6063 // inserting them in the result.
6065 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6066 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6067 if ((Elt0 & 1) != 0)
6068 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6070 TLI.getShiftAmountTy(InsElt0.getValueType())));
6072 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6073 DAG.getConstant(0x00FF, MVT::i16));
6074 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6077 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6078 DAG.getIntPtrConstant(i));
6080 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6083 // v32i8 shuffles - Translate to VPSHUFB if possible.
6085 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6086 const X86Subtarget *Subtarget,
6087 SelectionDAG &DAG) {
6088 EVT VT = SVOp->getValueType(0);
6089 SDValue V1 = SVOp->getOperand(0);
6090 SDValue V2 = SVOp->getOperand(1);
6091 DebugLoc dl = SVOp->getDebugLoc();
6092 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6094 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6095 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6096 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6098 // VPSHUFB may be generated if
6099 // (1) one of input vector is undefined or zeroinitializer.
6100 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6101 // And (2) the mask indexes don't cross the 128-bit lane.
6102 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6103 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6106 if (V1IsAllZero && !V2IsAllZero) {
6107 CommuteVectorShuffleMask(MaskVals, 32);
6110 SmallVector<SDValue, 32> pshufbMask;
6111 for (unsigned i = 0; i != 32; i++) {
6112 int EltIdx = MaskVals[i];
6113 if (EltIdx < 0 || EltIdx >= 32)
6116 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6117 // Cross lane is not allowed.
6121 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6123 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6124 DAG.getNode(ISD::BUILD_VECTOR, dl,
6125 MVT::v32i8, &pshufbMask[0], 32));
6128 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6129 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6130 /// done when every pair / quad of shuffle mask elements point to elements in
6131 /// the right sequence. e.g.
6132 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6134 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6135 SelectionDAG &DAG, DebugLoc dl) {
6136 MVT VT = SVOp->getValueType(0).getSimpleVT();
6137 unsigned NumElems = VT.getVectorNumElements();
6140 switch (VT.SimpleTy) {
6141 default: llvm_unreachable("Unexpected!");
6142 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6143 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6144 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6145 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6146 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6147 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6150 SmallVector<int, 8> MaskVec;
6151 for (unsigned i = 0; i != NumElems; i += Scale) {
6153 for (unsigned j = 0; j != Scale; ++j) {
6154 int EltIdx = SVOp->getMaskElt(i+j);
6158 StartIdx = (EltIdx / Scale);
6159 if (EltIdx != (int)(StartIdx*Scale + j))
6162 MaskVec.push_back(StartIdx);
6165 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6166 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6167 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6170 /// getVZextMovL - Return a zero-extending vector move low node.
6172 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6173 SDValue SrcOp, SelectionDAG &DAG,
6174 const X86Subtarget *Subtarget, DebugLoc dl) {
6175 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6176 LoadSDNode *LD = NULL;
6177 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6178 LD = dyn_cast<LoadSDNode>(SrcOp);
6180 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6182 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6183 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6184 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6185 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6186 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6188 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6189 return DAG.getNode(ISD::BITCAST, dl, VT,
6190 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6191 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6199 return DAG.getNode(ISD::BITCAST, dl, VT,
6200 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6201 DAG.getNode(ISD::BITCAST, dl,
6205 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6206 /// which could not be matched by any known target speficic shuffle
6208 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6210 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6211 if (NewOp.getNode())
6214 EVT VT = SVOp->getValueType(0);
6216 unsigned NumElems = VT.getVectorNumElements();
6217 unsigned NumLaneElems = NumElems / 2;
6219 DebugLoc dl = SVOp->getDebugLoc();
6220 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6221 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6224 SmallVector<int, 16> Mask;
6225 for (unsigned l = 0; l < 2; ++l) {
6226 // Build a shuffle mask for the output, discovering on the fly which
6227 // input vectors to use as shuffle operands (recorded in InputUsed).
6228 // If building a suitable shuffle vector proves too hard, then bail
6229 // out with UseBuildVector set.
6230 bool UseBuildVector = false;
6231 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6232 unsigned LaneStart = l * NumLaneElems;
6233 for (unsigned i = 0; i != NumLaneElems; ++i) {
6234 // The mask element. This indexes into the input.
6235 int Idx = SVOp->getMaskElt(i+LaneStart);
6237 // the mask element does not index into any input vector.
6242 // The input vector this mask element indexes into.
6243 int Input = Idx / NumLaneElems;
6245 // Turn the index into an offset from the start of the input vector.
6246 Idx -= Input * NumLaneElems;
6248 // Find or create a shuffle vector operand to hold this input.
6250 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6251 if (InputUsed[OpNo] == Input)
6252 // This input vector is already an operand.
6254 if (InputUsed[OpNo] < 0) {
6255 // Create a new operand for this input vector.
6256 InputUsed[OpNo] = Input;
6261 if (OpNo >= array_lengthof(InputUsed)) {
6262 // More than two input vectors used! Give up on trying to create a
6263 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6264 UseBuildVector = true;
6268 // Add the mask index for the new shuffle vector.
6269 Mask.push_back(Idx + OpNo * NumLaneElems);
6272 if (UseBuildVector) {
6273 SmallVector<SDValue, 16> SVOps;
6274 for (unsigned i = 0; i != NumLaneElems; ++i) {
6275 // The mask element. This indexes into the input.
6276 int Idx = SVOp->getMaskElt(i+LaneStart);
6278 SVOps.push_back(DAG.getUNDEF(EltVT));
6282 // The input vector this mask element indexes into.
6283 int Input = Idx / NumElems;
6285 // Turn the index into an offset from the start of the input vector.
6286 Idx -= Input * NumElems;
6288 // Extract the vector element by hand.
6289 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6290 SVOp->getOperand(Input),
6291 DAG.getIntPtrConstant(Idx)));
6294 // Construct the output using a BUILD_VECTOR.
6295 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6297 } else if (InputUsed[0] < 0) {
6298 // No input vectors were used! The result is undefined.
6299 Output[l] = DAG.getUNDEF(NVT);
6301 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6302 (InputUsed[0] % 2) * NumLaneElems,
6304 // If only one input was used, use an undefined vector for the other.
6305 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6306 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6307 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6308 // At least one input vector was used. Create a new shuffle vector.
6309 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6315 // Concatenate the result back
6316 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6319 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6320 /// 4 elements, and match them with several different shuffle types.
6322 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6323 SDValue V1 = SVOp->getOperand(0);
6324 SDValue V2 = SVOp->getOperand(1);
6325 DebugLoc dl = SVOp->getDebugLoc();
6326 EVT VT = SVOp->getValueType(0);
6328 assert(VT.is128BitVector() && "Unsupported vector size");
6330 std::pair<int, int> Locs[4];
6331 int Mask1[] = { -1, -1, -1, -1 };
6332 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6336 for (unsigned i = 0; i != 4; ++i) {
6337 int Idx = PermMask[i];
6339 Locs[i] = std::make_pair(-1, -1);
6341 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6343 Locs[i] = std::make_pair(0, NumLo);
6347 Locs[i] = std::make_pair(1, NumHi);
6349 Mask1[2+NumHi] = Idx;
6355 if (NumLo <= 2 && NumHi <= 2) {
6356 // If no more than two elements come from either vector. This can be
6357 // implemented with two shuffles. First shuffle gather the elements.
6358 // The second shuffle, which takes the first shuffle as both of its
6359 // vector operands, put the elements into the right order.
6360 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6362 int Mask2[] = { -1, -1, -1, -1 };
6364 for (unsigned i = 0; i != 4; ++i)
6365 if (Locs[i].first != -1) {
6366 unsigned Idx = (i < 2) ? 0 : 4;
6367 Idx += Locs[i].first * 2 + Locs[i].second;
6371 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6374 if (NumLo == 3 || NumHi == 3) {
6375 // Otherwise, we must have three elements from one vector, call it X, and
6376 // one element from the other, call it Y. First, use a shufps to build an
6377 // intermediate vector with the one element from Y and the element from X
6378 // that will be in the same half in the final destination (the indexes don't
6379 // matter). Then, use a shufps to build the final vector, taking the half
6380 // containing the element from Y from the intermediate, and the other half
6383 // Normalize it so the 3 elements come from V1.
6384 CommuteVectorShuffleMask(PermMask, 4);
6388 // Find the element from V2.
6390 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6391 int Val = PermMask[HiIndex];
6398 Mask1[0] = PermMask[HiIndex];
6400 Mask1[2] = PermMask[HiIndex^1];
6402 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6405 Mask1[0] = PermMask[0];
6406 Mask1[1] = PermMask[1];
6407 Mask1[2] = HiIndex & 1 ? 6 : 4;
6408 Mask1[3] = HiIndex & 1 ? 4 : 6;
6409 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6412 Mask1[0] = HiIndex & 1 ? 2 : 0;
6413 Mask1[1] = HiIndex & 1 ? 0 : 2;
6414 Mask1[2] = PermMask[2];
6415 Mask1[3] = PermMask[3];
6420 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6423 // Break it into (shuffle shuffle_hi, shuffle_lo).
6424 int LoMask[] = { -1, -1, -1, -1 };
6425 int HiMask[] = { -1, -1, -1, -1 };
6427 int *MaskPtr = LoMask;
6428 unsigned MaskIdx = 0;
6431 for (unsigned i = 0; i != 4; ++i) {
6438 int Idx = PermMask[i];
6440 Locs[i] = std::make_pair(-1, -1);
6441 } else if (Idx < 4) {
6442 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6443 MaskPtr[LoIdx] = Idx;
6446 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6447 MaskPtr[HiIdx] = Idx;
6452 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6453 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6454 int MaskOps[] = { -1, -1, -1, -1 };
6455 for (unsigned i = 0; i != 4; ++i)
6456 if (Locs[i].first != -1)
6457 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6458 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6461 static bool MayFoldVectorLoad(SDValue V) {
6462 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6463 V = V.getOperand(0);
6465 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6466 V = V.getOperand(0);
6467 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6468 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6469 // BUILD_VECTOR (load), undef
6470 V = V.getOperand(0);
6472 return MayFoldLoad(V);
6476 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6477 EVT VT = Op.getValueType();
6479 // Canonizalize to v2f64.
6480 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6481 return DAG.getNode(ISD::BITCAST, dl, VT,
6482 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6487 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6489 SDValue V1 = Op.getOperand(0);
6490 SDValue V2 = Op.getOperand(1);
6491 EVT VT = Op.getValueType();
6493 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6495 if (HasSSE2 && VT == MVT::v2f64)
6496 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6498 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6499 return DAG.getNode(ISD::BITCAST, dl, VT,
6500 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6501 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6502 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6506 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6507 SDValue V1 = Op.getOperand(0);
6508 SDValue V2 = Op.getOperand(1);
6509 EVT VT = Op.getValueType();
6511 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6512 "unsupported shuffle type");
6514 if (V2.getOpcode() == ISD::UNDEF)
6518 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6522 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6523 SDValue V1 = Op.getOperand(0);
6524 SDValue V2 = Op.getOperand(1);
6525 EVT VT = Op.getValueType();
6526 unsigned NumElems = VT.getVectorNumElements();
6528 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6529 // operand of these instructions is only memory, so check if there's a
6530 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6532 bool CanFoldLoad = false;
6534 // Trivial case, when V2 comes from a load.
6535 if (MayFoldVectorLoad(V2))
6538 // When V1 is a load, it can be folded later into a store in isel, example:
6539 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6541 // (MOVLPSmr addr:$src1, VR128:$src2)
6542 // So, recognize this potential and also use MOVLPS or MOVLPD
6543 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6546 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6548 if (HasSSE2 && NumElems == 2)
6549 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6552 // If we don't care about the second element, proceed to use movss.
6553 if (SVOp->getMaskElt(1) != -1)
6554 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6557 // movl and movlp will both match v2i64, but v2i64 is never matched by
6558 // movl earlier because we make it strict to avoid messing with the movlp load
6559 // folding logic (see the code above getMOVLP call). Match it here then,
6560 // this is horrible, but will stay like this until we move all shuffle
6561 // matching to x86 specific nodes. Note that for the 1st condition all
6562 // types are matched with movsd.
6564 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6565 // as to remove this logic from here, as much as possible
6566 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6567 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6568 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6571 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6573 // Invert the operand order and use SHUFPS to match it.
6574 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6575 getShuffleSHUFImmediate(SVOp), DAG);
6578 // Reduce a vector shuffle to zext.
6580 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6581 // PMOVZX is only available from SSE41.
6582 if (!Subtarget->hasSSE41())
6585 EVT VT = Op.getValueType();
6587 // Only AVX2 support 256-bit vector integer extending.
6588 if (!Subtarget->hasInt256() && VT.is256BitVector())
6591 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6592 DebugLoc DL = Op.getDebugLoc();
6593 SDValue V1 = Op.getOperand(0);
6594 SDValue V2 = Op.getOperand(1);
6595 unsigned NumElems = VT.getVectorNumElements();
6597 // Extending is an unary operation and the element type of the source vector
6598 // won't be equal to or larger than i64.
6599 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6600 VT.getVectorElementType() == MVT::i64)
6603 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6604 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6605 while ((1U << Shift) < NumElems) {
6606 if (SVOp->getMaskElt(1U << Shift) == 1)
6609 // The maximal ratio is 8, i.e. from i8 to i64.
6614 // Check the shuffle mask.
6615 unsigned Mask = (1U << Shift) - 1;
6616 for (unsigned i = 0; i != NumElems; ++i) {
6617 int EltIdx = SVOp->getMaskElt(i);
6618 if ((i & Mask) != 0 && EltIdx != -1)
6620 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6624 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6625 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6626 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6628 if (!isTypeLegal(NVT))
6631 // Simplify the operand as it's prepared to be fed into shuffle.
6632 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6633 if (V1.getOpcode() == ISD::BITCAST &&
6634 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6635 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6637 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6638 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6639 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6640 ConstantSDNode *CIdx =
6641 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6642 // If it's foldable, i.e. normal load with single use, we will let code
6643 // selection to fold it. Otherwise, we will short the conversion sequence.
6644 if (CIdx && CIdx->getZExtValue() == 0 &&
6645 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6646 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6649 return DAG.getNode(ISD::BITCAST, DL, VT,
6650 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6654 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6655 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6656 EVT VT = Op.getValueType();
6657 DebugLoc dl = Op.getDebugLoc();
6658 SDValue V1 = Op.getOperand(0);
6659 SDValue V2 = Op.getOperand(1);
6661 if (isZeroShuffle(SVOp))
6662 return getZeroVector(VT, Subtarget, DAG, dl);
6664 // Handle splat operations
6665 if (SVOp->isSplat()) {
6666 unsigned NumElem = VT.getVectorNumElements();
6667 int Size = VT.getSizeInBits();
6669 // Use vbroadcast whenever the splat comes from a foldable load
6670 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6671 if (Broadcast.getNode())
6674 // Handle splats by matching through known shuffle masks
6675 if ((Size == 128 && NumElem <= 4) ||
6676 (Size == 256 && NumElem <= 8))
6679 // All remaning splats are promoted to target supported vector shuffles.
6680 return PromoteSplat(SVOp, DAG);
6683 // Check integer expanding shuffles.
6684 SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6685 if (NewOp.getNode())
6688 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6690 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6691 VT == MVT::v16i16 || VT == MVT::v32i8) {
6692 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6693 if (NewOp.getNode())
6694 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6695 } else if ((VT == MVT::v4i32 ||
6696 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6697 // FIXME: Figure out a cleaner way to do this.
6698 // Try to make use of movq to zero out the top part.
6699 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6700 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6701 if (NewOp.getNode()) {
6702 EVT NewVT = NewOp.getValueType();
6703 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6704 NewVT, true, false))
6705 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6706 DAG, Subtarget, dl);
6708 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6709 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6710 if (NewOp.getNode()) {
6711 EVT NewVT = NewOp.getValueType();
6712 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6713 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6714 DAG, Subtarget, dl);
6722 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6723 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6724 SDValue V1 = Op.getOperand(0);
6725 SDValue V2 = Op.getOperand(1);
6726 EVT VT = Op.getValueType();
6727 DebugLoc dl = Op.getDebugLoc();
6728 unsigned NumElems = VT.getVectorNumElements();
6729 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6730 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6731 bool V1IsSplat = false;
6732 bool V2IsSplat = false;
6733 bool HasSSE2 = Subtarget->hasSSE2();
6734 bool HasFp256 = Subtarget->hasFp256();
6735 bool HasInt256 = Subtarget->hasInt256();
6736 MachineFunction &MF = DAG.getMachineFunction();
6737 bool OptForSize = MF.getFunction()->getFnAttributes().
6738 hasAttribute(Attribute::OptimizeForSize);
6740 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6742 if (V1IsUndef && V2IsUndef)
6743 return DAG.getUNDEF(VT);
6745 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6747 // Vector shuffle lowering takes 3 steps:
6749 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6750 // narrowing and commutation of operands should be handled.
6751 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6753 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6754 // so the shuffle can be broken into other shuffles and the legalizer can
6755 // try the lowering again.
6757 // The general idea is that no vector_shuffle operation should be left to
6758 // be matched during isel, all of them must be converted to a target specific
6761 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6762 // narrowing and commutation of operands should be handled. The actual code
6763 // doesn't include all of those, work in progress...
6764 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6765 if (NewOp.getNode())
6768 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6770 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6771 // unpckh_undef). Only use pshufd if speed is more important than size.
6772 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6773 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6774 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6775 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6777 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6778 V2IsUndef && MayFoldVectorLoad(V1))
6779 return getMOVDDup(Op, dl, V1, DAG);
6781 if (isMOVHLPS_v_undef_Mask(M, VT))
6782 return getMOVHighToLow(Op, dl, DAG);
6784 // Use to match splats
6785 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6786 (VT == MVT::v2f64 || VT == MVT::v2i64))
6787 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6789 if (isPSHUFDMask(M, VT)) {
6790 // The actual implementation will match the mask in the if above and then
6791 // during isel it can match several different instructions, not only pshufd
6792 // as its name says, sad but true, emulate the behavior for now...
6793 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6794 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6796 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6798 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6799 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6801 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6802 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6805 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6809 // Check if this can be converted into a logical shift.
6810 bool isLeft = false;
6813 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6814 if (isShift && ShVal.hasOneUse()) {
6815 // If the shifted value has multiple uses, it may be cheaper to use
6816 // v_set0 + movlhps or movhlps, etc.
6817 EVT EltVT = VT.getVectorElementType();
6818 ShAmt *= EltVT.getSizeInBits();
6819 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6822 if (isMOVLMask(M, VT)) {
6823 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6824 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6825 if (!isMOVLPMask(M, VT)) {
6826 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6827 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6829 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6830 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6834 // FIXME: fold these into legal mask.
6835 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6836 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6838 if (isMOVHLPSMask(M, VT))
6839 return getMOVHighToLow(Op, dl, DAG);
6841 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6842 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6844 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6845 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6847 if (isMOVLPMask(M, VT))
6848 return getMOVLP(Op, dl, DAG, HasSSE2);
6850 if (ShouldXformToMOVHLPS(M, VT) ||
6851 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6852 return CommuteVectorShuffle(SVOp, DAG);
6855 // No better options. Use a vshldq / vsrldq.
6856 EVT EltVT = VT.getVectorElementType();
6857 ShAmt *= EltVT.getSizeInBits();
6858 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6861 bool Commuted = false;
6862 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6863 // 1,1,1,1 -> v8i16 though.
6864 V1IsSplat = isSplatVector(V1.getNode());
6865 V2IsSplat = isSplatVector(V2.getNode());
6867 // Canonicalize the splat or undef, if present, to be on the RHS.
6868 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6869 CommuteVectorShuffleMask(M, NumElems);
6871 std::swap(V1IsSplat, V2IsSplat);
6875 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6876 // Shuffling low element of v1 into undef, just return v1.
6879 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6880 // the instruction selector will not match, so get a canonical MOVL with
6881 // swapped operands to undo the commute.
6882 return getMOVL(DAG, dl, VT, V2, V1);
6885 if (isUNPCKLMask(M, VT, HasInt256))
6886 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6888 if (isUNPCKHMask(M, VT, HasInt256))
6889 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6892 // Normalize mask so all entries that point to V2 points to its first
6893 // element then try to match unpck{h|l} again. If match, return a
6894 // new vector_shuffle with the corrected mask.p
6895 SmallVector<int, 8> NewMask(M.begin(), M.end());
6896 NormalizeMask(NewMask, NumElems);
6897 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6898 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6899 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6900 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6904 // Commute is back and try unpck* again.
6905 // FIXME: this seems wrong.
6906 CommuteVectorShuffleMask(M, NumElems);
6908 std::swap(V1IsSplat, V2IsSplat);
6911 if (isUNPCKLMask(M, VT, HasInt256))
6912 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6914 if (isUNPCKHMask(M, VT, HasInt256))
6915 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6918 // Normalize the node to match x86 shuffle ops if needed
6919 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6920 return CommuteVectorShuffle(SVOp, DAG);
6922 // The checks below are all present in isShuffleMaskLegal, but they are
6923 // inlined here right now to enable us to directly emit target specific
6924 // nodes, and remove one by one until they don't return Op anymore.
6926 if (isPALIGNRMask(M, VT, Subtarget))
6927 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6928 getShufflePALIGNRImmediate(SVOp),
6931 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6932 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6933 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6934 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6937 if (isPSHUFHWMask(M, VT, HasInt256))
6938 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6939 getShufflePSHUFHWImmediate(SVOp),
6942 if (isPSHUFLWMask(M, VT, HasInt256))
6943 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6944 getShufflePSHUFLWImmediate(SVOp),
6947 if (isSHUFPMask(M, VT, HasFp256))
6948 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6949 getShuffleSHUFImmediate(SVOp), DAG);
6951 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6952 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6953 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6954 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6956 //===--------------------------------------------------------------------===//
6957 // Generate target specific nodes for 128 or 256-bit shuffles only
6958 // supported in the AVX instruction set.
6961 // Handle VMOVDDUPY permutations
6962 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6963 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6965 // Handle VPERMILPS/D* permutations
6966 if (isVPERMILPMask(M, VT, HasFp256)) {
6967 if (HasInt256 && VT == MVT::v8i32)
6968 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6969 getShuffleSHUFImmediate(SVOp), DAG);
6970 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6971 getShuffleSHUFImmediate(SVOp), DAG);
6974 // Handle VPERM2F128/VPERM2I128 permutations
6975 if (isVPERM2X128Mask(M, VT, HasFp256))
6976 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6977 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6979 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6980 if (BlendOp.getNode())
6983 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6984 SmallVector<SDValue, 8> permclMask;
6985 for (unsigned i = 0; i != 8; ++i) {
6986 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6988 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6990 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6991 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6992 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6995 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6996 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6997 getShuffleCLImmediate(SVOp), DAG);
6999 //===--------------------------------------------------------------------===//
7000 // Since no target specific shuffle was selected for this generic one,
7001 // lower it into other known shuffles. FIXME: this isn't true yet, but
7002 // this is the plan.
7005 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7006 if (VT == MVT::v8i16) {
7007 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7008 if (NewOp.getNode())
7012 if (VT == MVT::v16i8) {
7013 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7014 if (NewOp.getNode())
7018 if (VT == MVT::v32i8) {
7019 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7020 if (NewOp.getNode())
7024 // Handle all 128-bit wide vectors with 4 elements, and match them with
7025 // several different shuffle types.
7026 if (NumElems == 4 && VT.is128BitVector())
7027 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7029 // Handle general 256-bit shuffles
7030 if (VT.is256BitVector())
7031 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7037 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7038 SelectionDAG &DAG) const {
7039 EVT VT = Op.getValueType();
7040 DebugLoc dl = Op.getDebugLoc();
7042 if (!Op.getOperand(0).getValueType().is128BitVector())
7045 if (VT.getSizeInBits() == 8) {
7046 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7047 Op.getOperand(0), Op.getOperand(1));
7048 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7049 DAG.getValueType(VT));
7050 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7053 if (VT.getSizeInBits() == 16) {
7054 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7055 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7057 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7058 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7059 DAG.getNode(ISD::BITCAST, dl,
7063 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7064 Op.getOperand(0), Op.getOperand(1));
7065 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7066 DAG.getValueType(VT));
7067 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7070 if (VT == MVT::f32) {
7071 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7072 // the result back to FR32 register. It's only worth matching if the
7073 // result has a single use which is a store or a bitcast to i32. And in
7074 // the case of a store, it's not worth it if the index is a constant 0,
7075 // because a MOVSSmr can be used instead, which is smaller and faster.
7076 if (!Op.hasOneUse())
7078 SDNode *User = *Op.getNode()->use_begin();
7079 if ((User->getOpcode() != ISD::STORE ||
7080 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7081 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7082 (User->getOpcode() != ISD::BITCAST ||
7083 User->getValueType(0) != MVT::i32))
7085 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7086 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7089 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7092 if (VT == MVT::i32 || VT == MVT::i64) {
7093 // ExtractPS/pextrq works with constant index.
7094 if (isa<ConstantSDNode>(Op.getOperand(1)))
7101 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7102 SelectionDAG &DAG) const {
7103 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7106 SDValue Vec = Op.getOperand(0);
7107 EVT VecVT = Vec.getValueType();
7109 // If this is a 256-bit vector result, first extract the 128-bit vector and
7110 // then extract the element from the 128-bit vector.
7111 if (VecVT.is256BitVector()) {
7112 DebugLoc dl = Op.getNode()->getDebugLoc();
7113 unsigned NumElems = VecVT.getVectorNumElements();
7114 SDValue Idx = Op.getOperand(1);
7115 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7117 // Get the 128-bit vector.
7118 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7120 if (IdxVal >= NumElems/2)
7121 IdxVal -= NumElems/2;
7122 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7123 DAG.getConstant(IdxVal, MVT::i32));
7126 assert(VecVT.is128BitVector() && "Unexpected vector length");
7128 if (Subtarget->hasSSE41()) {
7129 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7134 EVT VT = Op.getValueType();
7135 DebugLoc dl = Op.getDebugLoc();
7136 // TODO: handle v16i8.
7137 if (VT.getSizeInBits() == 16) {
7138 SDValue Vec = Op.getOperand(0);
7139 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7141 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7142 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7143 DAG.getNode(ISD::BITCAST, dl,
7146 // Transform it so it match pextrw which produces a 32-bit result.
7147 EVT EltVT = MVT::i32;
7148 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7149 Op.getOperand(0), Op.getOperand(1));
7150 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7151 DAG.getValueType(VT));
7152 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7155 if (VT.getSizeInBits() == 32) {
7156 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7160 // SHUFPS the element to the lowest double word, then movss.
7161 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7162 EVT VVT = Op.getOperand(0).getValueType();
7163 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7164 DAG.getUNDEF(VVT), Mask);
7165 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7166 DAG.getIntPtrConstant(0));
7169 if (VT.getSizeInBits() == 64) {
7170 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7171 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7172 // to match extract_elt for f64.
7173 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7177 // UNPCKHPD the element to the lowest double word, then movsd.
7178 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7179 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7180 int Mask[2] = { 1, -1 };
7181 EVT VVT = Op.getOperand(0).getValueType();
7182 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7183 DAG.getUNDEF(VVT), Mask);
7184 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7185 DAG.getIntPtrConstant(0));
7192 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7193 SelectionDAG &DAG) const {
7194 EVT VT = Op.getValueType();
7195 EVT EltVT = VT.getVectorElementType();
7196 DebugLoc dl = Op.getDebugLoc();
7198 SDValue N0 = Op.getOperand(0);
7199 SDValue N1 = Op.getOperand(1);
7200 SDValue N2 = Op.getOperand(2);
7202 if (!VT.is128BitVector())
7205 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7206 isa<ConstantSDNode>(N2)) {
7208 if (VT == MVT::v8i16)
7209 Opc = X86ISD::PINSRW;
7210 else if (VT == MVT::v16i8)
7211 Opc = X86ISD::PINSRB;
7213 Opc = X86ISD::PINSRB;
7215 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7217 if (N1.getValueType() != MVT::i32)
7218 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7219 if (N2.getValueType() != MVT::i32)
7220 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7221 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7224 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7225 // Bits [7:6] of the constant are the source select. This will always be
7226 // zero here. The DAG Combiner may combine an extract_elt index into these
7227 // bits. For example (insert (extract, 3), 2) could be matched by putting
7228 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7229 // Bits [5:4] of the constant are the destination select. This is the
7230 // value of the incoming immediate.
7231 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7232 // combine either bitwise AND or insert of float 0.0 to set these bits.
7233 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7234 // Create this as a scalar to vector..
7235 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7236 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7239 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7240 // PINSR* works with constant index.
7247 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7248 EVT VT = Op.getValueType();
7249 EVT EltVT = VT.getVectorElementType();
7251 DebugLoc dl = Op.getDebugLoc();
7252 SDValue N0 = Op.getOperand(0);
7253 SDValue N1 = Op.getOperand(1);
7254 SDValue N2 = Op.getOperand(2);
7256 // If this is a 256-bit vector result, first extract the 128-bit vector,
7257 // insert the element into the extracted half and then place it back.
7258 if (VT.is256BitVector()) {
7259 if (!isa<ConstantSDNode>(N2))
7262 // Get the desired 128-bit vector half.
7263 unsigned NumElems = VT.getVectorNumElements();
7264 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7265 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7267 // Insert the element into the desired half.
7268 bool Upper = IdxVal >= NumElems/2;
7269 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7270 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7272 // Insert the changed part back to the 256-bit vector
7273 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7276 if (Subtarget->hasSSE41())
7277 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7279 if (EltVT == MVT::i8)
7282 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7283 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7284 // as its second argument.
7285 if (N1.getValueType() != MVT::i32)
7286 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7287 if (N2.getValueType() != MVT::i32)
7288 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7289 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7294 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7295 LLVMContext *Context = DAG.getContext();
7296 DebugLoc dl = Op.getDebugLoc();
7297 EVT OpVT = Op.getValueType();
7299 // If this is a 256-bit vector result, first insert into a 128-bit
7300 // vector and then insert into the 256-bit vector.
7301 if (!OpVT.is128BitVector()) {
7302 // Insert into a 128-bit vector.
7303 EVT VT128 = EVT::getVectorVT(*Context,
7304 OpVT.getVectorElementType(),
7305 OpVT.getVectorNumElements() / 2);
7307 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7309 // Insert the 128-bit vector.
7310 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7313 if (OpVT == MVT::v1i64 &&
7314 Op.getOperand(0).getValueType() == MVT::i64)
7315 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7317 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7318 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7319 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7320 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7323 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7324 // a simple subregister reference or explicit instructions to grab
7325 // upper bits of a vector.
7326 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7327 SelectionDAG &DAG) {
7328 if (Subtarget->hasFp256()) {
7329 DebugLoc dl = Op.getNode()->getDebugLoc();
7330 SDValue Vec = Op.getNode()->getOperand(0);
7331 SDValue Idx = Op.getNode()->getOperand(1);
7333 if (Op.getNode()->getValueType(0).is128BitVector() &&
7334 Vec.getNode()->getValueType(0).is256BitVector() &&
7335 isa<ConstantSDNode>(Idx)) {
7336 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7337 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7343 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7344 // simple superregister reference or explicit instructions to insert
7345 // the upper bits of a vector.
7346 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7347 SelectionDAG &DAG) {
7348 if (Subtarget->hasFp256()) {
7349 DebugLoc dl = Op.getNode()->getDebugLoc();
7350 SDValue Vec = Op.getNode()->getOperand(0);
7351 SDValue SubVec = Op.getNode()->getOperand(1);
7352 SDValue Idx = Op.getNode()->getOperand(2);
7354 if (Op.getNode()->getValueType(0).is256BitVector() &&
7355 SubVec.getNode()->getValueType(0).is128BitVector() &&
7356 isa<ConstantSDNode>(Idx)) {
7357 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7358 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7364 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7365 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7366 // one of the above mentioned nodes. It has to be wrapped because otherwise
7367 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7368 // be used to form addressing mode. These wrapped nodes will be selected
7371 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7372 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7374 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7376 unsigned char OpFlag = 0;
7377 unsigned WrapperKind = X86ISD::Wrapper;
7378 CodeModel::Model M = getTargetMachine().getCodeModel();
7380 if (Subtarget->isPICStyleRIPRel() &&
7381 (M == CodeModel::Small || M == CodeModel::Kernel))
7382 WrapperKind = X86ISD::WrapperRIP;
7383 else if (Subtarget->isPICStyleGOT())
7384 OpFlag = X86II::MO_GOTOFF;
7385 else if (Subtarget->isPICStyleStubPIC())
7386 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7388 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7390 CP->getOffset(), OpFlag);
7391 DebugLoc DL = CP->getDebugLoc();
7392 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7393 // With PIC, the address is actually $g + Offset.
7395 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7396 DAG.getNode(X86ISD::GlobalBaseReg,
7397 DebugLoc(), getPointerTy()),
7404 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7405 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7407 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7409 unsigned char OpFlag = 0;
7410 unsigned WrapperKind = X86ISD::Wrapper;
7411 CodeModel::Model M = getTargetMachine().getCodeModel();
7413 if (Subtarget->isPICStyleRIPRel() &&
7414 (M == CodeModel::Small || M == CodeModel::Kernel))
7415 WrapperKind = X86ISD::WrapperRIP;
7416 else if (Subtarget->isPICStyleGOT())
7417 OpFlag = X86II::MO_GOTOFF;
7418 else if (Subtarget->isPICStyleStubPIC())
7419 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7421 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7423 DebugLoc DL = JT->getDebugLoc();
7424 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7426 // With PIC, the address is actually $g + Offset.
7428 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7429 DAG.getNode(X86ISD::GlobalBaseReg,
7430 DebugLoc(), getPointerTy()),
7437 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7438 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7440 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7442 unsigned char OpFlag = 0;
7443 unsigned WrapperKind = X86ISD::Wrapper;
7444 CodeModel::Model M = getTargetMachine().getCodeModel();
7446 if (Subtarget->isPICStyleRIPRel() &&
7447 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7448 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7449 OpFlag = X86II::MO_GOTPCREL;
7450 WrapperKind = X86ISD::WrapperRIP;
7451 } else if (Subtarget->isPICStyleGOT()) {
7452 OpFlag = X86II::MO_GOT;
7453 } else if (Subtarget->isPICStyleStubPIC()) {
7454 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7455 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7456 OpFlag = X86II::MO_DARWIN_NONLAZY;
7459 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7461 DebugLoc DL = Op.getDebugLoc();
7462 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7464 // With PIC, the address is actually $g + Offset.
7465 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7466 !Subtarget->is64Bit()) {
7467 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7468 DAG.getNode(X86ISD::GlobalBaseReg,
7469 DebugLoc(), getPointerTy()),
7473 // For symbols that require a load from a stub to get the address, emit the
7475 if (isGlobalStubReference(OpFlag))
7476 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7477 MachinePointerInfo::getGOT(), false, false, false, 0);
7483 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7484 // Create the TargetBlockAddressAddress node.
7485 unsigned char OpFlags =
7486 Subtarget->ClassifyBlockAddressReference();
7487 CodeModel::Model M = getTargetMachine().getCodeModel();
7488 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7489 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7490 DebugLoc dl = Op.getDebugLoc();
7491 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7494 if (Subtarget->isPICStyleRIPRel() &&
7495 (M == CodeModel::Small || M == CodeModel::Kernel))
7496 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7498 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7500 // With PIC, the address is actually $g + Offset.
7501 if (isGlobalRelativeToPICBase(OpFlags)) {
7502 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7503 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7511 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7513 SelectionDAG &DAG) const {
7514 // Create the TargetGlobalAddress node, folding in the constant
7515 // offset if it is legal.
7516 unsigned char OpFlags =
7517 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7518 CodeModel::Model M = getTargetMachine().getCodeModel();
7520 if (OpFlags == X86II::MO_NO_FLAG &&
7521 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7522 // A direct static reference to a global.
7523 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7526 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7529 if (Subtarget->isPICStyleRIPRel() &&
7530 (M == CodeModel::Small || M == CodeModel::Kernel))
7531 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7533 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7535 // With PIC, the address is actually $g + Offset.
7536 if (isGlobalRelativeToPICBase(OpFlags)) {
7537 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7538 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7542 // For globals that require a load from a stub to get the address, emit the
7544 if (isGlobalStubReference(OpFlags))
7545 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7546 MachinePointerInfo::getGOT(), false, false, false, 0);
7548 // If there was a non-zero offset that we didn't fold, create an explicit
7551 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7552 DAG.getConstant(Offset, getPointerTy()));
7558 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7559 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7560 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7561 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7565 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7566 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7567 unsigned char OperandFlags, bool LocalDynamic = false) {
7568 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7569 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7570 DebugLoc dl = GA->getDebugLoc();
7571 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7572 GA->getValueType(0),
7576 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7580 SDValue Ops[] = { Chain, TGA, *InFlag };
7581 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7583 SDValue Ops[] = { Chain, TGA };
7584 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7587 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7588 MFI->setAdjustsStack(true);
7590 SDValue Flag = Chain.getValue(1);
7591 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7594 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7596 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7599 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7600 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7601 DAG.getNode(X86ISD::GlobalBaseReg,
7602 DebugLoc(), PtrVT), InFlag);
7603 InFlag = Chain.getValue(1);
7605 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7608 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7610 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7612 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7613 X86::RAX, X86II::MO_TLSGD);
7616 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7620 DebugLoc dl = GA->getDebugLoc();
7622 // Get the start address of the TLS block for this module.
7623 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7624 .getInfo<X86MachineFunctionInfo>();
7625 MFI->incNumLocalDynamicTLSAccesses();
7629 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7630 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7633 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7634 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7635 InFlag = Chain.getValue(1);
7636 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7637 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7640 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7644 unsigned char OperandFlags = X86II::MO_DTPOFF;
7645 unsigned WrapperKind = X86ISD::Wrapper;
7646 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7647 GA->getValueType(0),
7648 GA->getOffset(), OperandFlags);
7649 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7651 // Add x@dtpoff with the base.
7652 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7655 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7656 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7657 const EVT PtrVT, TLSModel::Model model,
7658 bool is64Bit, bool isPIC) {
7659 DebugLoc dl = GA->getDebugLoc();
7661 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7662 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7663 is64Bit ? 257 : 256));
7665 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7666 DAG.getIntPtrConstant(0),
7667 MachinePointerInfo(Ptr),
7668 false, false, false, 0);
7670 unsigned char OperandFlags = 0;
7671 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7673 unsigned WrapperKind = X86ISD::Wrapper;
7674 if (model == TLSModel::LocalExec) {
7675 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7676 } else if (model == TLSModel::InitialExec) {
7678 OperandFlags = X86II::MO_GOTTPOFF;
7679 WrapperKind = X86ISD::WrapperRIP;
7681 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7684 llvm_unreachable("Unexpected model");
7687 // emit "addl x@ntpoff,%eax" (local exec)
7688 // or "addl x@indntpoff,%eax" (initial exec)
7689 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7690 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7691 GA->getValueType(0),
7692 GA->getOffset(), OperandFlags);
7693 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7695 if (model == TLSModel::InitialExec) {
7696 if (isPIC && !is64Bit) {
7697 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7698 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7702 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7703 MachinePointerInfo::getGOT(), false, false, false,
7707 // The address of the thread local variable is the add of the thread
7708 // pointer with the offset of the variable.
7709 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7713 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7715 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7716 const GlobalValue *GV = GA->getGlobal();
7718 if (Subtarget->isTargetELF()) {
7719 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7722 case TLSModel::GeneralDynamic:
7723 if (Subtarget->is64Bit())
7724 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7725 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7726 case TLSModel::LocalDynamic:
7727 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7728 Subtarget->is64Bit());
7729 case TLSModel::InitialExec:
7730 case TLSModel::LocalExec:
7731 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7732 Subtarget->is64Bit(),
7733 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7735 llvm_unreachable("Unknown TLS model.");
7738 if (Subtarget->isTargetDarwin()) {
7739 // Darwin only has one model of TLS. Lower to that.
7740 unsigned char OpFlag = 0;
7741 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7742 X86ISD::WrapperRIP : X86ISD::Wrapper;
7744 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7746 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7747 !Subtarget->is64Bit();
7749 OpFlag = X86II::MO_TLVP_PIC_BASE;
7751 OpFlag = X86II::MO_TLVP;
7752 DebugLoc DL = Op.getDebugLoc();
7753 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7754 GA->getValueType(0),
7755 GA->getOffset(), OpFlag);
7756 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7758 // With PIC32, the address is actually $g + Offset.
7760 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7761 DAG.getNode(X86ISD::GlobalBaseReg,
7762 DebugLoc(), getPointerTy()),
7765 // Lowering the machine isd will make sure everything is in the right
7767 SDValue Chain = DAG.getEntryNode();
7768 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7769 SDValue Args[] = { Chain, Offset };
7770 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7772 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7773 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7774 MFI->setAdjustsStack(true);
7776 // And our return value (tls address) is in the standard call return value
7778 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7779 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7783 if (Subtarget->isTargetWindows()) {
7784 // Just use the implicit TLS architecture
7785 // Need to generate someting similar to:
7786 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7788 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7789 // mov rcx, qword [rdx+rcx*8]
7790 // mov eax, .tls$:tlsvar
7791 // [rax+rcx] contains the address
7792 // Windows 64bit: gs:0x58
7793 // Windows 32bit: fs:__tls_array
7795 // If GV is an alias then use the aliasee for determining
7796 // thread-localness.
7797 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7798 GV = GA->resolveAliasedGlobal(false);
7799 DebugLoc dl = GA->getDebugLoc();
7800 SDValue Chain = DAG.getEntryNode();
7802 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7803 // %gs:0x58 (64-bit).
7804 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7805 ? Type::getInt8PtrTy(*DAG.getContext(),
7807 : Type::getInt32PtrTy(*DAG.getContext(),
7810 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7811 Subtarget->is64Bit()
7812 ? DAG.getIntPtrConstant(0x58)
7813 : DAG.getExternalSymbol("_tls_array",
7815 MachinePointerInfo(Ptr),
7816 false, false, false, 0);
7818 // Load the _tls_index variable
7819 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7820 if (Subtarget->is64Bit())
7821 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7822 IDX, MachinePointerInfo(), MVT::i32,
7825 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7826 false, false, false, 0);
7828 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7830 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7832 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7833 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7834 false, false, false, 0);
7836 // Get the offset of start of .tls section
7837 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7838 GA->getValueType(0),
7839 GA->getOffset(), X86II::MO_SECREL);
7840 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7842 // The address of the thread local variable is the add of the thread
7843 // pointer with the offset of the variable.
7844 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7847 llvm_unreachable("TLS not implemented for this target.");
7850 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7851 /// and take a 2 x i32 value to shift plus a shift amount.
7852 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7853 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7854 EVT VT = Op.getValueType();
7855 unsigned VTBits = VT.getSizeInBits();
7856 DebugLoc dl = Op.getDebugLoc();
7857 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7858 SDValue ShOpLo = Op.getOperand(0);
7859 SDValue ShOpHi = Op.getOperand(1);
7860 SDValue ShAmt = Op.getOperand(2);
7861 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7862 DAG.getConstant(VTBits - 1, MVT::i8))
7863 : DAG.getConstant(0, VT);
7866 if (Op.getOpcode() == ISD::SHL_PARTS) {
7867 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7868 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7870 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7871 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7874 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7875 DAG.getConstant(VTBits, MVT::i8));
7876 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7877 AndNode, DAG.getConstant(0, MVT::i8));
7880 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7881 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7882 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7884 if (Op.getOpcode() == ISD::SHL_PARTS) {
7885 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7886 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7888 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7889 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7892 SDValue Ops[2] = { Lo, Hi };
7893 return DAG.getMergeValues(Ops, 2, dl);
7896 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7897 SelectionDAG &DAG) const {
7898 EVT SrcVT = Op.getOperand(0).getValueType();
7900 if (SrcVT.isVector())
7903 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7904 "Unknown SINT_TO_FP to lower!");
7906 // These are really Legal; return the operand so the caller accepts it as
7908 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7910 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7911 Subtarget->is64Bit()) {
7915 DebugLoc dl = Op.getDebugLoc();
7916 unsigned Size = SrcVT.getSizeInBits()/8;
7917 MachineFunction &MF = DAG.getMachineFunction();
7918 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7919 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7920 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7922 MachinePointerInfo::getFixedStack(SSFI),
7924 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7927 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7929 SelectionDAG &DAG) const {
7931 DebugLoc DL = Op.getDebugLoc();
7933 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7935 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7937 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7939 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7941 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7942 MachineMemOperand *MMO;
7944 int SSFI = FI->getIndex();
7946 DAG.getMachineFunction()
7947 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7948 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7950 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7951 StackSlot = StackSlot.getOperand(1);
7953 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7954 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7956 Tys, Ops, array_lengthof(Ops),
7960 Chain = Result.getValue(1);
7961 SDValue InFlag = Result.getValue(2);
7963 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7964 // shouldn't be necessary except that RFP cannot be live across
7965 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7966 MachineFunction &MF = DAG.getMachineFunction();
7967 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7968 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7969 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7970 Tys = DAG.getVTList(MVT::Other);
7972 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7974 MachineMemOperand *MMO =
7975 DAG.getMachineFunction()
7976 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7977 MachineMemOperand::MOStore, SSFISize, SSFISize);
7979 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7980 Ops, array_lengthof(Ops),
7981 Op.getValueType(), MMO);
7982 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7983 MachinePointerInfo::getFixedStack(SSFI),
7984 false, false, false, 0);
7990 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7991 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7992 SelectionDAG &DAG) const {
7993 // This algorithm is not obvious. Here it is what we're trying to output:
7996 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7997 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8001 pshufd $0x4e, %xmm0, %xmm1
8006 DebugLoc dl = Op.getDebugLoc();
8007 LLVMContext *Context = DAG.getContext();
8009 // Build some magic constants.
8010 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8011 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8012 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8014 SmallVector<Constant*,2> CV1;
8016 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8018 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8019 Constant *C1 = ConstantVector::get(CV1);
8020 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8022 // Load the 64-bit value into an XMM register.
8023 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8025 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8026 MachinePointerInfo::getConstantPool(),
8027 false, false, false, 16);
8028 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8029 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8032 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8033 MachinePointerInfo::getConstantPool(),
8034 false, false, false, 16);
8035 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8036 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8039 if (Subtarget->hasSSE3()) {
8040 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8041 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8043 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8044 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8046 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8047 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8051 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8052 DAG.getIntPtrConstant(0));
8055 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8056 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8057 SelectionDAG &DAG) const {
8058 DebugLoc dl = Op.getDebugLoc();
8059 // FP constant to bias correct the final result.
8060 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8063 // Load the 32-bit value into an XMM register.
8064 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8067 // Zero out the upper parts of the register.
8068 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8070 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8071 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8072 DAG.getIntPtrConstant(0));
8074 // Or the load with the bias.
8075 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8076 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8077 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8079 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8080 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8081 MVT::v2f64, Bias)));
8082 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8083 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8084 DAG.getIntPtrConstant(0));
8086 // Subtract the bias.
8087 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8089 // Handle final rounding.
8090 EVT DestVT = Op.getValueType();
8092 if (DestVT.bitsLT(MVT::f64))
8093 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8094 DAG.getIntPtrConstant(0));
8095 if (DestVT.bitsGT(MVT::f64))
8096 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8098 // Handle final rounding.
8102 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8103 SelectionDAG &DAG) const {
8104 SDValue N0 = Op.getOperand(0);
8105 EVT SVT = N0.getValueType();
8106 DebugLoc dl = Op.getDebugLoc();
8108 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8109 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8110 "Custom UINT_TO_FP is not supported!");
8112 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8113 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8114 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8117 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8118 SelectionDAG &DAG) const {
8119 SDValue N0 = Op.getOperand(0);
8120 DebugLoc dl = Op.getDebugLoc();
8122 if (Op.getValueType().isVector())
8123 return lowerUINT_TO_FP_vec(Op, DAG);
8125 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8126 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8127 // the optimization here.
8128 if (DAG.SignBitIsZero(N0))
8129 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8131 EVT SrcVT = N0.getValueType();
8132 EVT DstVT = Op.getValueType();
8133 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8134 return LowerUINT_TO_FP_i64(Op, DAG);
8135 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8136 return LowerUINT_TO_FP_i32(Op, DAG);
8137 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8140 // Make a 64-bit buffer, and use it to build an FILD.
8141 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8142 if (SrcVT == MVT::i32) {
8143 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8144 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8145 getPointerTy(), StackSlot, WordOff);
8146 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8147 StackSlot, MachinePointerInfo(),
8149 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8150 OffsetSlot, MachinePointerInfo(),
8152 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8156 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8157 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8158 StackSlot, MachinePointerInfo(),
8160 // For i64 source, we need to add the appropriate power of 2 if the input
8161 // was negative. This is the same as the optimization in
8162 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8163 // we must be careful to do the computation in x87 extended precision, not
8164 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8165 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8166 MachineMemOperand *MMO =
8167 DAG.getMachineFunction()
8168 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8169 MachineMemOperand::MOLoad, 8, 8);
8171 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8172 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8173 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8176 APInt FF(32, 0x5F800000ULL);
8178 // Check whether the sign bit is set.
8179 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8180 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8183 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8184 SDValue FudgePtr = DAG.getConstantPool(
8185 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8188 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8189 SDValue Zero = DAG.getIntPtrConstant(0);
8190 SDValue Four = DAG.getIntPtrConstant(4);
8191 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8193 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8195 // Load the value out, extending it from f32 to f80.
8196 // FIXME: Avoid the extend by constructing the right constant pool?
8197 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8198 FudgePtr, MachinePointerInfo::getConstantPool(),
8199 MVT::f32, false, false, 4);
8200 // Extend everything to 80 bits to force it to be done on x87.
8201 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8202 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8205 std::pair<SDValue,SDValue> X86TargetLowering::
8206 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8207 DebugLoc DL = Op.getDebugLoc();
8209 EVT DstTy = Op.getValueType();
8211 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8212 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8216 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8217 DstTy.getSimpleVT() >= MVT::i16 &&
8218 "Unknown FP_TO_INT to lower!");
8220 // These are really Legal.
8221 if (DstTy == MVT::i32 &&
8222 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8223 return std::make_pair(SDValue(), SDValue());
8224 if (Subtarget->is64Bit() &&
8225 DstTy == MVT::i64 &&
8226 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8227 return std::make_pair(SDValue(), SDValue());
8229 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8230 // stack slot, or into the FTOL runtime function.
8231 MachineFunction &MF = DAG.getMachineFunction();
8232 unsigned MemSize = DstTy.getSizeInBits()/8;
8233 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8234 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8237 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8238 Opc = X86ISD::WIN_FTOL;
8240 switch (DstTy.getSimpleVT().SimpleTy) {
8241 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8242 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8243 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8244 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8247 SDValue Chain = DAG.getEntryNode();
8248 SDValue Value = Op.getOperand(0);
8249 EVT TheVT = Op.getOperand(0).getValueType();
8250 // FIXME This causes a redundant load/store if the SSE-class value is already
8251 // in memory, such as if it is on the callstack.
8252 if (isScalarFPTypeInSSEReg(TheVT)) {
8253 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8254 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8255 MachinePointerInfo::getFixedStack(SSFI),
8257 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8259 Chain, StackSlot, DAG.getValueType(TheVT)
8262 MachineMemOperand *MMO =
8263 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8264 MachineMemOperand::MOLoad, MemSize, MemSize);
8265 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8267 Chain = Value.getValue(1);
8268 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8269 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8272 MachineMemOperand *MMO =
8273 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8274 MachineMemOperand::MOStore, MemSize, MemSize);
8276 if (Opc != X86ISD::WIN_FTOL) {
8277 // Build the FP_TO_INT*_IN_MEM
8278 SDValue Ops[] = { Chain, Value, StackSlot };
8279 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8280 Ops, 3, DstTy, MMO);
8281 return std::make_pair(FIST, StackSlot);
8283 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8284 DAG.getVTList(MVT::Other, MVT::Glue),
8286 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8287 MVT::i32, ftol.getValue(1));
8288 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8289 MVT::i32, eax.getValue(2));
8290 SDValue Ops[] = { eax, edx };
8291 SDValue pair = IsReplace
8292 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8293 : DAG.getMergeValues(Ops, 2, DL);
8294 return std::make_pair(pair, SDValue());
8298 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8299 const X86Subtarget *Subtarget) {
8300 EVT VT = Op->getValueType(0);
8301 SDValue In = Op->getOperand(0);
8302 EVT InVT = In.getValueType();
8303 DebugLoc dl = Op->getDebugLoc();
8305 // Optimize vectors in AVX mode:
8308 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8309 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8310 // Concat upper and lower parts.
8313 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8314 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8315 // Concat upper and lower parts.
8318 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8319 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8322 if (Subtarget->hasInt256())
8323 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8325 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8326 SDValue Undef = DAG.getUNDEF(InVT);
8327 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8328 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8329 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8331 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8332 VT.getVectorNumElements()/2);
8334 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8335 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8337 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8340 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8341 SelectionDAG &DAG) const {
8342 if (Subtarget->hasFp256()) {
8343 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8350 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8351 SelectionDAG &DAG) const {
8352 DebugLoc DL = Op.getDebugLoc();
8353 EVT VT = Op.getValueType();
8354 SDValue In = Op.getOperand(0);
8355 EVT SVT = In.getValueType();
8357 if (Subtarget->hasFp256()) {
8358 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8363 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8364 VT.getVectorNumElements() != SVT.getVectorNumElements())
8367 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8369 // AVX2 has better support of integer extending.
8370 if (Subtarget->hasInt256())
8371 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8373 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8374 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8375 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8376 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8377 DAG.getUNDEF(MVT::v8i16),
8380 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8383 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8384 DebugLoc DL = Op.getDebugLoc();
8385 EVT VT = Op.getValueType();
8386 SDValue In = Op.getOperand(0);
8387 EVT SVT = In.getValueType();
8389 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8390 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8391 if (Subtarget->hasInt256()) {
8392 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8393 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8394 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8396 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8397 DAG.getIntPtrConstant(0));
8400 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8401 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8402 DAG.getIntPtrConstant(0));
8403 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8404 DAG.getIntPtrConstant(2));
8406 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8407 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8410 static const int ShufMask1[] = {0, 2, 0, 0};
8411 SDValue Undef = DAG.getUNDEF(VT);
8412 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8413 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8415 // The MOVLHPS mask:
8416 static const int ShufMask2[] = {0, 1, 4, 5};
8417 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8420 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8421 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8422 if (Subtarget->hasInt256()) {
8423 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8425 SmallVector<SDValue,32> pshufbMask;
8426 for (unsigned i = 0; i < 2; ++i) {
8427 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8428 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8429 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8430 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8431 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8432 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8433 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8434 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8435 for (unsigned j = 0; j < 8; ++j)
8436 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8438 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8439 &pshufbMask[0], 32);
8440 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8441 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8443 static const int ShufMask[] = {0, 2, -1, -1};
8444 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8446 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8447 DAG.getIntPtrConstant(0));
8448 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8451 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8452 DAG.getIntPtrConstant(0));
8454 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8455 DAG.getIntPtrConstant(4));
8457 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8458 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8461 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8462 -1, -1, -1, -1, -1, -1, -1, -1};
8464 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8465 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8466 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8468 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8469 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8471 // The MOVLHPS Mask:
8472 static const int ShufMask2[] = {0, 1, 4, 5};
8473 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8474 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8477 // Handle truncation of V256 to V128 using shuffles.
8478 if (!VT.is128BitVector() || !SVT.is256BitVector())
8481 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8483 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8485 unsigned NumElems = VT.getVectorNumElements();
8486 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8489 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8490 // Prepare truncation shuffle mask
8491 for (unsigned i = 0; i != NumElems; ++i)
8493 SDValue V = DAG.getVectorShuffle(NVT, DL,
8494 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8495 DAG.getUNDEF(NVT), &MaskVec[0]);
8496 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8497 DAG.getIntPtrConstant(0));
8500 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8501 SelectionDAG &DAG) const {
8502 if (Op.getValueType().isVector()) {
8503 if (Op.getValueType() == MVT::v8i16)
8504 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8505 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8506 MVT::v8i32, Op.getOperand(0)));
8510 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8511 /*IsSigned=*/ true, /*IsReplace=*/ false);
8512 SDValue FIST = Vals.first, StackSlot = Vals.second;
8513 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8514 if (FIST.getNode() == 0) return Op;
8516 if (StackSlot.getNode())
8518 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8519 FIST, StackSlot, MachinePointerInfo(),
8520 false, false, false, 0);
8522 // The node is the result.
8526 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8527 SelectionDAG &DAG) const {
8528 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8529 /*IsSigned=*/ false, /*IsReplace=*/ false);
8530 SDValue FIST = Vals.first, StackSlot = Vals.second;
8531 assert(FIST.getNode() && "Unexpected failure");
8533 if (StackSlot.getNode())
8535 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8536 FIST, StackSlot, MachinePointerInfo(),
8537 false, false, false, 0);
8539 // The node is the result.
8543 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8544 SelectionDAG &DAG) const {
8545 DebugLoc DL = Op.getDebugLoc();
8546 EVT VT = Op.getValueType();
8547 SDValue In = Op.getOperand(0);
8548 EVT SVT = In.getValueType();
8550 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8552 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8553 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8554 In, DAG.getUNDEF(SVT)));
8557 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8558 LLVMContext *Context = DAG.getContext();
8559 DebugLoc dl = Op.getDebugLoc();
8560 EVT VT = Op.getValueType();
8562 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8563 if (VT.isVector()) {
8564 EltVT = VT.getVectorElementType();
8565 NumElts = VT.getVectorNumElements();
8568 if (EltVT == MVT::f64)
8569 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8571 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8572 C = ConstantVector::getSplat(NumElts, C);
8573 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8574 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8575 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8576 MachinePointerInfo::getConstantPool(),
8577 false, false, false, Alignment);
8578 if (VT.isVector()) {
8579 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8580 return DAG.getNode(ISD::BITCAST, dl, VT,
8581 DAG.getNode(ISD::AND, dl, ANDVT,
8582 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8584 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8586 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8589 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8590 LLVMContext *Context = DAG.getContext();
8591 DebugLoc dl = Op.getDebugLoc();
8592 EVT VT = Op.getValueType();
8594 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8595 if (VT.isVector()) {
8596 EltVT = VT.getVectorElementType();
8597 NumElts = VT.getVectorNumElements();
8600 if (EltVT == MVT::f64)
8601 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8603 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8604 C = ConstantVector::getSplat(NumElts, C);
8605 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8606 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8607 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8608 MachinePointerInfo::getConstantPool(),
8609 false, false, false, Alignment);
8610 if (VT.isVector()) {
8611 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8612 return DAG.getNode(ISD::BITCAST, dl, VT,
8613 DAG.getNode(ISD::XOR, dl, XORVT,
8614 DAG.getNode(ISD::BITCAST, dl, XORVT,
8616 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8619 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8622 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8623 LLVMContext *Context = DAG.getContext();
8624 SDValue Op0 = Op.getOperand(0);
8625 SDValue Op1 = Op.getOperand(1);
8626 DebugLoc dl = Op.getDebugLoc();
8627 EVT VT = Op.getValueType();
8628 EVT SrcVT = Op1.getValueType();
8630 // If second operand is smaller, extend it first.
8631 if (SrcVT.bitsLT(VT)) {
8632 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8635 // And if it is bigger, shrink it first.
8636 if (SrcVT.bitsGT(VT)) {
8637 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8641 // At this point the operands and the result should have the same
8642 // type, and that won't be f80 since that is not custom lowered.
8644 // First get the sign bit of second operand.
8645 SmallVector<Constant*,4> CV;
8646 if (SrcVT == MVT::f64) {
8647 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8648 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8650 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8651 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8652 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8653 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8655 Constant *C = ConstantVector::get(CV);
8656 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8657 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8658 MachinePointerInfo::getConstantPool(),
8659 false, false, false, 16);
8660 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8662 // Shift sign bit right or left if the two operands have different types.
8663 if (SrcVT.bitsGT(VT)) {
8664 // Op0 is MVT::f32, Op1 is MVT::f64.
8665 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8666 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8667 DAG.getConstant(32, MVT::i32));
8668 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8669 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8670 DAG.getIntPtrConstant(0));
8673 // Clear first operand sign bit.
8675 if (VT == MVT::f64) {
8676 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8677 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8679 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8680 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8681 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8682 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8684 C = ConstantVector::get(CV);
8685 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8686 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8687 MachinePointerInfo::getConstantPool(),
8688 false, false, false, 16);
8689 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8691 // Or the value with the sign bit.
8692 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8695 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8696 SDValue N0 = Op.getOperand(0);
8697 DebugLoc dl = Op.getDebugLoc();
8698 EVT VT = Op.getValueType();
8700 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8701 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8702 DAG.getConstant(1, VT));
8703 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8706 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8708 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8709 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8711 if (!Subtarget->hasSSE41())
8714 if (!Op->hasOneUse())
8717 SDNode *N = Op.getNode();
8718 DebugLoc DL = N->getDebugLoc();
8720 SmallVector<SDValue, 8> Opnds;
8721 DenseMap<SDValue, unsigned> VecInMap;
8722 EVT VT = MVT::Other;
8724 // Recognize a special case where a vector is casted into wide integer to
8726 Opnds.push_back(N->getOperand(0));
8727 Opnds.push_back(N->getOperand(1));
8729 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8730 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8731 // BFS traverse all OR'd operands.
8732 if (I->getOpcode() == ISD::OR) {
8733 Opnds.push_back(I->getOperand(0));
8734 Opnds.push_back(I->getOperand(1));
8735 // Re-evaluate the number of nodes to be traversed.
8736 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8740 // Quit if a non-EXTRACT_VECTOR_ELT
8741 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8744 // Quit if without a constant index.
8745 SDValue Idx = I->getOperand(1);
8746 if (!isa<ConstantSDNode>(Idx))
8749 SDValue ExtractedFromVec = I->getOperand(0);
8750 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8751 if (M == VecInMap.end()) {
8752 VT = ExtractedFromVec.getValueType();
8753 // Quit if not 128/256-bit vector.
8754 if (!VT.is128BitVector() && !VT.is256BitVector())
8756 // Quit if not the same type.
8757 if (VecInMap.begin() != VecInMap.end() &&
8758 VT != VecInMap.begin()->first.getValueType())
8760 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8762 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8765 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8766 "Not extracted from 128-/256-bit vector.");
8768 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8769 SmallVector<SDValue, 8> VecIns;
8771 for (DenseMap<SDValue, unsigned>::const_iterator
8772 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8773 // Quit if not all elements are used.
8774 if (I->second != FullMask)
8776 VecIns.push_back(I->first);
8779 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8781 // Cast all vectors into TestVT for PTEST.
8782 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8783 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8785 // If more than one full vectors are evaluated, OR them first before PTEST.
8786 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8787 // Each iteration will OR 2 nodes and append the result until there is only
8788 // 1 node left, i.e. the final OR'd value of all vectors.
8789 SDValue LHS = VecIns[Slot];
8790 SDValue RHS = VecIns[Slot + 1];
8791 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8794 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8795 VecIns.back(), VecIns.back());
8798 /// Emit nodes that will be selected as "test Op0,Op0", or something
8800 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8801 SelectionDAG &DAG) const {
8802 DebugLoc dl = Op.getDebugLoc();
8804 // CF and OF aren't always set the way we want. Determine which
8805 // of these we need.
8806 bool NeedCF = false;
8807 bool NeedOF = false;
8810 case X86::COND_A: case X86::COND_AE:
8811 case X86::COND_B: case X86::COND_BE:
8814 case X86::COND_G: case X86::COND_GE:
8815 case X86::COND_L: case X86::COND_LE:
8816 case X86::COND_O: case X86::COND_NO:
8821 // See if we can use the EFLAGS value from the operand instead of
8822 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8823 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8824 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8825 // Emit a CMP with 0, which is the TEST pattern.
8826 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8827 DAG.getConstant(0, Op.getValueType()));
8829 unsigned Opcode = 0;
8830 unsigned NumOperands = 0;
8832 // Truncate operations may prevent the merge of the SETCC instruction
8833 // and the arithmetic intruction before it. Attempt to truncate the operands
8834 // of the arithmetic instruction and use a reduced bit-width instruction.
8835 bool NeedTruncation = false;
8836 SDValue ArithOp = Op;
8837 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8838 SDValue Arith = Op->getOperand(0);
8839 // Both the trunc and the arithmetic op need to have one user each.
8840 if (Arith->hasOneUse())
8841 switch (Arith.getOpcode()) {
8848 NeedTruncation = true;
8854 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8855 // which may be the result of a CAST. We use the variable 'Op', which is the
8856 // non-casted variable when we check for possible users.
8857 switch (ArithOp.getOpcode()) {
8859 // Due to an isel shortcoming, be conservative if this add is likely to be
8860 // selected as part of a load-modify-store instruction. When the root node
8861 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8862 // uses of other nodes in the match, such as the ADD in this case. This
8863 // leads to the ADD being left around and reselected, with the result being
8864 // two adds in the output. Alas, even if none our users are stores, that
8865 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8866 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8867 // climbing the DAG back to the root, and it doesn't seem to be worth the
8869 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8870 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8871 if (UI->getOpcode() != ISD::CopyToReg &&
8872 UI->getOpcode() != ISD::SETCC &&
8873 UI->getOpcode() != ISD::STORE)
8876 if (ConstantSDNode *C =
8877 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8878 // An add of one will be selected as an INC.
8879 if (C->getAPIntValue() == 1) {
8880 Opcode = X86ISD::INC;
8885 // An add of negative one (subtract of one) will be selected as a DEC.
8886 if (C->getAPIntValue().isAllOnesValue()) {
8887 Opcode = X86ISD::DEC;
8893 // Otherwise use a regular EFLAGS-setting add.
8894 Opcode = X86ISD::ADD;
8898 // If the primary and result isn't used, don't bother using X86ISD::AND,
8899 // because a TEST instruction will be better.
8900 bool NonFlagUse = false;
8901 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8902 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8904 unsigned UOpNo = UI.getOperandNo();
8905 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8906 // Look pass truncate.
8907 UOpNo = User->use_begin().getOperandNo();
8908 User = *User->use_begin();
8911 if (User->getOpcode() != ISD::BRCOND &&
8912 User->getOpcode() != ISD::SETCC &&
8913 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8926 // Due to the ISEL shortcoming noted above, be conservative if this op is
8927 // likely to be selected as part of a load-modify-store instruction.
8928 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8929 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8930 if (UI->getOpcode() == ISD::STORE)
8933 // Otherwise use a regular EFLAGS-setting instruction.
8934 switch (ArithOp.getOpcode()) {
8935 default: llvm_unreachable("unexpected operator!");
8936 case ISD::SUB: Opcode = X86ISD::SUB; break;
8937 case ISD::XOR: Opcode = X86ISD::XOR; break;
8938 case ISD::AND: Opcode = X86ISD::AND; break;
8940 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8941 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8942 if (EFLAGS.getNode())
8945 Opcode = X86ISD::OR;
8959 return SDValue(Op.getNode(), 1);
8965 // If we found that truncation is beneficial, perform the truncation and
8967 if (NeedTruncation) {
8968 EVT VT = Op.getValueType();
8969 SDValue WideVal = Op->getOperand(0);
8970 EVT WideVT = WideVal.getValueType();
8971 unsigned ConvertedOp = 0;
8972 // Use a target machine opcode to prevent further DAGCombine
8973 // optimizations that may separate the arithmetic operations
8974 // from the setcc node.
8975 switch (WideVal.getOpcode()) {
8977 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8978 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8979 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8980 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8981 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8986 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8987 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8988 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8989 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8995 // Emit a CMP with 0, which is the TEST pattern.
8996 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8997 DAG.getConstant(0, Op.getValueType()));
8999 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9000 SmallVector<SDValue, 4> Ops;
9001 for (unsigned i = 0; i != NumOperands; ++i)
9002 Ops.push_back(Op.getOperand(i));
9004 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9005 DAG.ReplaceAllUsesWith(Op, New);
9006 return SDValue(New.getNode(), 1);
9009 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9011 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9012 SelectionDAG &DAG) const {
9013 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9014 if (C->getAPIntValue() == 0)
9015 return EmitTest(Op0, X86CC, DAG);
9017 DebugLoc dl = Op0.getDebugLoc();
9018 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9019 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9020 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9021 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9022 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9024 return SDValue(Sub.getNode(), 1);
9026 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9029 /// Convert a comparison if required by the subtarget.
9030 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9031 SelectionDAG &DAG) const {
9032 // If the subtarget does not support the FUCOMI instruction, floating-point
9033 // comparisons have to be converted.
9034 if (Subtarget->hasCMov() ||
9035 Cmp.getOpcode() != X86ISD::CMP ||
9036 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9037 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9040 // The instruction selector will select an FUCOM instruction instead of
9041 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9042 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9043 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9044 DebugLoc dl = Cmp.getDebugLoc();
9045 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9046 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9047 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9048 DAG.getConstant(8, MVT::i8));
9049 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9050 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9053 static bool isAllOnes(SDValue V) {
9054 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9055 return C && C->isAllOnesValue();
9058 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9059 /// if it's possible.
9060 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9061 DebugLoc dl, SelectionDAG &DAG) const {
9062 SDValue Op0 = And.getOperand(0);
9063 SDValue Op1 = And.getOperand(1);
9064 if (Op0.getOpcode() == ISD::TRUNCATE)
9065 Op0 = Op0.getOperand(0);
9066 if (Op1.getOpcode() == ISD::TRUNCATE)
9067 Op1 = Op1.getOperand(0);
9070 if (Op1.getOpcode() == ISD::SHL)
9071 std::swap(Op0, Op1);
9072 if (Op0.getOpcode() == ISD::SHL) {
9073 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9074 if (And00C->getZExtValue() == 1) {
9075 // If we looked past a truncate, check that it's only truncating away
9077 unsigned BitWidth = Op0.getValueSizeInBits();
9078 unsigned AndBitWidth = And.getValueSizeInBits();
9079 if (BitWidth > AndBitWidth) {
9081 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9082 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9086 RHS = Op0.getOperand(1);
9088 } else if (Op1.getOpcode() == ISD::Constant) {
9089 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9090 uint64_t AndRHSVal = AndRHS->getZExtValue();
9091 SDValue AndLHS = Op0;
9093 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9094 LHS = AndLHS.getOperand(0);
9095 RHS = AndLHS.getOperand(1);
9098 // Use BT if the immediate can't be encoded in a TEST instruction.
9099 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9101 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9105 if (LHS.getNode()) {
9106 // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9107 // the condition code later.
9108 bool Invert = false;
9109 if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9111 LHS = LHS.getOperand(0);
9114 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9115 // instruction. Since the shift amount is in-range-or-undefined, we know
9116 // that doing a bittest on the i32 value is ok. We extend to i32 because
9117 // the encoding for the i16 version is larger than the i32 version.
9118 // Also promote i16 to i32 for performance / code size reason.
9119 if (LHS.getValueType() == MVT::i8 ||
9120 LHS.getValueType() == MVT::i16)
9121 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9123 // If the operand types disagree, extend the shift amount to match. Since
9124 // BT ignores high bits (like shifts) we can use anyextend.
9125 if (LHS.getValueType() != RHS.getValueType())
9126 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9128 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9129 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9130 // Flip the condition if the LHS was a not instruction
9132 Cond = X86::GetOppositeBranchCondition(Cond);
9133 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9134 DAG.getConstant(Cond, MVT::i8), BT);
9140 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9142 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
9144 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
9145 SDValue Op0 = Op.getOperand(0);
9146 SDValue Op1 = Op.getOperand(1);
9147 DebugLoc dl = Op.getDebugLoc();
9148 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9150 // Optimize to BT if possible.
9151 // Lower (X & (1 << N)) == 0 to BT(X, N).
9152 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9153 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9154 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9155 Op1.getOpcode() == ISD::Constant &&
9156 cast<ConstantSDNode>(Op1)->isNullValue() &&
9157 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9158 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9159 if (NewSetCC.getNode())
9163 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9165 if (Op1.getOpcode() == ISD::Constant &&
9166 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9167 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9168 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9170 // If the input is a setcc, then reuse the input setcc or use a new one with
9171 // the inverted condition.
9172 if (Op0.getOpcode() == X86ISD::SETCC) {
9173 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9174 bool Invert = (CC == ISD::SETNE) ^
9175 cast<ConstantSDNode>(Op1)->isNullValue();
9176 if (!Invert) return Op0;
9178 CCode = X86::GetOppositeBranchCondition(CCode);
9179 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9180 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9184 bool isFP = Op1.getValueType().isFloatingPoint();
9185 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9186 if (X86CC == X86::COND_INVALID)
9189 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9190 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9191 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9192 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9195 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9196 // ones, and then concatenate the result back.
9197 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9198 EVT VT = Op.getValueType();
9200 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9201 "Unsupported value type for operation");
9203 unsigned NumElems = VT.getVectorNumElements();
9204 DebugLoc dl = Op.getDebugLoc();
9205 SDValue CC = Op.getOperand(2);
9207 // Extract the LHS vectors
9208 SDValue LHS = Op.getOperand(0);
9209 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9210 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9212 // Extract the RHS vectors
9213 SDValue RHS = Op.getOperand(1);
9214 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9215 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9217 // Issue the operation on the smaller types and concatenate the result back
9218 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9219 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9220 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9221 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9222 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9225 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9227 SDValue Op0 = Op.getOperand(0);
9228 SDValue Op1 = Op.getOperand(1);
9229 SDValue CC = Op.getOperand(2);
9230 EVT VT = Op.getValueType();
9231 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9232 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9233 DebugLoc dl = Op.getDebugLoc();
9237 EVT EltVT = Op0.getValueType().getVectorElementType();
9238 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9244 // SSE Condition code mapping:
9253 switch (SetCCOpcode) {
9254 default: llvm_unreachable("Unexpected SETCC condition");
9256 case ISD::SETEQ: SSECC = 0; break;
9258 case ISD::SETGT: Swap = true; // Fallthrough
9260 case ISD::SETOLT: SSECC = 1; break;
9262 case ISD::SETGE: Swap = true; // Fallthrough
9264 case ISD::SETOLE: SSECC = 2; break;
9265 case ISD::SETUO: SSECC = 3; break;
9267 case ISD::SETNE: SSECC = 4; break;
9268 case ISD::SETULE: Swap = true; // Fallthrough
9269 case ISD::SETUGE: SSECC = 5; break;
9270 case ISD::SETULT: Swap = true; // Fallthrough
9271 case ISD::SETUGT: SSECC = 6; break;
9272 case ISD::SETO: SSECC = 7; break;
9274 case ISD::SETONE: SSECC = 8; break;
9277 std::swap(Op0, Op1);
9279 // In the two special cases we can't handle, emit two comparisons.
9282 unsigned CombineOpc;
9283 if (SetCCOpcode == ISD::SETUEQ) {
9284 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9286 assert(SetCCOpcode == ISD::SETONE);
9287 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9290 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9291 DAG.getConstant(CC0, MVT::i8));
9292 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9293 DAG.getConstant(CC1, MVT::i8));
9294 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9296 // Handle all other FP comparisons here.
9297 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9298 DAG.getConstant(SSECC, MVT::i8));
9301 // Break 256-bit integer vector compare into smaller ones.
9302 if (VT.is256BitVector() && !Subtarget->hasInt256())
9303 return Lower256IntVSETCC(Op, DAG);
9305 // We are handling one of the integer comparisons here. Since SSE only has
9306 // GT and EQ comparisons for integer, swapping operands and multiple
9307 // operations may be required for some comparisons.
9309 bool Swap = false, Invert = false, FlipSigns = false;
9311 switch (SetCCOpcode) {
9312 default: llvm_unreachable("Unexpected SETCC condition");
9313 case ISD::SETNE: Invert = true;
9314 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9315 case ISD::SETLT: Swap = true;
9316 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9317 case ISD::SETGE: Swap = true;
9318 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9319 case ISD::SETULT: Swap = true;
9320 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9321 case ISD::SETUGE: Swap = true;
9322 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9325 std::swap(Op0, Op1);
9327 // Check that the operation in question is available (most are plain SSE2,
9328 // but PCMPGTQ and PCMPEQQ have different requirements).
9329 if (VT == MVT::v2i64) {
9330 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9332 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9333 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9334 // pcmpeqd + pshufd + pand.
9335 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9337 // First cast everything to the right type,
9338 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9339 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9342 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9344 // Make sure the lower and upper halves are both all-ones.
9345 const int Mask[] = { 1, 0, 3, 2 };
9346 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9347 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9350 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9352 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9356 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9357 // bits of the inputs before performing those operations.
9359 EVT EltVT = VT.getVectorElementType();
9360 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9362 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9363 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9365 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9366 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9369 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9371 // If the logical-not of the result is required, perform that now.
9373 Result = DAG.getNOT(dl, Result, VT);
9378 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9379 static bool isX86LogicalCmp(SDValue Op) {
9380 unsigned Opc = Op.getNode()->getOpcode();
9381 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9382 Opc == X86ISD::SAHF)
9384 if (Op.getResNo() == 1 &&
9385 (Opc == X86ISD::ADD ||
9386 Opc == X86ISD::SUB ||
9387 Opc == X86ISD::ADC ||
9388 Opc == X86ISD::SBB ||
9389 Opc == X86ISD::SMUL ||
9390 Opc == X86ISD::UMUL ||
9391 Opc == X86ISD::INC ||
9392 Opc == X86ISD::DEC ||
9393 Opc == X86ISD::OR ||
9394 Opc == X86ISD::XOR ||
9395 Opc == X86ISD::AND))
9398 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9404 static bool isZero(SDValue V) {
9405 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9406 return C && C->isNullValue();
9409 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9410 if (V.getOpcode() != ISD::TRUNCATE)
9413 SDValue VOp0 = V.getOperand(0);
9414 unsigned InBits = VOp0.getValueSizeInBits();
9415 unsigned Bits = V.getValueSizeInBits();
9416 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9419 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9420 bool addTest = true;
9421 SDValue Cond = Op.getOperand(0);
9422 SDValue Op1 = Op.getOperand(1);
9423 SDValue Op2 = Op.getOperand(2);
9424 DebugLoc DL = Op.getDebugLoc();
9427 if (Cond.getOpcode() == ISD::SETCC) {
9428 SDValue NewCond = LowerSETCC(Cond, DAG);
9429 if (NewCond.getNode())
9433 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9434 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9435 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9436 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9437 if (Cond.getOpcode() == X86ISD::SETCC &&
9438 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9439 isZero(Cond.getOperand(1).getOperand(1))) {
9440 SDValue Cmp = Cond.getOperand(1);
9442 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9444 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9445 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9446 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9448 SDValue CmpOp0 = Cmp.getOperand(0);
9449 // Apply further optimizations for special cases
9450 // (select (x != 0), -1, 0) -> neg & sbb
9451 // (select (x == 0), 0, -1) -> neg & sbb
9452 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9453 if (YC->isNullValue() &&
9454 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9455 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9456 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9457 DAG.getConstant(0, CmpOp0.getValueType()),
9459 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9460 DAG.getConstant(X86::COND_B, MVT::i8),
9461 SDValue(Neg.getNode(), 1));
9465 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9466 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9467 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9469 SDValue Res = // Res = 0 or -1.
9470 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9471 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9473 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9474 Res = DAG.getNOT(DL, Res, Res.getValueType());
9476 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9477 if (N2C == 0 || !N2C->isNullValue())
9478 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9483 // Look past (and (setcc_carry (cmp ...)), 1).
9484 if (Cond.getOpcode() == ISD::AND &&
9485 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9486 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9487 if (C && C->getAPIntValue() == 1)
9488 Cond = Cond.getOperand(0);
9491 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9492 // setting operand in place of the X86ISD::SETCC.
9493 unsigned CondOpcode = Cond.getOpcode();
9494 if (CondOpcode == X86ISD::SETCC ||
9495 CondOpcode == X86ISD::SETCC_CARRY) {
9496 CC = Cond.getOperand(0);
9498 SDValue Cmp = Cond.getOperand(1);
9499 unsigned Opc = Cmp.getOpcode();
9500 EVT VT = Op.getValueType();
9502 bool IllegalFPCMov = false;
9503 if (VT.isFloatingPoint() && !VT.isVector() &&
9504 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9505 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9507 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9508 Opc == X86ISD::BT) { // FIXME
9512 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9513 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9514 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9515 Cond.getOperand(0).getValueType() != MVT::i8)) {
9516 SDValue LHS = Cond.getOperand(0);
9517 SDValue RHS = Cond.getOperand(1);
9521 switch (CondOpcode) {
9522 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9523 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9524 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9525 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9526 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9527 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9528 default: llvm_unreachable("unexpected overflowing operator");
9530 if (CondOpcode == ISD::UMULO)
9531 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9534 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9536 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9538 if (CondOpcode == ISD::UMULO)
9539 Cond = X86Op.getValue(2);
9541 Cond = X86Op.getValue(1);
9543 CC = DAG.getConstant(X86Cond, MVT::i8);
9548 // Look pass the truncate if the high bits are known zero.
9549 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9550 Cond = Cond.getOperand(0);
9552 // We know the result of AND is compared against zero. Try to match
9554 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9555 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9556 if (NewSetCC.getNode()) {
9557 CC = NewSetCC.getOperand(0);
9558 Cond = NewSetCC.getOperand(1);
9565 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9566 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9569 // a < b ? -1 : 0 -> RES = ~setcc_carry
9570 // a < b ? 0 : -1 -> RES = setcc_carry
9571 // a >= b ? -1 : 0 -> RES = setcc_carry
9572 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9573 if (Cond.getOpcode() == X86ISD::SUB) {
9574 Cond = ConvertCmpIfNecessary(Cond, DAG);
9575 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9577 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9578 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9579 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9580 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9581 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9582 return DAG.getNOT(DL, Res, Res.getValueType());
9587 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9588 // widen the cmov and push the truncate through. This avoids introducing a new
9589 // branch during isel and doesn't add any extensions.
9590 if (Op.getValueType() == MVT::i8 &&
9591 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9592 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9593 if (T1.getValueType() == T2.getValueType() &&
9594 // Blacklist CopyFromReg to avoid partial register stalls.
9595 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9596 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9597 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9598 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9602 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9603 // condition is true.
9604 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9605 SDValue Ops[] = { Op2, Op1, CC, Cond };
9606 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9609 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9610 SelectionDAG &DAG) const {
9611 EVT VT = Op->getValueType(0);
9612 SDValue In = Op->getOperand(0);
9613 EVT InVT = In.getValueType();
9614 DebugLoc dl = Op->getDebugLoc();
9616 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9617 (VT != MVT::v8i32 || InVT != MVT::v8i16))
9620 if (Subtarget->hasInt256())
9621 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9623 // Optimize vectors in AVX mode
9624 // Sign extend v8i16 to v8i32 and
9627 // Divide input vector into two parts
9628 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9629 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9630 // concat the vectors to original VT
9632 unsigned NumElems = InVT.getVectorNumElements();
9633 SDValue Undef = DAG.getUNDEF(InVT);
9635 SmallVector<int,8> ShufMask1(NumElems, -1);
9636 for (unsigned i = 0; i != NumElems/2; ++i)
9639 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9641 SmallVector<int,8> ShufMask2(NumElems, -1);
9642 for (unsigned i = 0; i != NumElems/2; ++i)
9643 ShufMask2[i] = i + NumElems/2;
9645 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9647 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
9648 VT.getVectorNumElements()/2);
9650 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9651 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9653 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9656 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9657 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9658 // from the AND / OR.
9659 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9660 Opc = Op.getOpcode();
9661 if (Opc != ISD::OR && Opc != ISD::AND)
9663 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9664 Op.getOperand(0).hasOneUse() &&
9665 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9666 Op.getOperand(1).hasOneUse());
9669 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9670 // 1 and that the SETCC node has a single use.
9671 static bool isXor1OfSetCC(SDValue Op) {
9672 if (Op.getOpcode() != ISD::XOR)
9674 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9675 if (N1C && N1C->getAPIntValue() == 1) {
9676 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9677 Op.getOperand(0).hasOneUse();
9682 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9683 bool addTest = true;
9684 SDValue Chain = Op.getOperand(0);
9685 SDValue Cond = Op.getOperand(1);
9686 SDValue Dest = Op.getOperand(2);
9687 DebugLoc dl = Op.getDebugLoc();
9689 bool Inverted = false;
9691 if (Cond.getOpcode() == ISD::SETCC) {
9692 // Check for setcc([su]{add,sub,mul}o == 0).
9693 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9694 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9695 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9696 Cond.getOperand(0).getResNo() == 1 &&
9697 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9698 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9699 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9700 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9701 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9702 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9704 Cond = Cond.getOperand(0);
9706 SDValue NewCond = LowerSETCC(Cond, DAG);
9707 if (NewCond.getNode())
9712 // FIXME: LowerXALUO doesn't handle these!!
9713 else if (Cond.getOpcode() == X86ISD::ADD ||
9714 Cond.getOpcode() == X86ISD::SUB ||
9715 Cond.getOpcode() == X86ISD::SMUL ||
9716 Cond.getOpcode() == X86ISD::UMUL)
9717 Cond = LowerXALUO(Cond, DAG);
9720 // Look pass (and (setcc_carry (cmp ...)), 1).
9721 if (Cond.getOpcode() == ISD::AND &&
9722 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9723 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9724 if (C && C->getAPIntValue() == 1)
9725 Cond = Cond.getOperand(0);
9728 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9729 // setting operand in place of the X86ISD::SETCC.
9730 unsigned CondOpcode = Cond.getOpcode();
9731 if (CondOpcode == X86ISD::SETCC ||
9732 CondOpcode == X86ISD::SETCC_CARRY) {
9733 CC = Cond.getOperand(0);
9735 SDValue Cmp = Cond.getOperand(1);
9736 unsigned Opc = Cmp.getOpcode();
9737 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9738 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9742 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9746 // These can only come from an arithmetic instruction with overflow,
9747 // e.g. SADDO, UADDO.
9748 Cond = Cond.getNode()->getOperand(1);
9754 CondOpcode = Cond.getOpcode();
9755 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9756 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9757 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9758 Cond.getOperand(0).getValueType() != MVT::i8)) {
9759 SDValue LHS = Cond.getOperand(0);
9760 SDValue RHS = Cond.getOperand(1);
9764 switch (CondOpcode) {
9765 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9766 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9767 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9768 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9769 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9770 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9771 default: llvm_unreachable("unexpected overflowing operator");
9774 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9775 if (CondOpcode == ISD::UMULO)
9776 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9779 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9781 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9783 if (CondOpcode == ISD::UMULO)
9784 Cond = X86Op.getValue(2);
9786 Cond = X86Op.getValue(1);
9788 CC = DAG.getConstant(X86Cond, MVT::i8);
9792 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9793 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9794 if (CondOpc == ISD::OR) {
9795 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9796 // two branches instead of an explicit OR instruction with a
9798 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9799 isX86LogicalCmp(Cmp)) {
9800 CC = Cond.getOperand(0).getOperand(0);
9801 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9802 Chain, Dest, CC, Cmp);
9803 CC = Cond.getOperand(1).getOperand(0);
9807 } else { // ISD::AND
9808 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9809 // two branches instead of an explicit AND instruction with a
9810 // separate test. However, we only do this if this block doesn't
9811 // have a fall-through edge, because this requires an explicit
9812 // jmp when the condition is false.
9813 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9814 isX86LogicalCmp(Cmp) &&
9815 Op.getNode()->hasOneUse()) {
9816 X86::CondCode CCode =
9817 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9818 CCode = X86::GetOppositeBranchCondition(CCode);
9819 CC = DAG.getConstant(CCode, MVT::i8);
9820 SDNode *User = *Op.getNode()->use_begin();
9821 // Look for an unconditional branch following this conditional branch.
9822 // We need this because we need to reverse the successors in order
9823 // to implement FCMP_OEQ.
9824 if (User->getOpcode() == ISD::BR) {
9825 SDValue FalseBB = User->getOperand(1);
9827 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9828 assert(NewBR == User);
9832 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9833 Chain, Dest, CC, Cmp);
9834 X86::CondCode CCode =
9835 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9836 CCode = X86::GetOppositeBranchCondition(CCode);
9837 CC = DAG.getConstant(CCode, MVT::i8);
9843 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9844 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9845 // It should be transformed during dag combiner except when the condition
9846 // is set by a arithmetics with overflow node.
9847 X86::CondCode CCode =
9848 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9849 CCode = X86::GetOppositeBranchCondition(CCode);
9850 CC = DAG.getConstant(CCode, MVT::i8);
9851 Cond = Cond.getOperand(0).getOperand(1);
9853 } else if (Cond.getOpcode() == ISD::SETCC &&
9854 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9855 // For FCMP_OEQ, we can emit
9856 // two branches instead of an explicit AND instruction with a
9857 // separate test. However, we only do this if this block doesn't
9858 // have a fall-through edge, because this requires an explicit
9859 // jmp when the condition is false.
9860 if (Op.getNode()->hasOneUse()) {
9861 SDNode *User = *Op.getNode()->use_begin();
9862 // Look for an unconditional branch following this conditional branch.
9863 // We need this because we need to reverse the successors in order
9864 // to implement FCMP_OEQ.
9865 if (User->getOpcode() == ISD::BR) {
9866 SDValue FalseBB = User->getOperand(1);
9868 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9869 assert(NewBR == User);
9873 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9874 Cond.getOperand(0), Cond.getOperand(1));
9875 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9876 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9877 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9878 Chain, Dest, CC, Cmp);
9879 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9884 } else if (Cond.getOpcode() == ISD::SETCC &&
9885 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9886 // For FCMP_UNE, we can emit
9887 // two branches instead of an explicit AND instruction with a
9888 // separate test. However, we only do this if this block doesn't
9889 // have a fall-through edge, because this requires an explicit
9890 // jmp when the condition is false.
9891 if (Op.getNode()->hasOneUse()) {
9892 SDNode *User = *Op.getNode()->use_begin();
9893 // Look for an unconditional branch following this conditional branch.
9894 // We need this because we need to reverse the successors in order
9895 // to implement FCMP_UNE.
9896 if (User->getOpcode() == ISD::BR) {
9897 SDValue FalseBB = User->getOperand(1);
9899 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9900 assert(NewBR == User);
9903 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9904 Cond.getOperand(0), Cond.getOperand(1));
9905 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9906 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9907 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9908 Chain, Dest, CC, Cmp);
9909 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9919 // Look pass the truncate if the high bits are known zero.
9920 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9921 Cond = Cond.getOperand(0);
9923 // We know the result of AND is compared against zero. Try to match
9925 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9926 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9927 if (NewSetCC.getNode()) {
9928 CC = NewSetCC.getOperand(0);
9929 Cond = NewSetCC.getOperand(1);
9936 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9937 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9939 Cond = ConvertCmpIfNecessary(Cond, DAG);
9940 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9941 Chain, Dest, CC, Cond);
9944 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9945 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9946 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9947 // that the guard pages used by the OS virtual memory manager are allocated in
9948 // correct sequence.
9950 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9951 SelectionDAG &DAG) const {
9952 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9953 getTargetMachine().Options.EnableSegmentedStacks) &&
9954 "This should be used only on Windows targets or when segmented stacks "
9956 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9957 DebugLoc dl = Op.getDebugLoc();
9960 SDValue Chain = Op.getOperand(0);
9961 SDValue Size = Op.getOperand(1);
9962 // FIXME: Ensure alignment here
9964 bool Is64Bit = Subtarget->is64Bit();
9965 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9967 if (getTargetMachine().Options.EnableSegmentedStacks) {
9968 MachineFunction &MF = DAG.getMachineFunction();
9969 MachineRegisterInfo &MRI = MF.getRegInfo();
9972 // The 64 bit implementation of segmented stacks needs to clobber both r10
9973 // r11. This makes it impossible to use it along with nested parameters.
9974 const Function *F = MF.getFunction();
9976 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9978 if (I->hasNestAttr())
9979 report_fatal_error("Cannot use segmented stacks with functions that "
9980 "have nested arguments.");
9983 const TargetRegisterClass *AddrRegClass =
9984 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9985 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9986 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9987 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9988 DAG.getRegister(Vreg, SPTy));
9989 SDValue Ops1[2] = { Value, Chain };
9990 return DAG.getMergeValues(Ops1, 2, dl);
9993 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9995 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9996 Flag = Chain.getValue(1);
9997 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9999 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10000 Flag = Chain.getValue(1);
10002 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10005 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10006 return DAG.getMergeValues(Ops1, 2, dl);
10010 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10011 MachineFunction &MF = DAG.getMachineFunction();
10012 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10014 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10015 DebugLoc DL = Op.getDebugLoc();
10017 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10018 // vastart just stores the address of the VarArgsFrameIndex slot into the
10019 // memory location argument.
10020 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10022 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10023 MachinePointerInfo(SV), false, false, 0);
10027 // gp_offset (0 - 6 * 8)
10028 // fp_offset (48 - 48 + 8 * 16)
10029 // overflow_arg_area (point to parameters coming in memory).
10031 SmallVector<SDValue, 8> MemOps;
10032 SDValue FIN = Op.getOperand(1);
10034 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10035 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10037 FIN, MachinePointerInfo(SV), false, false, 0);
10038 MemOps.push_back(Store);
10041 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10042 FIN, DAG.getIntPtrConstant(4));
10043 Store = DAG.getStore(Op.getOperand(0), DL,
10044 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10046 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10047 MemOps.push_back(Store);
10049 // Store ptr to overflow_arg_area
10050 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10051 FIN, DAG.getIntPtrConstant(4));
10052 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10054 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10055 MachinePointerInfo(SV, 8),
10057 MemOps.push_back(Store);
10059 // Store ptr to reg_save_area.
10060 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10061 FIN, DAG.getIntPtrConstant(8));
10062 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10064 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10065 MachinePointerInfo(SV, 16), false, false, 0);
10066 MemOps.push_back(Store);
10067 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10068 &MemOps[0], MemOps.size());
10071 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10072 assert(Subtarget->is64Bit() &&
10073 "LowerVAARG only handles 64-bit va_arg!");
10074 assert((Subtarget->isTargetLinux() ||
10075 Subtarget->isTargetDarwin()) &&
10076 "Unhandled target in LowerVAARG");
10077 assert(Op.getNode()->getNumOperands() == 4);
10078 SDValue Chain = Op.getOperand(0);
10079 SDValue SrcPtr = Op.getOperand(1);
10080 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10081 unsigned Align = Op.getConstantOperandVal(3);
10082 DebugLoc dl = Op.getDebugLoc();
10084 EVT ArgVT = Op.getNode()->getValueType(0);
10085 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10086 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10089 // Decide which area this value should be read from.
10090 // TODO: Implement the AMD64 ABI in its entirety. This simple
10091 // selection mechanism works only for the basic types.
10092 if (ArgVT == MVT::f80) {
10093 llvm_unreachable("va_arg for f80 not yet implemented");
10094 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10095 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10096 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10097 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10099 llvm_unreachable("Unhandled argument type in LowerVAARG");
10102 if (ArgMode == 2) {
10103 // Sanity Check: Make sure using fp_offset makes sense.
10104 assert(!getTargetMachine().Options.UseSoftFloat &&
10105 !(DAG.getMachineFunction()
10106 .getFunction()->getFnAttributes()
10107 .hasAttribute(Attribute::NoImplicitFloat)) &&
10108 Subtarget->hasSSE1());
10111 // Insert VAARG_64 node into the DAG
10112 // VAARG_64 returns two values: Variable Argument Address, Chain
10113 SmallVector<SDValue, 11> InstOps;
10114 InstOps.push_back(Chain);
10115 InstOps.push_back(SrcPtr);
10116 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10117 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10118 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10119 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10120 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10121 VTs, &InstOps[0], InstOps.size(),
10123 MachinePointerInfo(SV),
10125 /*Volatile=*/false,
10127 /*WriteMem=*/true);
10128 Chain = VAARG.getValue(1);
10130 // Load the next argument and return it
10131 return DAG.getLoad(ArgVT, dl,
10134 MachinePointerInfo(),
10135 false, false, false, 0);
10138 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10139 SelectionDAG &DAG) {
10140 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10141 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10142 SDValue Chain = Op.getOperand(0);
10143 SDValue DstPtr = Op.getOperand(1);
10144 SDValue SrcPtr = Op.getOperand(2);
10145 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10146 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10147 DebugLoc DL = Op.getDebugLoc();
10149 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10150 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10152 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10155 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
10156 // may or may not be a constant. Takes immediate version of shift as input.
10157 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10158 SDValue SrcOp, SDValue ShAmt,
10159 SelectionDAG &DAG) {
10160 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10162 if (isa<ConstantSDNode>(ShAmt)) {
10163 // Constant may be a TargetConstant. Use a regular constant.
10164 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10166 default: llvm_unreachable("Unknown target vector shift node");
10167 case X86ISD::VSHLI:
10168 case X86ISD::VSRLI:
10169 case X86ISD::VSRAI:
10170 return DAG.getNode(Opc, dl, VT, SrcOp,
10171 DAG.getConstant(ShiftAmt, MVT::i32));
10175 // Change opcode to non-immediate version
10177 default: llvm_unreachable("Unknown target vector shift node");
10178 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10179 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10180 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10183 // Need to build a vector containing shift amount
10184 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10187 ShOps[1] = DAG.getConstant(0, MVT::i32);
10188 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10189 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10191 // The return type has to be a 128-bit type with the same element
10192 // type as the input type.
10193 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10194 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10196 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10197 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10200 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10201 DebugLoc dl = Op.getDebugLoc();
10202 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10204 default: return SDValue(); // Don't custom lower most intrinsics.
10205 // Comparison intrinsics.
10206 case Intrinsic::x86_sse_comieq_ss:
10207 case Intrinsic::x86_sse_comilt_ss:
10208 case Intrinsic::x86_sse_comile_ss:
10209 case Intrinsic::x86_sse_comigt_ss:
10210 case Intrinsic::x86_sse_comige_ss:
10211 case Intrinsic::x86_sse_comineq_ss:
10212 case Intrinsic::x86_sse_ucomieq_ss:
10213 case Intrinsic::x86_sse_ucomilt_ss:
10214 case Intrinsic::x86_sse_ucomile_ss:
10215 case Intrinsic::x86_sse_ucomigt_ss:
10216 case Intrinsic::x86_sse_ucomige_ss:
10217 case Intrinsic::x86_sse_ucomineq_ss:
10218 case Intrinsic::x86_sse2_comieq_sd:
10219 case Intrinsic::x86_sse2_comilt_sd:
10220 case Intrinsic::x86_sse2_comile_sd:
10221 case Intrinsic::x86_sse2_comigt_sd:
10222 case Intrinsic::x86_sse2_comige_sd:
10223 case Intrinsic::x86_sse2_comineq_sd:
10224 case Intrinsic::x86_sse2_ucomieq_sd:
10225 case Intrinsic::x86_sse2_ucomilt_sd:
10226 case Intrinsic::x86_sse2_ucomile_sd:
10227 case Intrinsic::x86_sse2_ucomigt_sd:
10228 case Intrinsic::x86_sse2_ucomige_sd:
10229 case Intrinsic::x86_sse2_ucomineq_sd: {
10233 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10234 case Intrinsic::x86_sse_comieq_ss:
10235 case Intrinsic::x86_sse2_comieq_sd:
10236 Opc = X86ISD::COMI;
10239 case Intrinsic::x86_sse_comilt_ss:
10240 case Intrinsic::x86_sse2_comilt_sd:
10241 Opc = X86ISD::COMI;
10244 case Intrinsic::x86_sse_comile_ss:
10245 case Intrinsic::x86_sse2_comile_sd:
10246 Opc = X86ISD::COMI;
10249 case Intrinsic::x86_sse_comigt_ss:
10250 case Intrinsic::x86_sse2_comigt_sd:
10251 Opc = X86ISD::COMI;
10254 case Intrinsic::x86_sse_comige_ss:
10255 case Intrinsic::x86_sse2_comige_sd:
10256 Opc = X86ISD::COMI;
10259 case Intrinsic::x86_sse_comineq_ss:
10260 case Intrinsic::x86_sse2_comineq_sd:
10261 Opc = X86ISD::COMI;
10264 case Intrinsic::x86_sse_ucomieq_ss:
10265 case Intrinsic::x86_sse2_ucomieq_sd:
10266 Opc = X86ISD::UCOMI;
10269 case Intrinsic::x86_sse_ucomilt_ss:
10270 case Intrinsic::x86_sse2_ucomilt_sd:
10271 Opc = X86ISD::UCOMI;
10274 case Intrinsic::x86_sse_ucomile_ss:
10275 case Intrinsic::x86_sse2_ucomile_sd:
10276 Opc = X86ISD::UCOMI;
10279 case Intrinsic::x86_sse_ucomigt_ss:
10280 case Intrinsic::x86_sse2_ucomigt_sd:
10281 Opc = X86ISD::UCOMI;
10284 case Intrinsic::x86_sse_ucomige_ss:
10285 case Intrinsic::x86_sse2_ucomige_sd:
10286 Opc = X86ISD::UCOMI;
10289 case Intrinsic::x86_sse_ucomineq_ss:
10290 case Intrinsic::x86_sse2_ucomineq_sd:
10291 Opc = X86ISD::UCOMI;
10296 SDValue LHS = Op.getOperand(1);
10297 SDValue RHS = Op.getOperand(2);
10298 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10299 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10300 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10301 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10302 DAG.getConstant(X86CC, MVT::i8), Cond);
10303 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10306 // Arithmetic intrinsics.
10307 case Intrinsic::x86_sse2_pmulu_dq:
10308 case Intrinsic::x86_avx2_pmulu_dq:
10309 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10310 Op.getOperand(1), Op.getOperand(2));
10312 // SSE2/AVX2 sub with unsigned saturation intrinsics
10313 case Intrinsic::x86_sse2_psubus_b:
10314 case Intrinsic::x86_sse2_psubus_w:
10315 case Intrinsic::x86_avx2_psubus_b:
10316 case Intrinsic::x86_avx2_psubus_w:
10317 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10318 Op.getOperand(1), Op.getOperand(2));
10320 // SSE3/AVX horizontal add/sub intrinsics
10321 case Intrinsic::x86_sse3_hadd_ps:
10322 case Intrinsic::x86_sse3_hadd_pd:
10323 case Intrinsic::x86_avx_hadd_ps_256:
10324 case Intrinsic::x86_avx_hadd_pd_256:
10325 case Intrinsic::x86_sse3_hsub_ps:
10326 case Intrinsic::x86_sse3_hsub_pd:
10327 case Intrinsic::x86_avx_hsub_ps_256:
10328 case Intrinsic::x86_avx_hsub_pd_256:
10329 case Intrinsic::x86_ssse3_phadd_w_128:
10330 case Intrinsic::x86_ssse3_phadd_d_128:
10331 case Intrinsic::x86_avx2_phadd_w:
10332 case Intrinsic::x86_avx2_phadd_d:
10333 case Intrinsic::x86_ssse3_phsub_w_128:
10334 case Intrinsic::x86_ssse3_phsub_d_128:
10335 case Intrinsic::x86_avx2_phsub_w:
10336 case Intrinsic::x86_avx2_phsub_d: {
10339 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10340 case Intrinsic::x86_sse3_hadd_ps:
10341 case Intrinsic::x86_sse3_hadd_pd:
10342 case Intrinsic::x86_avx_hadd_ps_256:
10343 case Intrinsic::x86_avx_hadd_pd_256:
10344 Opcode = X86ISD::FHADD;
10346 case Intrinsic::x86_sse3_hsub_ps:
10347 case Intrinsic::x86_sse3_hsub_pd:
10348 case Intrinsic::x86_avx_hsub_ps_256:
10349 case Intrinsic::x86_avx_hsub_pd_256:
10350 Opcode = X86ISD::FHSUB;
10352 case Intrinsic::x86_ssse3_phadd_w_128:
10353 case Intrinsic::x86_ssse3_phadd_d_128:
10354 case Intrinsic::x86_avx2_phadd_w:
10355 case Intrinsic::x86_avx2_phadd_d:
10356 Opcode = X86ISD::HADD;
10358 case Intrinsic::x86_ssse3_phsub_w_128:
10359 case Intrinsic::x86_ssse3_phsub_d_128:
10360 case Intrinsic::x86_avx2_phsub_w:
10361 case Intrinsic::x86_avx2_phsub_d:
10362 Opcode = X86ISD::HSUB;
10365 return DAG.getNode(Opcode, dl, Op.getValueType(),
10366 Op.getOperand(1), Op.getOperand(2));
10369 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10370 case Intrinsic::x86_sse2_pmaxu_b:
10371 case Intrinsic::x86_sse41_pmaxuw:
10372 case Intrinsic::x86_sse41_pmaxud:
10373 case Intrinsic::x86_avx2_pmaxu_b:
10374 case Intrinsic::x86_avx2_pmaxu_w:
10375 case Intrinsic::x86_avx2_pmaxu_d:
10376 case Intrinsic::x86_sse2_pminu_b:
10377 case Intrinsic::x86_sse41_pminuw:
10378 case Intrinsic::x86_sse41_pminud:
10379 case Intrinsic::x86_avx2_pminu_b:
10380 case Intrinsic::x86_avx2_pminu_w:
10381 case Intrinsic::x86_avx2_pminu_d:
10382 case Intrinsic::x86_sse41_pmaxsb:
10383 case Intrinsic::x86_sse2_pmaxs_w:
10384 case Intrinsic::x86_sse41_pmaxsd:
10385 case Intrinsic::x86_avx2_pmaxs_b:
10386 case Intrinsic::x86_avx2_pmaxs_w:
10387 case Intrinsic::x86_avx2_pmaxs_d:
10388 case Intrinsic::x86_sse41_pminsb:
10389 case Intrinsic::x86_sse2_pmins_w:
10390 case Intrinsic::x86_sse41_pminsd:
10391 case Intrinsic::x86_avx2_pmins_b:
10392 case Intrinsic::x86_avx2_pmins_w:
10393 case Intrinsic::x86_avx2_pmins_d: {
10396 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10397 case Intrinsic::x86_sse2_pmaxu_b:
10398 case Intrinsic::x86_sse41_pmaxuw:
10399 case Intrinsic::x86_sse41_pmaxud:
10400 case Intrinsic::x86_avx2_pmaxu_b:
10401 case Intrinsic::x86_avx2_pmaxu_w:
10402 case Intrinsic::x86_avx2_pmaxu_d:
10403 Opcode = X86ISD::UMAX;
10405 case Intrinsic::x86_sse2_pminu_b:
10406 case Intrinsic::x86_sse41_pminuw:
10407 case Intrinsic::x86_sse41_pminud:
10408 case Intrinsic::x86_avx2_pminu_b:
10409 case Intrinsic::x86_avx2_pminu_w:
10410 case Intrinsic::x86_avx2_pminu_d:
10411 Opcode = X86ISD::UMIN;
10413 case Intrinsic::x86_sse41_pmaxsb:
10414 case Intrinsic::x86_sse2_pmaxs_w:
10415 case Intrinsic::x86_sse41_pmaxsd:
10416 case Intrinsic::x86_avx2_pmaxs_b:
10417 case Intrinsic::x86_avx2_pmaxs_w:
10418 case Intrinsic::x86_avx2_pmaxs_d:
10419 Opcode = X86ISD::SMAX;
10421 case Intrinsic::x86_sse41_pminsb:
10422 case Intrinsic::x86_sse2_pmins_w:
10423 case Intrinsic::x86_sse41_pminsd:
10424 case Intrinsic::x86_avx2_pmins_b:
10425 case Intrinsic::x86_avx2_pmins_w:
10426 case Intrinsic::x86_avx2_pmins_d:
10427 Opcode = X86ISD::SMIN;
10430 return DAG.getNode(Opcode, dl, Op.getValueType(),
10431 Op.getOperand(1), Op.getOperand(2));
10434 // SSE/SSE2/AVX floating point max/min intrinsics.
10435 case Intrinsic::x86_sse_max_ps:
10436 case Intrinsic::x86_sse2_max_pd:
10437 case Intrinsic::x86_avx_max_ps_256:
10438 case Intrinsic::x86_avx_max_pd_256:
10439 case Intrinsic::x86_sse_min_ps:
10440 case Intrinsic::x86_sse2_min_pd:
10441 case Intrinsic::x86_avx_min_ps_256:
10442 case Intrinsic::x86_avx_min_pd_256: {
10445 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10446 case Intrinsic::x86_sse_max_ps:
10447 case Intrinsic::x86_sse2_max_pd:
10448 case Intrinsic::x86_avx_max_ps_256:
10449 case Intrinsic::x86_avx_max_pd_256:
10450 Opcode = X86ISD::FMAX;
10452 case Intrinsic::x86_sse_min_ps:
10453 case Intrinsic::x86_sse2_min_pd:
10454 case Intrinsic::x86_avx_min_ps_256:
10455 case Intrinsic::x86_avx_min_pd_256:
10456 Opcode = X86ISD::FMIN;
10459 return DAG.getNode(Opcode, dl, Op.getValueType(),
10460 Op.getOperand(1), Op.getOperand(2));
10463 // AVX2 variable shift intrinsics
10464 case Intrinsic::x86_avx2_psllv_d:
10465 case Intrinsic::x86_avx2_psllv_q:
10466 case Intrinsic::x86_avx2_psllv_d_256:
10467 case Intrinsic::x86_avx2_psllv_q_256:
10468 case Intrinsic::x86_avx2_psrlv_d:
10469 case Intrinsic::x86_avx2_psrlv_q:
10470 case Intrinsic::x86_avx2_psrlv_d_256:
10471 case Intrinsic::x86_avx2_psrlv_q_256:
10472 case Intrinsic::x86_avx2_psrav_d:
10473 case Intrinsic::x86_avx2_psrav_d_256: {
10476 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10477 case Intrinsic::x86_avx2_psllv_d:
10478 case Intrinsic::x86_avx2_psllv_q:
10479 case Intrinsic::x86_avx2_psllv_d_256:
10480 case Intrinsic::x86_avx2_psllv_q_256:
10483 case Intrinsic::x86_avx2_psrlv_d:
10484 case Intrinsic::x86_avx2_psrlv_q:
10485 case Intrinsic::x86_avx2_psrlv_d_256:
10486 case Intrinsic::x86_avx2_psrlv_q_256:
10489 case Intrinsic::x86_avx2_psrav_d:
10490 case Intrinsic::x86_avx2_psrav_d_256:
10494 return DAG.getNode(Opcode, dl, Op.getValueType(),
10495 Op.getOperand(1), Op.getOperand(2));
10498 case Intrinsic::x86_ssse3_pshuf_b_128:
10499 case Intrinsic::x86_avx2_pshuf_b:
10500 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10501 Op.getOperand(1), Op.getOperand(2));
10503 case Intrinsic::x86_ssse3_psign_b_128:
10504 case Intrinsic::x86_ssse3_psign_w_128:
10505 case Intrinsic::x86_ssse3_psign_d_128:
10506 case Intrinsic::x86_avx2_psign_b:
10507 case Intrinsic::x86_avx2_psign_w:
10508 case Intrinsic::x86_avx2_psign_d:
10509 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10510 Op.getOperand(1), Op.getOperand(2));
10512 case Intrinsic::x86_sse41_insertps:
10513 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10514 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10516 case Intrinsic::x86_avx_vperm2f128_ps_256:
10517 case Intrinsic::x86_avx_vperm2f128_pd_256:
10518 case Intrinsic::x86_avx_vperm2f128_si_256:
10519 case Intrinsic::x86_avx2_vperm2i128:
10520 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10521 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10523 case Intrinsic::x86_avx2_permd:
10524 case Intrinsic::x86_avx2_permps:
10525 // Operands intentionally swapped. Mask is last operand to intrinsic,
10526 // but second operand for node/intruction.
10527 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10528 Op.getOperand(2), Op.getOperand(1));
10530 case Intrinsic::x86_sse_sqrt_ps:
10531 case Intrinsic::x86_sse2_sqrt_pd:
10532 case Intrinsic::x86_avx_sqrt_ps_256:
10533 case Intrinsic::x86_avx_sqrt_pd_256:
10534 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10536 // ptest and testp intrinsics. The intrinsic these come from are designed to
10537 // return an integer value, not just an instruction so lower it to the ptest
10538 // or testp pattern and a setcc for the result.
10539 case Intrinsic::x86_sse41_ptestz:
10540 case Intrinsic::x86_sse41_ptestc:
10541 case Intrinsic::x86_sse41_ptestnzc:
10542 case Intrinsic::x86_avx_ptestz_256:
10543 case Intrinsic::x86_avx_ptestc_256:
10544 case Intrinsic::x86_avx_ptestnzc_256:
10545 case Intrinsic::x86_avx_vtestz_ps:
10546 case Intrinsic::x86_avx_vtestc_ps:
10547 case Intrinsic::x86_avx_vtestnzc_ps:
10548 case Intrinsic::x86_avx_vtestz_pd:
10549 case Intrinsic::x86_avx_vtestc_pd:
10550 case Intrinsic::x86_avx_vtestnzc_pd:
10551 case Intrinsic::x86_avx_vtestz_ps_256:
10552 case Intrinsic::x86_avx_vtestc_ps_256:
10553 case Intrinsic::x86_avx_vtestnzc_ps_256:
10554 case Intrinsic::x86_avx_vtestz_pd_256:
10555 case Intrinsic::x86_avx_vtestc_pd_256:
10556 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10557 bool IsTestPacked = false;
10560 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10561 case Intrinsic::x86_avx_vtestz_ps:
10562 case Intrinsic::x86_avx_vtestz_pd:
10563 case Intrinsic::x86_avx_vtestz_ps_256:
10564 case Intrinsic::x86_avx_vtestz_pd_256:
10565 IsTestPacked = true; // Fallthrough
10566 case Intrinsic::x86_sse41_ptestz:
10567 case Intrinsic::x86_avx_ptestz_256:
10569 X86CC = X86::COND_E;
10571 case Intrinsic::x86_avx_vtestc_ps:
10572 case Intrinsic::x86_avx_vtestc_pd:
10573 case Intrinsic::x86_avx_vtestc_ps_256:
10574 case Intrinsic::x86_avx_vtestc_pd_256:
10575 IsTestPacked = true; // Fallthrough
10576 case Intrinsic::x86_sse41_ptestc:
10577 case Intrinsic::x86_avx_ptestc_256:
10579 X86CC = X86::COND_B;
10581 case Intrinsic::x86_avx_vtestnzc_ps:
10582 case Intrinsic::x86_avx_vtestnzc_pd:
10583 case Intrinsic::x86_avx_vtestnzc_ps_256:
10584 case Intrinsic::x86_avx_vtestnzc_pd_256:
10585 IsTestPacked = true; // Fallthrough
10586 case Intrinsic::x86_sse41_ptestnzc:
10587 case Intrinsic::x86_avx_ptestnzc_256:
10589 X86CC = X86::COND_A;
10593 SDValue LHS = Op.getOperand(1);
10594 SDValue RHS = Op.getOperand(2);
10595 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10596 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10597 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10598 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10599 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10602 // SSE/AVX shift intrinsics
10603 case Intrinsic::x86_sse2_psll_w:
10604 case Intrinsic::x86_sse2_psll_d:
10605 case Intrinsic::x86_sse2_psll_q:
10606 case Intrinsic::x86_avx2_psll_w:
10607 case Intrinsic::x86_avx2_psll_d:
10608 case Intrinsic::x86_avx2_psll_q:
10609 case Intrinsic::x86_sse2_psrl_w:
10610 case Intrinsic::x86_sse2_psrl_d:
10611 case Intrinsic::x86_sse2_psrl_q:
10612 case Intrinsic::x86_avx2_psrl_w:
10613 case Intrinsic::x86_avx2_psrl_d:
10614 case Intrinsic::x86_avx2_psrl_q:
10615 case Intrinsic::x86_sse2_psra_w:
10616 case Intrinsic::x86_sse2_psra_d:
10617 case Intrinsic::x86_avx2_psra_w:
10618 case Intrinsic::x86_avx2_psra_d: {
10621 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10622 case Intrinsic::x86_sse2_psll_w:
10623 case Intrinsic::x86_sse2_psll_d:
10624 case Intrinsic::x86_sse2_psll_q:
10625 case Intrinsic::x86_avx2_psll_w:
10626 case Intrinsic::x86_avx2_psll_d:
10627 case Intrinsic::x86_avx2_psll_q:
10628 Opcode = X86ISD::VSHL;
10630 case Intrinsic::x86_sse2_psrl_w:
10631 case Intrinsic::x86_sse2_psrl_d:
10632 case Intrinsic::x86_sse2_psrl_q:
10633 case Intrinsic::x86_avx2_psrl_w:
10634 case Intrinsic::x86_avx2_psrl_d:
10635 case Intrinsic::x86_avx2_psrl_q:
10636 Opcode = X86ISD::VSRL;
10638 case Intrinsic::x86_sse2_psra_w:
10639 case Intrinsic::x86_sse2_psra_d:
10640 case Intrinsic::x86_avx2_psra_w:
10641 case Intrinsic::x86_avx2_psra_d:
10642 Opcode = X86ISD::VSRA;
10645 return DAG.getNode(Opcode, dl, Op.getValueType(),
10646 Op.getOperand(1), Op.getOperand(2));
10649 // SSE/AVX immediate shift intrinsics
10650 case Intrinsic::x86_sse2_pslli_w:
10651 case Intrinsic::x86_sse2_pslli_d:
10652 case Intrinsic::x86_sse2_pslli_q:
10653 case Intrinsic::x86_avx2_pslli_w:
10654 case Intrinsic::x86_avx2_pslli_d:
10655 case Intrinsic::x86_avx2_pslli_q:
10656 case Intrinsic::x86_sse2_psrli_w:
10657 case Intrinsic::x86_sse2_psrli_d:
10658 case Intrinsic::x86_sse2_psrli_q:
10659 case Intrinsic::x86_avx2_psrli_w:
10660 case Intrinsic::x86_avx2_psrli_d:
10661 case Intrinsic::x86_avx2_psrli_q:
10662 case Intrinsic::x86_sse2_psrai_w:
10663 case Intrinsic::x86_sse2_psrai_d:
10664 case Intrinsic::x86_avx2_psrai_w:
10665 case Intrinsic::x86_avx2_psrai_d: {
10668 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10669 case Intrinsic::x86_sse2_pslli_w:
10670 case Intrinsic::x86_sse2_pslli_d:
10671 case Intrinsic::x86_sse2_pslli_q:
10672 case Intrinsic::x86_avx2_pslli_w:
10673 case Intrinsic::x86_avx2_pslli_d:
10674 case Intrinsic::x86_avx2_pslli_q:
10675 Opcode = X86ISD::VSHLI;
10677 case Intrinsic::x86_sse2_psrli_w:
10678 case Intrinsic::x86_sse2_psrli_d:
10679 case Intrinsic::x86_sse2_psrli_q:
10680 case Intrinsic::x86_avx2_psrli_w:
10681 case Intrinsic::x86_avx2_psrli_d:
10682 case Intrinsic::x86_avx2_psrli_q:
10683 Opcode = X86ISD::VSRLI;
10685 case Intrinsic::x86_sse2_psrai_w:
10686 case Intrinsic::x86_sse2_psrai_d:
10687 case Intrinsic::x86_avx2_psrai_w:
10688 case Intrinsic::x86_avx2_psrai_d:
10689 Opcode = X86ISD::VSRAI;
10692 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10693 Op.getOperand(1), Op.getOperand(2), DAG);
10696 case Intrinsic::x86_sse42_pcmpistria128:
10697 case Intrinsic::x86_sse42_pcmpestria128:
10698 case Intrinsic::x86_sse42_pcmpistric128:
10699 case Intrinsic::x86_sse42_pcmpestric128:
10700 case Intrinsic::x86_sse42_pcmpistrio128:
10701 case Intrinsic::x86_sse42_pcmpestrio128:
10702 case Intrinsic::x86_sse42_pcmpistris128:
10703 case Intrinsic::x86_sse42_pcmpestris128:
10704 case Intrinsic::x86_sse42_pcmpistriz128:
10705 case Intrinsic::x86_sse42_pcmpestriz128: {
10709 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10710 case Intrinsic::x86_sse42_pcmpistria128:
10711 Opcode = X86ISD::PCMPISTRI;
10712 X86CC = X86::COND_A;
10714 case Intrinsic::x86_sse42_pcmpestria128:
10715 Opcode = X86ISD::PCMPESTRI;
10716 X86CC = X86::COND_A;
10718 case Intrinsic::x86_sse42_pcmpistric128:
10719 Opcode = X86ISD::PCMPISTRI;
10720 X86CC = X86::COND_B;
10722 case Intrinsic::x86_sse42_pcmpestric128:
10723 Opcode = X86ISD::PCMPESTRI;
10724 X86CC = X86::COND_B;
10726 case Intrinsic::x86_sse42_pcmpistrio128:
10727 Opcode = X86ISD::PCMPISTRI;
10728 X86CC = X86::COND_O;
10730 case Intrinsic::x86_sse42_pcmpestrio128:
10731 Opcode = X86ISD::PCMPESTRI;
10732 X86CC = X86::COND_O;
10734 case Intrinsic::x86_sse42_pcmpistris128:
10735 Opcode = X86ISD::PCMPISTRI;
10736 X86CC = X86::COND_S;
10738 case Intrinsic::x86_sse42_pcmpestris128:
10739 Opcode = X86ISD::PCMPESTRI;
10740 X86CC = X86::COND_S;
10742 case Intrinsic::x86_sse42_pcmpistriz128:
10743 Opcode = X86ISD::PCMPISTRI;
10744 X86CC = X86::COND_E;
10746 case Intrinsic::x86_sse42_pcmpestriz128:
10747 Opcode = X86ISD::PCMPESTRI;
10748 X86CC = X86::COND_E;
10751 SmallVector<SDValue, 5> NewOps;
10752 NewOps.append(Op->op_begin()+1, Op->op_end());
10753 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10754 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10755 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10756 DAG.getConstant(X86CC, MVT::i8),
10757 SDValue(PCMP.getNode(), 1));
10758 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10761 case Intrinsic::x86_sse42_pcmpistri128:
10762 case Intrinsic::x86_sse42_pcmpestri128: {
10764 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10765 Opcode = X86ISD::PCMPISTRI;
10767 Opcode = X86ISD::PCMPESTRI;
10769 SmallVector<SDValue, 5> NewOps;
10770 NewOps.append(Op->op_begin()+1, Op->op_end());
10771 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10772 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10774 case Intrinsic::x86_fma_vfmadd_ps:
10775 case Intrinsic::x86_fma_vfmadd_pd:
10776 case Intrinsic::x86_fma_vfmsub_ps:
10777 case Intrinsic::x86_fma_vfmsub_pd:
10778 case Intrinsic::x86_fma_vfnmadd_ps:
10779 case Intrinsic::x86_fma_vfnmadd_pd:
10780 case Intrinsic::x86_fma_vfnmsub_ps:
10781 case Intrinsic::x86_fma_vfnmsub_pd:
10782 case Intrinsic::x86_fma_vfmaddsub_ps:
10783 case Intrinsic::x86_fma_vfmaddsub_pd:
10784 case Intrinsic::x86_fma_vfmsubadd_ps:
10785 case Intrinsic::x86_fma_vfmsubadd_pd:
10786 case Intrinsic::x86_fma_vfmadd_ps_256:
10787 case Intrinsic::x86_fma_vfmadd_pd_256:
10788 case Intrinsic::x86_fma_vfmsub_ps_256:
10789 case Intrinsic::x86_fma_vfmsub_pd_256:
10790 case Intrinsic::x86_fma_vfnmadd_ps_256:
10791 case Intrinsic::x86_fma_vfnmadd_pd_256:
10792 case Intrinsic::x86_fma_vfnmsub_ps_256:
10793 case Intrinsic::x86_fma_vfnmsub_pd_256:
10794 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10795 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10796 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10797 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10800 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10801 case Intrinsic::x86_fma_vfmadd_ps:
10802 case Intrinsic::x86_fma_vfmadd_pd:
10803 case Intrinsic::x86_fma_vfmadd_ps_256:
10804 case Intrinsic::x86_fma_vfmadd_pd_256:
10805 Opc = X86ISD::FMADD;
10807 case Intrinsic::x86_fma_vfmsub_ps:
10808 case Intrinsic::x86_fma_vfmsub_pd:
10809 case Intrinsic::x86_fma_vfmsub_ps_256:
10810 case Intrinsic::x86_fma_vfmsub_pd_256:
10811 Opc = X86ISD::FMSUB;
10813 case Intrinsic::x86_fma_vfnmadd_ps:
10814 case Intrinsic::x86_fma_vfnmadd_pd:
10815 case Intrinsic::x86_fma_vfnmadd_ps_256:
10816 case Intrinsic::x86_fma_vfnmadd_pd_256:
10817 Opc = X86ISD::FNMADD;
10819 case Intrinsic::x86_fma_vfnmsub_ps:
10820 case Intrinsic::x86_fma_vfnmsub_pd:
10821 case Intrinsic::x86_fma_vfnmsub_ps_256:
10822 case Intrinsic::x86_fma_vfnmsub_pd_256:
10823 Opc = X86ISD::FNMSUB;
10825 case Intrinsic::x86_fma_vfmaddsub_ps:
10826 case Intrinsic::x86_fma_vfmaddsub_pd:
10827 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10828 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10829 Opc = X86ISD::FMADDSUB;
10831 case Intrinsic::x86_fma_vfmsubadd_ps:
10832 case Intrinsic::x86_fma_vfmsubadd_pd:
10833 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10834 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10835 Opc = X86ISD::FMSUBADD;
10839 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10840 Op.getOperand(2), Op.getOperand(3));
10845 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10846 DebugLoc dl = Op.getDebugLoc();
10847 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10849 default: return SDValue(); // Don't custom lower most intrinsics.
10851 // RDRAND intrinsics.
10852 case Intrinsic::x86_rdrand_16:
10853 case Intrinsic::x86_rdrand_32:
10854 case Intrinsic::x86_rdrand_64: {
10855 // Emit the node with the right value type.
10856 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10857 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10859 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10860 // return the value from Rand, which is always 0, casted to i32.
10861 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10862 DAG.getConstant(1, Op->getValueType(1)),
10863 DAG.getConstant(X86::COND_B, MVT::i32),
10864 SDValue(Result.getNode(), 1) };
10865 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10866 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10869 // Return { result, isValid, chain }.
10870 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10871 SDValue(Result.getNode(), 2));
10876 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10877 SelectionDAG &DAG) const {
10878 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10879 MFI->setReturnAddressIsTaken(true);
10881 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10882 DebugLoc dl = Op.getDebugLoc();
10883 EVT PtrVT = getPointerTy();
10886 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10888 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10889 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10890 DAG.getNode(ISD::ADD, dl, PtrVT,
10891 FrameAddr, Offset),
10892 MachinePointerInfo(), false, false, false, 0);
10895 // Just load the return address.
10896 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10897 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10898 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10901 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10902 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10903 MFI->setFrameAddressIsTaken(true);
10905 EVT VT = Op.getValueType();
10906 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10907 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10908 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10909 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10911 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10912 MachinePointerInfo(),
10913 false, false, false, 0);
10917 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10918 SelectionDAG &DAG) const {
10919 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10922 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10923 SDValue Chain = Op.getOperand(0);
10924 SDValue Offset = Op.getOperand(1);
10925 SDValue Handler = Op.getOperand(2);
10926 DebugLoc dl = Op.getDebugLoc();
10928 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10929 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10931 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10933 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10934 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10935 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10936 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10938 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10940 return DAG.getNode(X86ISD::EH_RETURN, dl,
10942 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10945 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10946 SelectionDAG &DAG) const {
10947 DebugLoc DL = Op.getDebugLoc();
10948 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10949 DAG.getVTList(MVT::i32, MVT::Other),
10950 Op.getOperand(0), Op.getOperand(1));
10953 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10954 SelectionDAG &DAG) const {
10955 DebugLoc DL = Op.getDebugLoc();
10956 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10957 Op.getOperand(0), Op.getOperand(1));
10960 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10961 return Op.getOperand(0);
10964 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10965 SelectionDAG &DAG) const {
10966 SDValue Root = Op.getOperand(0);
10967 SDValue Trmp = Op.getOperand(1); // trampoline
10968 SDValue FPtr = Op.getOperand(2); // nested function
10969 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10970 DebugLoc dl = Op.getDebugLoc();
10972 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10973 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10975 if (Subtarget->is64Bit()) {
10976 SDValue OutChains[6];
10978 // Large code-model.
10979 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10980 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10982 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10983 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10985 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10987 // Load the pointer to the nested function into R11.
10988 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10989 SDValue Addr = Trmp;
10990 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10991 Addr, MachinePointerInfo(TrmpAddr),
10994 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10995 DAG.getConstant(2, MVT::i64));
10996 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10997 MachinePointerInfo(TrmpAddr, 2),
11000 // Load the 'nest' parameter value into R10.
11001 // R10 is specified in X86CallingConv.td
11002 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11003 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11004 DAG.getConstant(10, MVT::i64));
11005 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11006 Addr, MachinePointerInfo(TrmpAddr, 10),
11009 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11010 DAG.getConstant(12, MVT::i64));
11011 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11012 MachinePointerInfo(TrmpAddr, 12),
11015 // Jump to the nested function.
11016 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11017 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11018 DAG.getConstant(20, MVT::i64));
11019 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11020 Addr, MachinePointerInfo(TrmpAddr, 20),
11023 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11024 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11025 DAG.getConstant(22, MVT::i64));
11026 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11027 MachinePointerInfo(TrmpAddr, 22),
11030 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11032 const Function *Func =
11033 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11034 CallingConv::ID CC = Func->getCallingConv();
11039 llvm_unreachable("Unsupported calling convention");
11040 case CallingConv::C:
11041 case CallingConv::X86_StdCall: {
11042 // Pass 'nest' parameter in ECX.
11043 // Must be kept in sync with X86CallingConv.td
11044 NestReg = X86::ECX;
11046 // Check that ECX wasn't needed by an 'inreg' parameter.
11047 FunctionType *FTy = Func->getFunctionType();
11048 const AttributeSet &Attrs = Func->getAttributes();
11050 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11051 unsigned InRegCount = 0;
11054 for (FunctionType::param_iterator I = FTy->param_begin(),
11055 E = FTy->param_end(); I != E; ++I, ++Idx)
11056 if (Attrs.getParamAttributes(Idx).hasAttribute(Attribute::InReg))
11057 // FIXME: should only count parameters that are lowered to integers.
11058 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11060 if (InRegCount > 2) {
11061 report_fatal_error("Nest register in use - reduce number of inreg"
11067 case CallingConv::X86_FastCall:
11068 case CallingConv::X86_ThisCall:
11069 case CallingConv::Fast:
11070 // Pass 'nest' parameter in EAX.
11071 // Must be kept in sync with X86CallingConv.td
11072 NestReg = X86::EAX;
11076 SDValue OutChains[4];
11077 SDValue Addr, Disp;
11079 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11080 DAG.getConstant(10, MVT::i32));
11081 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11083 // This is storing the opcode for MOV32ri.
11084 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11085 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11086 OutChains[0] = DAG.getStore(Root, dl,
11087 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11088 Trmp, MachinePointerInfo(TrmpAddr),
11091 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11092 DAG.getConstant(1, MVT::i32));
11093 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11094 MachinePointerInfo(TrmpAddr, 1),
11097 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11098 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11099 DAG.getConstant(5, MVT::i32));
11100 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11101 MachinePointerInfo(TrmpAddr, 5),
11104 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11105 DAG.getConstant(6, MVT::i32));
11106 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11107 MachinePointerInfo(TrmpAddr, 6),
11110 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11114 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11115 SelectionDAG &DAG) const {
11117 The rounding mode is in bits 11:10 of FPSR, and has the following
11119 00 Round to nearest
11124 FLT_ROUNDS, on the other hand, expects the following:
11131 To perform the conversion, we do:
11132 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11135 MachineFunction &MF = DAG.getMachineFunction();
11136 const TargetMachine &TM = MF.getTarget();
11137 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11138 unsigned StackAlignment = TFI.getStackAlignment();
11139 EVT VT = Op.getValueType();
11140 DebugLoc DL = Op.getDebugLoc();
11142 // Save FP Control Word to stack slot
11143 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11144 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11146 MachineMemOperand *MMO =
11147 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11148 MachineMemOperand::MOStore, 2, 2);
11150 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11151 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11152 DAG.getVTList(MVT::Other),
11153 Ops, 2, MVT::i16, MMO);
11155 // Load FP Control Word from stack slot
11156 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11157 MachinePointerInfo(), false, false, false, 0);
11159 // Transform as necessary
11161 DAG.getNode(ISD::SRL, DL, MVT::i16,
11162 DAG.getNode(ISD::AND, DL, MVT::i16,
11163 CWD, DAG.getConstant(0x800, MVT::i16)),
11164 DAG.getConstant(11, MVT::i8));
11166 DAG.getNode(ISD::SRL, DL, MVT::i16,
11167 DAG.getNode(ISD::AND, DL, MVT::i16,
11168 CWD, DAG.getConstant(0x400, MVT::i16)),
11169 DAG.getConstant(9, MVT::i8));
11172 DAG.getNode(ISD::AND, DL, MVT::i16,
11173 DAG.getNode(ISD::ADD, DL, MVT::i16,
11174 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11175 DAG.getConstant(1, MVT::i16)),
11176 DAG.getConstant(3, MVT::i16));
11178 return DAG.getNode((VT.getSizeInBits() < 16 ?
11179 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11182 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11183 EVT VT = Op.getValueType();
11185 unsigned NumBits = VT.getSizeInBits();
11186 DebugLoc dl = Op.getDebugLoc();
11188 Op = Op.getOperand(0);
11189 if (VT == MVT::i8) {
11190 // Zero extend to i32 since there is not an i8 bsr.
11192 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11195 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11196 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11197 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11199 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11202 DAG.getConstant(NumBits+NumBits-1, OpVT),
11203 DAG.getConstant(X86::COND_E, MVT::i8),
11206 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11208 // Finally xor with NumBits-1.
11209 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11212 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11216 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11217 EVT VT = Op.getValueType();
11219 unsigned NumBits = VT.getSizeInBits();
11220 DebugLoc dl = Op.getDebugLoc();
11222 Op = Op.getOperand(0);
11223 if (VT == MVT::i8) {
11224 // Zero extend to i32 since there is not an i8 bsr.
11226 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11229 // Issue a bsr (scan bits in reverse).
11230 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11231 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11233 // And xor with NumBits-1.
11234 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11237 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11241 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11242 EVT VT = Op.getValueType();
11243 unsigned NumBits = VT.getSizeInBits();
11244 DebugLoc dl = Op.getDebugLoc();
11245 Op = Op.getOperand(0);
11247 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11248 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11249 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11251 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11254 DAG.getConstant(NumBits, VT),
11255 DAG.getConstant(X86::COND_E, MVT::i8),
11258 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11261 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11262 // ones, and then concatenate the result back.
11263 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11264 EVT VT = Op.getValueType();
11266 assert(VT.is256BitVector() && VT.isInteger() &&
11267 "Unsupported value type for operation");
11269 unsigned NumElems = VT.getVectorNumElements();
11270 DebugLoc dl = Op.getDebugLoc();
11272 // Extract the LHS vectors
11273 SDValue LHS = Op.getOperand(0);
11274 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11275 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11277 // Extract the RHS vectors
11278 SDValue RHS = Op.getOperand(1);
11279 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11280 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11282 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11283 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11285 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11286 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11287 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11290 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11291 assert(Op.getValueType().is256BitVector() &&
11292 Op.getValueType().isInteger() &&
11293 "Only handle AVX 256-bit vector integer operation");
11294 return Lower256IntArith(Op, DAG);
11297 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11298 assert(Op.getValueType().is256BitVector() &&
11299 Op.getValueType().isInteger() &&
11300 "Only handle AVX 256-bit vector integer operation");
11301 return Lower256IntArith(Op, DAG);
11304 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11305 SelectionDAG &DAG) {
11306 DebugLoc dl = Op.getDebugLoc();
11307 EVT VT = Op.getValueType();
11309 // Decompose 256-bit ops into smaller 128-bit ops.
11310 if (VT.is256BitVector() && !Subtarget->hasInt256())
11311 return Lower256IntArith(Op, DAG);
11313 SDValue A = Op.getOperand(0);
11314 SDValue B = Op.getOperand(1);
11316 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11317 if (VT == MVT::v4i32) {
11318 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11319 "Should not custom lower when pmuldq is available!");
11321 // Extract the odd parts.
11322 const int UnpackMask[] = { 1, -1, 3, -1 };
11323 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11324 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11326 // Multiply the even parts.
11327 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11328 // Now multiply odd parts.
11329 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11331 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11332 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11334 // Merge the two vectors back together with a shuffle. This expands into 2
11336 const int ShufMask[] = { 0, 4, 2, 6 };
11337 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11340 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11341 "Only know how to lower V2I64/V4I64 multiply");
11343 // Ahi = psrlqi(a, 32);
11344 // Bhi = psrlqi(b, 32);
11346 // AloBlo = pmuludq(a, b);
11347 // AloBhi = pmuludq(a, Bhi);
11348 // AhiBlo = pmuludq(Ahi, b);
11350 // AloBhi = psllqi(AloBhi, 32);
11351 // AhiBlo = psllqi(AhiBlo, 32);
11352 // return AloBlo + AloBhi + AhiBlo;
11354 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11356 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11357 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11359 // Bit cast to 32-bit vectors for MULUDQ
11360 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11361 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11362 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11363 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11364 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11366 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11367 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11368 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11370 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11371 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11373 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11374 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11377 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11379 EVT VT = Op.getValueType();
11380 DebugLoc dl = Op.getDebugLoc();
11381 SDValue R = Op.getOperand(0);
11382 SDValue Amt = Op.getOperand(1);
11383 LLVMContext *Context = DAG.getContext();
11385 if (!Subtarget->hasSSE2())
11388 // Optimize shl/srl/sra with constant shift amount.
11389 if (isSplatVector(Amt.getNode())) {
11390 SDValue SclrAmt = Amt->getOperand(0);
11391 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11392 uint64_t ShiftAmt = C->getZExtValue();
11394 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11395 (Subtarget->hasInt256() &&
11396 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11397 if (Op.getOpcode() == ISD::SHL)
11398 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11399 DAG.getConstant(ShiftAmt, MVT::i32));
11400 if (Op.getOpcode() == ISD::SRL)
11401 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11402 DAG.getConstant(ShiftAmt, MVT::i32));
11403 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11404 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11405 DAG.getConstant(ShiftAmt, MVT::i32));
11408 if (VT == MVT::v16i8) {
11409 if (Op.getOpcode() == ISD::SHL) {
11410 // Make a large shift.
11411 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11412 DAG.getConstant(ShiftAmt, MVT::i32));
11413 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11414 // Zero out the rightmost bits.
11415 SmallVector<SDValue, 16> V(16,
11416 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11418 return DAG.getNode(ISD::AND, dl, VT, SHL,
11419 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11421 if (Op.getOpcode() == ISD::SRL) {
11422 // Make a large shift.
11423 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11424 DAG.getConstant(ShiftAmt, MVT::i32));
11425 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11426 // Zero out the leftmost bits.
11427 SmallVector<SDValue, 16> V(16,
11428 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11430 return DAG.getNode(ISD::AND, dl, VT, SRL,
11431 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11433 if (Op.getOpcode() == ISD::SRA) {
11434 if (ShiftAmt == 7) {
11435 // R s>> 7 === R s< 0
11436 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11437 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11440 // R s>> a === ((R u>> a) ^ m) - m
11441 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11442 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11444 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11445 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11446 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11449 llvm_unreachable("Unknown shift opcode.");
11452 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11453 if (Op.getOpcode() == ISD::SHL) {
11454 // Make a large shift.
11455 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11456 DAG.getConstant(ShiftAmt, MVT::i32));
11457 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11458 // Zero out the rightmost bits.
11459 SmallVector<SDValue, 32> V(32,
11460 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11462 return DAG.getNode(ISD::AND, dl, VT, SHL,
11463 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11465 if (Op.getOpcode() == ISD::SRL) {
11466 // Make a large shift.
11467 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11468 DAG.getConstant(ShiftAmt, MVT::i32));
11469 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11470 // Zero out the leftmost bits.
11471 SmallVector<SDValue, 32> V(32,
11472 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11474 return DAG.getNode(ISD::AND, dl, VT, SRL,
11475 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11477 if (Op.getOpcode() == ISD::SRA) {
11478 if (ShiftAmt == 7) {
11479 // R s>> 7 === R s< 0
11480 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11481 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11484 // R s>> a === ((R u>> a) ^ m) - m
11485 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11486 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11488 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11489 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11490 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11493 llvm_unreachable("Unknown shift opcode.");
11498 // Lower SHL with variable shift amount.
11499 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11500 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11501 DAG.getConstant(23, MVT::i32));
11503 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11504 Constant *C = ConstantDataVector::get(*Context, CV);
11505 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11506 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11507 MachinePointerInfo::getConstantPool(),
11508 false, false, false, 16);
11510 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11511 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11512 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11513 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11515 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11516 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11519 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11520 DAG.getConstant(5, MVT::i32));
11521 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11523 // Turn 'a' into a mask suitable for VSELECT
11524 SDValue VSelM = DAG.getConstant(0x80, VT);
11525 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11526 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11528 SDValue CM1 = DAG.getConstant(0x0f, VT);
11529 SDValue CM2 = DAG.getConstant(0x3f, VT);
11531 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11532 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11533 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11534 DAG.getConstant(4, MVT::i32), DAG);
11535 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11536 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11539 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11540 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11541 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11543 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11544 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11545 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11546 DAG.getConstant(2, MVT::i32), DAG);
11547 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11548 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11551 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11552 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11553 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11555 // return VSELECT(r, r+r, a);
11556 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11557 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11561 // Decompose 256-bit shifts into smaller 128-bit shifts.
11562 if (VT.is256BitVector()) {
11563 unsigned NumElems = VT.getVectorNumElements();
11564 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11565 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11567 // Extract the two vectors
11568 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11569 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11571 // Recreate the shift amount vectors
11572 SDValue Amt1, Amt2;
11573 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11574 // Constant shift amount
11575 SmallVector<SDValue, 4> Amt1Csts;
11576 SmallVector<SDValue, 4> Amt2Csts;
11577 for (unsigned i = 0; i != NumElems/2; ++i)
11578 Amt1Csts.push_back(Amt->getOperand(i));
11579 for (unsigned i = NumElems/2; i != NumElems; ++i)
11580 Amt2Csts.push_back(Amt->getOperand(i));
11582 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11583 &Amt1Csts[0], NumElems/2);
11584 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11585 &Amt2Csts[0], NumElems/2);
11587 // Variable shift amount
11588 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11589 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11592 // Issue new vector shifts for the smaller types
11593 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11594 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11596 // Concatenate the result back
11597 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11603 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11604 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11605 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11606 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11607 // has only one use.
11608 SDNode *N = Op.getNode();
11609 SDValue LHS = N->getOperand(0);
11610 SDValue RHS = N->getOperand(1);
11611 unsigned BaseOp = 0;
11613 DebugLoc DL = Op.getDebugLoc();
11614 switch (Op.getOpcode()) {
11615 default: llvm_unreachable("Unknown ovf instruction!");
11617 // A subtract of one will be selected as a INC. Note that INC doesn't
11618 // set CF, so we can't do this for UADDO.
11619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11621 BaseOp = X86ISD::INC;
11622 Cond = X86::COND_O;
11625 BaseOp = X86ISD::ADD;
11626 Cond = X86::COND_O;
11629 BaseOp = X86ISD::ADD;
11630 Cond = X86::COND_B;
11633 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11634 // set CF, so we can't do this for USUBO.
11635 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11637 BaseOp = X86ISD::DEC;
11638 Cond = X86::COND_O;
11641 BaseOp = X86ISD::SUB;
11642 Cond = X86::COND_O;
11645 BaseOp = X86ISD::SUB;
11646 Cond = X86::COND_B;
11649 BaseOp = X86ISD::SMUL;
11650 Cond = X86::COND_O;
11652 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11653 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11655 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11658 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11659 DAG.getConstant(X86::COND_O, MVT::i32),
11660 SDValue(Sum.getNode(), 2));
11662 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11666 // Also sets EFLAGS.
11667 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11668 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11671 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11672 DAG.getConstant(Cond, MVT::i32),
11673 SDValue(Sum.getNode(), 1));
11675 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11678 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11679 SelectionDAG &DAG) const {
11680 DebugLoc dl = Op.getDebugLoc();
11681 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11682 EVT VT = Op.getValueType();
11684 if (!Subtarget->hasSSE2() || !VT.isVector())
11687 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11688 ExtraVT.getScalarType().getSizeInBits();
11689 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11691 switch (VT.getSimpleVT().SimpleTy) {
11692 default: return SDValue();
11695 if (!Subtarget->hasFp256())
11697 if (!Subtarget->hasInt256()) {
11698 // needs to be split
11699 unsigned NumElems = VT.getVectorNumElements();
11701 // Extract the LHS vectors
11702 SDValue LHS = Op.getOperand(0);
11703 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11704 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11706 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11707 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11709 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11710 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11711 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11713 SDValue Extra = DAG.getValueType(ExtraVT);
11715 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11716 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11718 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11723 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11724 Op.getOperand(0), ShAmt, DAG);
11725 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11730 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11731 SelectionDAG &DAG) {
11732 DebugLoc dl = Op.getDebugLoc();
11734 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11735 // There isn't any reason to disable it if the target processor supports it.
11736 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11737 SDValue Chain = Op.getOperand(0);
11738 SDValue Zero = DAG.getConstant(0, MVT::i32);
11740 DAG.getRegister(X86::ESP, MVT::i32), // Base
11741 DAG.getTargetConstant(1, MVT::i8), // Scale
11742 DAG.getRegister(0, MVT::i32), // Index
11743 DAG.getTargetConstant(0, MVT::i32), // Disp
11744 DAG.getRegister(0, MVT::i32), // Segment.
11749 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11750 array_lengthof(Ops));
11751 return SDValue(Res, 0);
11754 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11756 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11758 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11759 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11760 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11761 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11763 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11764 if (!Op1 && !Op2 && !Op3 && Op4)
11765 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11767 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11768 if (Op1 && !Op2 && !Op3 && !Op4)
11769 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11771 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11773 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11776 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11777 SelectionDAG &DAG) {
11778 DebugLoc dl = Op.getDebugLoc();
11779 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11780 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11781 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11782 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11784 // The only fence that needs an instruction is a sequentially-consistent
11785 // cross-thread fence.
11786 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11787 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11788 // no-sse2). There isn't any reason to disable it if the target processor
11790 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11791 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11793 SDValue Chain = Op.getOperand(0);
11794 SDValue Zero = DAG.getConstant(0, MVT::i32);
11796 DAG.getRegister(X86::ESP, MVT::i32), // Base
11797 DAG.getTargetConstant(1, MVT::i8), // Scale
11798 DAG.getRegister(0, MVT::i32), // Index
11799 DAG.getTargetConstant(0, MVT::i32), // Disp
11800 DAG.getRegister(0, MVT::i32), // Segment.
11805 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11806 array_lengthof(Ops));
11807 return SDValue(Res, 0);
11810 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11811 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11814 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11815 SelectionDAG &DAG) {
11816 EVT T = Op.getValueType();
11817 DebugLoc DL = Op.getDebugLoc();
11820 switch(T.getSimpleVT().SimpleTy) {
11821 default: llvm_unreachable("Invalid value type!");
11822 case MVT::i8: Reg = X86::AL; size = 1; break;
11823 case MVT::i16: Reg = X86::AX; size = 2; break;
11824 case MVT::i32: Reg = X86::EAX; size = 4; break;
11826 assert(Subtarget->is64Bit() && "Node not type legal!");
11827 Reg = X86::RAX; size = 8;
11830 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11831 Op.getOperand(2), SDValue());
11832 SDValue Ops[] = { cpIn.getValue(0),
11835 DAG.getTargetConstant(size, MVT::i8),
11836 cpIn.getValue(1) };
11837 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11838 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11839 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11842 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11846 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11847 SelectionDAG &DAG) {
11848 assert(Subtarget->is64Bit() && "Result not type legalized?");
11849 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11850 SDValue TheChain = Op.getOperand(0);
11851 DebugLoc dl = Op.getDebugLoc();
11852 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11853 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11854 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11856 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11857 DAG.getConstant(32, MVT::i8));
11859 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11862 return DAG.getMergeValues(Ops, 2, dl);
11865 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11866 EVT SrcVT = Op.getOperand(0).getValueType();
11867 EVT DstVT = Op.getValueType();
11868 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11869 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11870 assert((DstVT == MVT::i64 ||
11871 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11872 "Unexpected custom BITCAST");
11873 // i64 <=> MMX conversions are Legal.
11874 if (SrcVT==MVT::i64 && DstVT.isVector())
11876 if (DstVT==MVT::i64 && SrcVT.isVector())
11878 // MMX <=> MMX conversions are Legal.
11879 if (SrcVT.isVector() && DstVT.isVector())
11881 // All other conversions need to be expanded.
11885 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11886 SDNode *Node = Op.getNode();
11887 DebugLoc dl = Node->getDebugLoc();
11888 EVT T = Node->getValueType(0);
11889 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11890 DAG.getConstant(0, T), Node->getOperand(2));
11891 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11892 cast<AtomicSDNode>(Node)->getMemoryVT(),
11893 Node->getOperand(0),
11894 Node->getOperand(1), negOp,
11895 cast<AtomicSDNode>(Node)->getSrcValue(),
11896 cast<AtomicSDNode>(Node)->getAlignment(),
11897 cast<AtomicSDNode>(Node)->getOrdering(),
11898 cast<AtomicSDNode>(Node)->getSynchScope());
11901 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11902 SDNode *Node = Op.getNode();
11903 DebugLoc dl = Node->getDebugLoc();
11904 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11906 // Convert seq_cst store -> xchg
11907 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11908 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11909 // (The only way to get a 16-byte store is cmpxchg16b)
11910 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11911 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11912 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11913 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11914 cast<AtomicSDNode>(Node)->getMemoryVT(),
11915 Node->getOperand(0),
11916 Node->getOperand(1), Node->getOperand(2),
11917 cast<AtomicSDNode>(Node)->getMemOperand(),
11918 cast<AtomicSDNode>(Node)->getOrdering(),
11919 cast<AtomicSDNode>(Node)->getSynchScope());
11920 return Swap.getValue(1);
11922 // Other atomic stores have a simple pattern.
11926 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11927 EVT VT = Op.getNode()->getValueType(0);
11929 // Let legalize expand this if it isn't a legal type yet.
11930 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11933 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11936 bool ExtraOp = false;
11937 switch (Op.getOpcode()) {
11938 default: llvm_unreachable("Invalid code");
11939 case ISD::ADDC: Opc = X86ISD::ADD; break;
11940 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11941 case ISD::SUBC: Opc = X86ISD::SUB; break;
11942 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11946 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11948 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11949 Op.getOperand(1), Op.getOperand(2));
11952 /// LowerOperation - Provide custom lowering hooks for some operations.
11954 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11955 switch (Op.getOpcode()) {
11956 default: llvm_unreachable("Should not custom lower this!");
11957 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11958 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11959 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11960 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11961 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11962 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11963 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11964 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11965 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11966 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11967 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11968 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11969 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11970 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11971 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11972 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11973 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11974 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11975 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11976 case ISD::SHL_PARTS:
11977 case ISD::SRA_PARTS:
11978 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11979 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11980 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11981 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG);
11982 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
11983 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
11984 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
11985 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11986 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11987 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11988 case ISD::FABS: return LowerFABS(Op, DAG);
11989 case ISD::FNEG: return LowerFNEG(Op, DAG);
11990 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11991 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11992 case ISD::SETCC: return LowerSETCC(Op, DAG);
11993 case ISD::SELECT: return LowerSELECT(Op, DAG);
11994 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11995 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11996 case ISD::VASTART: return LowerVASTART(Op, DAG);
11997 case ISD::VAARG: return LowerVAARG(Op, DAG);
11998 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11999 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12000 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12001 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12002 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12003 case ISD::FRAME_TO_ARGS_OFFSET:
12004 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12005 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12006 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12007 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12008 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12009 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12010 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12011 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12012 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12013 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12014 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12015 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12018 case ISD::SHL: return LowerShift(Op, DAG);
12024 case ISD::UMULO: return LowerXALUO(Op, DAG);
12025 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12026 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12030 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12031 case ISD::ADD: return LowerADD(Op, DAG);
12032 case ISD::SUB: return LowerSUB(Op, DAG);
12036 static void ReplaceATOMIC_LOAD(SDNode *Node,
12037 SmallVectorImpl<SDValue> &Results,
12038 SelectionDAG &DAG) {
12039 DebugLoc dl = Node->getDebugLoc();
12040 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12042 // Convert wide load -> cmpxchg8b/cmpxchg16b
12043 // FIXME: On 32-bit, load -> fild or movq would be more efficient
12044 // (The only way to get a 16-byte load is cmpxchg16b)
12045 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12046 SDValue Zero = DAG.getConstant(0, VT);
12047 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12048 Node->getOperand(0),
12049 Node->getOperand(1), Zero, Zero,
12050 cast<AtomicSDNode>(Node)->getMemOperand(),
12051 cast<AtomicSDNode>(Node)->getOrdering(),
12052 cast<AtomicSDNode>(Node)->getSynchScope());
12053 Results.push_back(Swap.getValue(0));
12054 Results.push_back(Swap.getValue(1));
12058 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12059 SelectionDAG &DAG, unsigned NewOp) {
12060 DebugLoc dl = Node->getDebugLoc();
12061 assert (Node->getValueType(0) == MVT::i64 &&
12062 "Only know how to expand i64 atomics");
12064 SDValue Chain = Node->getOperand(0);
12065 SDValue In1 = Node->getOperand(1);
12066 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12067 Node->getOperand(2), DAG.getIntPtrConstant(0));
12068 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12069 Node->getOperand(2), DAG.getIntPtrConstant(1));
12070 SDValue Ops[] = { Chain, In1, In2L, In2H };
12071 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12073 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12074 cast<MemSDNode>(Node)->getMemOperand());
12075 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12076 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12077 Results.push_back(Result.getValue(2));
12080 /// ReplaceNodeResults - Replace a node with an illegal result type
12081 /// with a new node built out of custom code.
12082 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12083 SmallVectorImpl<SDValue>&Results,
12084 SelectionDAG &DAG) const {
12085 DebugLoc dl = N->getDebugLoc();
12086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12087 switch (N->getOpcode()) {
12089 llvm_unreachable("Do not know how to custom type legalize this operation!");
12090 case ISD::SIGN_EXTEND_INREG:
12095 // We don't want to expand or promote these.
12097 case ISD::FP_TO_SINT:
12098 case ISD::FP_TO_UINT: {
12099 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12101 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12104 std::pair<SDValue,SDValue> Vals =
12105 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12106 SDValue FIST = Vals.first, StackSlot = Vals.second;
12107 if (FIST.getNode() != 0) {
12108 EVT VT = N->getValueType(0);
12109 // Return a load from the stack slot.
12110 if (StackSlot.getNode() != 0)
12111 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12112 MachinePointerInfo(),
12113 false, false, false, 0));
12115 Results.push_back(FIST);
12119 case ISD::UINT_TO_FP: {
12120 if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12121 N->getValueType(0) != MVT::v2f32)
12123 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12125 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12127 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12128 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12129 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12130 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12131 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12132 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12135 case ISD::FP_ROUND: {
12136 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12138 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12139 Results.push_back(V);
12142 case ISD::READCYCLECOUNTER: {
12143 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12144 SDValue TheChain = N->getOperand(0);
12145 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12146 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12148 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12150 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12151 SDValue Ops[] = { eax, edx };
12152 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12153 Results.push_back(edx.getValue(1));
12156 case ISD::ATOMIC_CMP_SWAP: {
12157 EVT T = N->getValueType(0);
12158 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12159 bool Regs64bit = T == MVT::i128;
12160 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12161 SDValue cpInL, cpInH;
12162 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12163 DAG.getConstant(0, HalfT));
12164 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12165 DAG.getConstant(1, HalfT));
12166 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12167 Regs64bit ? X86::RAX : X86::EAX,
12169 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12170 Regs64bit ? X86::RDX : X86::EDX,
12171 cpInH, cpInL.getValue(1));
12172 SDValue swapInL, swapInH;
12173 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12174 DAG.getConstant(0, HalfT));
12175 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12176 DAG.getConstant(1, HalfT));
12177 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12178 Regs64bit ? X86::RBX : X86::EBX,
12179 swapInL, cpInH.getValue(1));
12180 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12181 Regs64bit ? X86::RCX : X86::ECX,
12182 swapInH, swapInL.getValue(1));
12183 SDValue Ops[] = { swapInH.getValue(0),
12185 swapInH.getValue(1) };
12186 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12187 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12188 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12189 X86ISD::LCMPXCHG8_DAG;
12190 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12192 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12193 Regs64bit ? X86::RAX : X86::EAX,
12194 HalfT, Result.getValue(1));
12195 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12196 Regs64bit ? X86::RDX : X86::EDX,
12197 HalfT, cpOutL.getValue(2));
12198 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12199 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12200 Results.push_back(cpOutH.getValue(1));
12203 case ISD::ATOMIC_LOAD_ADD:
12204 case ISD::ATOMIC_LOAD_AND:
12205 case ISD::ATOMIC_LOAD_NAND:
12206 case ISD::ATOMIC_LOAD_OR:
12207 case ISD::ATOMIC_LOAD_SUB:
12208 case ISD::ATOMIC_LOAD_XOR:
12209 case ISD::ATOMIC_LOAD_MAX:
12210 case ISD::ATOMIC_LOAD_MIN:
12211 case ISD::ATOMIC_LOAD_UMAX:
12212 case ISD::ATOMIC_LOAD_UMIN:
12213 case ISD::ATOMIC_SWAP: {
12215 switch (N->getOpcode()) {
12216 default: llvm_unreachable("Unexpected opcode");
12217 case ISD::ATOMIC_LOAD_ADD:
12218 Opc = X86ISD::ATOMADD64_DAG;
12220 case ISD::ATOMIC_LOAD_AND:
12221 Opc = X86ISD::ATOMAND64_DAG;
12223 case ISD::ATOMIC_LOAD_NAND:
12224 Opc = X86ISD::ATOMNAND64_DAG;
12226 case ISD::ATOMIC_LOAD_OR:
12227 Opc = X86ISD::ATOMOR64_DAG;
12229 case ISD::ATOMIC_LOAD_SUB:
12230 Opc = X86ISD::ATOMSUB64_DAG;
12232 case ISD::ATOMIC_LOAD_XOR:
12233 Opc = X86ISD::ATOMXOR64_DAG;
12235 case ISD::ATOMIC_LOAD_MAX:
12236 Opc = X86ISD::ATOMMAX64_DAG;
12238 case ISD::ATOMIC_LOAD_MIN:
12239 Opc = X86ISD::ATOMMIN64_DAG;
12241 case ISD::ATOMIC_LOAD_UMAX:
12242 Opc = X86ISD::ATOMUMAX64_DAG;
12244 case ISD::ATOMIC_LOAD_UMIN:
12245 Opc = X86ISD::ATOMUMIN64_DAG;
12247 case ISD::ATOMIC_SWAP:
12248 Opc = X86ISD::ATOMSWAP64_DAG;
12251 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12254 case ISD::ATOMIC_LOAD:
12255 ReplaceATOMIC_LOAD(N, Results, DAG);
12259 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12261 default: return NULL;
12262 case X86ISD::BSF: return "X86ISD::BSF";
12263 case X86ISD::BSR: return "X86ISD::BSR";
12264 case X86ISD::SHLD: return "X86ISD::SHLD";
12265 case X86ISD::SHRD: return "X86ISD::SHRD";
12266 case X86ISD::FAND: return "X86ISD::FAND";
12267 case X86ISD::FOR: return "X86ISD::FOR";
12268 case X86ISD::FXOR: return "X86ISD::FXOR";
12269 case X86ISD::FSRL: return "X86ISD::FSRL";
12270 case X86ISD::FILD: return "X86ISD::FILD";
12271 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12272 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12273 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12274 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12275 case X86ISD::FLD: return "X86ISD::FLD";
12276 case X86ISD::FST: return "X86ISD::FST";
12277 case X86ISD::CALL: return "X86ISD::CALL";
12278 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12279 case X86ISD::BT: return "X86ISD::BT";
12280 case X86ISD::CMP: return "X86ISD::CMP";
12281 case X86ISD::COMI: return "X86ISD::COMI";
12282 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12283 case X86ISD::SETCC: return "X86ISD::SETCC";
12284 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12285 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12286 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12287 case X86ISD::CMOV: return "X86ISD::CMOV";
12288 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12289 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12290 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12291 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12292 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12293 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12294 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12295 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12296 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12297 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12298 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12299 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12300 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12301 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12302 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12303 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12304 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12305 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12306 case X86ISD::HADD: return "X86ISD::HADD";
12307 case X86ISD::HSUB: return "X86ISD::HSUB";
12308 case X86ISD::FHADD: return "X86ISD::FHADD";
12309 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12310 case X86ISD::UMAX: return "X86ISD::UMAX";
12311 case X86ISD::UMIN: return "X86ISD::UMIN";
12312 case X86ISD::SMAX: return "X86ISD::SMAX";
12313 case X86ISD::SMIN: return "X86ISD::SMIN";
12314 case X86ISD::FMAX: return "X86ISD::FMAX";
12315 case X86ISD::FMIN: return "X86ISD::FMIN";
12316 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12317 case X86ISD::FMINC: return "X86ISD::FMINC";
12318 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12319 case X86ISD::FRCP: return "X86ISD::FRCP";
12320 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12321 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12322 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12323 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12324 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12325 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12326 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12327 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12328 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12329 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12330 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12331 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12332 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12333 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12334 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12335 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12336 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12337 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12338 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12339 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12340 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12341 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12342 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12343 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12344 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12345 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12346 case X86ISD::VSHL: return "X86ISD::VSHL";
12347 case X86ISD::VSRL: return "X86ISD::VSRL";
12348 case X86ISD::VSRA: return "X86ISD::VSRA";
12349 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12350 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12351 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12352 case X86ISD::CMPP: return "X86ISD::CMPP";
12353 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12354 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12355 case X86ISD::ADD: return "X86ISD::ADD";
12356 case X86ISD::SUB: return "X86ISD::SUB";
12357 case X86ISD::ADC: return "X86ISD::ADC";
12358 case X86ISD::SBB: return "X86ISD::SBB";
12359 case X86ISD::SMUL: return "X86ISD::SMUL";
12360 case X86ISD::UMUL: return "X86ISD::UMUL";
12361 case X86ISD::INC: return "X86ISD::INC";
12362 case X86ISD::DEC: return "X86ISD::DEC";
12363 case X86ISD::OR: return "X86ISD::OR";
12364 case X86ISD::XOR: return "X86ISD::XOR";
12365 case X86ISD::AND: return "X86ISD::AND";
12366 case X86ISD::BLSI: return "X86ISD::BLSI";
12367 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12368 case X86ISD::BLSR: return "X86ISD::BLSR";
12369 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12370 case X86ISD::PTEST: return "X86ISD::PTEST";
12371 case X86ISD::TESTP: return "X86ISD::TESTP";
12372 case X86ISD::PALIGN: return "X86ISD::PALIGN";
12373 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12374 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12375 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12376 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12377 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12378 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12379 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12380 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12381 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12382 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12383 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12384 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12385 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12386 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12387 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12388 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12389 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12390 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12391 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12392 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12393 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12394 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12395 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12396 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12397 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12398 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12399 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12400 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12401 case X86ISD::SAHF: return "X86ISD::SAHF";
12402 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12403 case X86ISD::FMADD: return "X86ISD::FMADD";
12404 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12405 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12406 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12407 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12408 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12409 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12410 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12414 // isLegalAddressingMode - Return true if the addressing mode represented
12415 // by AM is legal for this target, for a load/store of the specified type.
12416 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12418 // X86 supports extremely general addressing modes.
12419 CodeModel::Model M = getTargetMachine().getCodeModel();
12420 Reloc::Model R = getTargetMachine().getRelocationModel();
12422 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12423 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12428 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12430 // If a reference to this global requires an extra load, we can't fold it.
12431 if (isGlobalStubReference(GVFlags))
12434 // If BaseGV requires a register for the PIC base, we cannot also have a
12435 // BaseReg specified.
12436 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12439 // If lower 4G is not available, then we must use rip-relative addressing.
12440 if ((M != CodeModel::Small || R != Reloc::Static) &&
12441 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12445 switch (AM.Scale) {
12451 // These scales always work.
12456 // These scales are formed with basereg+scalereg. Only accept if there is
12461 default: // Other stuff never works.
12468 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12469 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12471 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12472 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12473 return NumBits1 > NumBits2;
12476 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12477 return isInt<32>(Imm);
12480 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12481 // Can also use sub to handle negated immediates.
12482 return isInt<32>(Imm);
12485 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12486 if (!VT1.isInteger() || !VT2.isInteger())
12488 unsigned NumBits1 = VT1.getSizeInBits();
12489 unsigned NumBits2 = VT2.getSizeInBits();
12490 return NumBits1 > NumBits2;
12493 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12494 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12495 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12498 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12499 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12500 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12503 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12504 EVT VT1 = Val.getValueType();
12505 if (isZExtFree(VT1, VT2))
12508 if (Val.getOpcode() != ISD::LOAD)
12511 if (!VT1.isSimple() || !VT1.isInteger() ||
12512 !VT2.isSimple() || !VT2.isInteger())
12515 switch (VT1.getSimpleVT().SimpleTy) {
12520 // X86 has 8, 16, and 32-bit zero-extending loads.
12527 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12528 // i16 instructions are longer (0x66 prefix) and potentially slower.
12529 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12532 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12533 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12534 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12535 /// are assumed to be legal.
12537 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12539 // Very little shuffling can be done for 64-bit vectors right now.
12540 if (VT.getSizeInBits() == 64)
12543 // FIXME: pshufb, blends, shifts.
12544 return (VT.getVectorNumElements() == 2 ||
12545 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12546 isMOVLMask(M, VT) ||
12547 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12548 isPSHUFDMask(M, VT) ||
12549 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12550 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12551 isPALIGNRMask(M, VT, Subtarget) ||
12552 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12553 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12554 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12555 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12559 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12561 unsigned NumElts = VT.getVectorNumElements();
12562 // FIXME: This collection of masks seems suspect.
12565 if (NumElts == 4 && VT.is128BitVector()) {
12566 return (isMOVLMask(Mask, VT) ||
12567 isCommutedMOVLMask(Mask, VT, true) ||
12568 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12569 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12574 //===----------------------------------------------------------------------===//
12575 // X86 Scheduler Hooks
12576 //===----------------------------------------------------------------------===//
12578 /// Utility function to emit xbegin specifying the start of an RTM region.
12579 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12580 const TargetInstrInfo *TII) {
12581 DebugLoc DL = MI->getDebugLoc();
12583 const BasicBlock *BB = MBB->getBasicBlock();
12584 MachineFunction::iterator I = MBB;
12587 // For the v = xbegin(), we generate
12598 MachineBasicBlock *thisMBB = MBB;
12599 MachineFunction *MF = MBB->getParent();
12600 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12601 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12602 MF->insert(I, mainMBB);
12603 MF->insert(I, sinkMBB);
12605 // Transfer the remainder of BB and its successor edges to sinkMBB.
12606 sinkMBB->splice(sinkMBB->begin(), MBB,
12607 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12608 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12612 // # fallthrough to mainMBB
12613 // # abortion to sinkMBB
12614 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12615 thisMBB->addSuccessor(mainMBB);
12616 thisMBB->addSuccessor(sinkMBB);
12620 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12621 mainMBB->addSuccessor(sinkMBB);
12624 // EAX is live into the sinkMBB
12625 sinkMBB->addLiveIn(X86::EAX);
12626 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12627 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12630 MI->eraseFromParent();
12634 // Get CMPXCHG opcode for the specified data type.
12635 static unsigned getCmpXChgOpcode(EVT VT) {
12636 switch (VT.getSimpleVT().SimpleTy) {
12637 case MVT::i8: return X86::LCMPXCHG8;
12638 case MVT::i16: return X86::LCMPXCHG16;
12639 case MVT::i32: return X86::LCMPXCHG32;
12640 case MVT::i64: return X86::LCMPXCHG64;
12644 llvm_unreachable("Invalid operand size!");
12647 // Get LOAD opcode for the specified data type.
12648 static unsigned getLoadOpcode(EVT VT) {
12649 switch (VT.getSimpleVT().SimpleTy) {
12650 case MVT::i8: return X86::MOV8rm;
12651 case MVT::i16: return X86::MOV16rm;
12652 case MVT::i32: return X86::MOV32rm;
12653 case MVT::i64: return X86::MOV64rm;
12657 llvm_unreachable("Invalid operand size!");
12660 // Get opcode of the non-atomic one from the specified atomic instruction.
12661 static unsigned getNonAtomicOpcode(unsigned Opc) {
12663 case X86::ATOMAND8: return X86::AND8rr;
12664 case X86::ATOMAND16: return X86::AND16rr;
12665 case X86::ATOMAND32: return X86::AND32rr;
12666 case X86::ATOMAND64: return X86::AND64rr;
12667 case X86::ATOMOR8: return X86::OR8rr;
12668 case X86::ATOMOR16: return X86::OR16rr;
12669 case X86::ATOMOR32: return X86::OR32rr;
12670 case X86::ATOMOR64: return X86::OR64rr;
12671 case X86::ATOMXOR8: return X86::XOR8rr;
12672 case X86::ATOMXOR16: return X86::XOR16rr;
12673 case X86::ATOMXOR32: return X86::XOR32rr;
12674 case X86::ATOMXOR64: return X86::XOR64rr;
12676 llvm_unreachable("Unhandled atomic-load-op opcode!");
12679 // Get opcode of the non-atomic one from the specified atomic instruction with
12681 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12682 unsigned &ExtraOpc) {
12684 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12685 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12686 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12687 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12688 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12689 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12690 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12691 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12692 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12693 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12694 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12695 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12696 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12697 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12698 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12699 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12700 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12701 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12702 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12703 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12705 llvm_unreachable("Unhandled atomic-load-op opcode!");
12708 // Get opcode of the non-atomic one from the specified atomic instruction for
12709 // 64-bit data type on 32-bit target.
12710 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12712 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12713 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12714 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12715 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12716 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12717 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12718 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12719 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12720 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12721 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12723 llvm_unreachable("Unhandled atomic-load-op opcode!");
12726 // Get opcode of the non-atomic one from the specified atomic instruction for
12727 // 64-bit data type on 32-bit target with extra opcode.
12728 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12730 unsigned &ExtraOpc) {
12732 case X86::ATOMNAND6432:
12733 ExtraOpc = X86::NOT32r;
12734 HiOpc = X86::AND32rr;
12735 return X86::AND32rr;
12737 llvm_unreachable("Unhandled atomic-load-op opcode!");
12740 // Get pseudo CMOV opcode from the specified data type.
12741 static unsigned getPseudoCMOVOpc(EVT VT) {
12742 switch (VT.getSimpleVT().SimpleTy) {
12743 case MVT::i8: return X86::CMOV_GR8;
12744 case MVT::i16: return X86::CMOV_GR16;
12745 case MVT::i32: return X86::CMOV_GR32;
12749 llvm_unreachable("Unknown CMOV opcode!");
12752 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12753 // They will be translated into a spin-loop or compare-exchange loop from
12756 // dst = atomic-fetch-op MI.addr, MI.val
12762 // EAX = LOAD MI.addr
12764 // t1 = OP MI.val, EAX
12765 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12770 MachineBasicBlock *
12771 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12772 MachineBasicBlock *MBB) const {
12773 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12774 DebugLoc DL = MI->getDebugLoc();
12776 MachineFunction *MF = MBB->getParent();
12777 MachineRegisterInfo &MRI = MF->getRegInfo();
12779 const BasicBlock *BB = MBB->getBasicBlock();
12780 MachineFunction::iterator I = MBB;
12783 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12784 "Unexpected number of operands");
12786 assert(MI->hasOneMemOperand() &&
12787 "Expected atomic-load-op to have one memoperand");
12789 // Memory Reference
12790 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12791 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12793 unsigned DstReg, SrcReg;
12794 unsigned MemOpndSlot;
12796 unsigned CurOp = 0;
12798 DstReg = MI->getOperand(CurOp++).getReg();
12799 MemOpndSlot = CurOp;
12800 CurOp += X86::AddrNumOperands;
12801 SrcReg = MI->getOperand(CurOp++).getReg();
12803 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12804 MVT::SimpleValueType VT = *RC->vt_begin();
12805 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12807 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12808 unsigned LOADOpc = getLoadOpcode(VT);
12810 // For the atomic load-arith operator, we generate
12813 // EAX = LOAD [MI.addr]
12815 // t1 = OP MI.val, EAX
12816 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12820 MachineBasicBlock *thisMBB = MBB;
12821 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12822 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12823 MF->insert(I, mainMBB);
12824 MF->insert(I, sinkMBB);
12826 MachineInstrBuilder MIB;
12828 // Transfer the remainder of BB and its successor edges to sinkMBB.
12829 sinkMBB->splice(sinkMBB->begin(), MBB,
12830 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12831 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12834 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12835 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12836 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12837 MIB.setMemRefs(MMOBegin, MMOEnd);
12839 thisMBB->addSuccessor(mainMBB);
12842 MachineBasicBlock *origMainMBB = mainMBB;
12843 mainMBB->addLiveIn(AccPhyReg);
12845 // Copy AccPhyReg as it is used more than once.
12846 unsigned AccReg = MRI.createVirtualRegister(RC);
12847 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12848 .addReg(AccPhyReg);
12850 unsigned t1 = MRI.createVirtualRegister(RC);
12851 unsigned Opc = MI->getOpcode();
12854 llvm_unreachable("Unhandled atomic-load-op opcode!");
12855 case X86::ATOMAND8:
12856 case X86::ATOMAND16:
12857 case X86::ATOMAND32:
12858 case X86::ATOMAND64:
12860 case X86::ATOMOR16:
12861 case X86::ATOMOR32:
12862 case X86::ATOMOR64:
12863 case X86::ATOMXOR8:
12864 case X86::ATOMXOR16:
12865 case X86::ATOMXOR32:
12866 case X86::ATOMXOR64: {
12867 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12868 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12872 case X86::ATOMNAND8:
12873 case X86::ATOMNAND16:
12874 case X86::ATOMNAND32:
12875 case X86::ATOMNAND64: {
12876 unsigned t2 = MRI.createVirtualRegister(RC);
12878 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12879 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12881 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12884 case X86::ATOMMAX8:
12885 case X86::ATOMMAX16:
12886 case X86::ATOMMAX32:
12887 case X86::ATOMMAX64:
12888 case X86::ATOMMIN8:
12889 case X86::ATOMMIN16:
12890 case X86::ATOMMIN32:
12891 case X86::ATOMMIN64:
12892 case X86::ATOMUMAX8:
12893 case X86::ATOMUMAX16:
12894 case X86::ATOMUMAX32:
12895 case X86::ATOMUMAX64:
12896 case X86::ATOMUMIN8:
12897 case X86::ATOMUMIN16:
12898 case X86::ATOMUMIN32:
12899 case X86::ATOMUMIN64: {
12901 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12903 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12907 if (Subtarget->hasCMov()) {
12908 if (VT != MVT::i8) {
12910 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12914 // Promote i8 to i32 to use CMOV32
12915 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12916 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12917 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12918 unsigned t2 = MRI.createVirtualRegister(RC32);
12920 unsigned Undef = MRI.createVirtualRegister(RC32);
12921 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12923 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12926 .addImm(X86::sub_8bit);
12927 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12930 .addImm(X86::sub_8bit);
12932 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12936 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12937 .addReg(t2, 0, X86::sub_8bit);
12940 // Use pseudo select and lower them.
12941 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12942 "Invalid atomic-load-op transformation!");
12943 unsigned SelOpc = getPseudoCMOVOpc(VT);
12944 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12945 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12946 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12947 .addReg(SrcReg).addReg(AccReg)
12949 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12955 // Copy AccPhyReg back from virtual register.
12956 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12959 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12960 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12961 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12963 MIB.setMemRefs(MMOBegin, MMOEnd);
12965 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12967 mainMBB->addSuccessor(origMainMBB);
12968 mainMBB->addSuccessor(sinkMBB);
12971 sinkMBB->addLiveIn(AccPhyReg);
12973 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12974 TII->get(TargetOpcode::COPY), DstReg)
12975 .addReg(AccPhyReg);
12977 MI->eraseFromParent();
12981 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12982 // instructions. They will be translated into a spin-loop or compare-exchange
12986 // dst = atomic-fetch-op MI.addr, MI.val
12992 // EAX = LOAD [MI.addr + 0]
12993 // EDX = LOAD [MI.addr + 4]
12995 // EBX = OP MI.val.lo, EAX
12996 // ECX = OP MI.val.hi, EDX
12997 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13002 MachineBasicBlock *
13003 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13004 MachineBasicBlock *MBB) const {
13005 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13006 DebugLoc DL = MI->getDebugLoc();
13008 MachineFunction *MF = MBB->getParent();
13009 MachineRegisterInfo &MRI = MF->getRegInfo();
13011 const BasicBlock *BB = MBB->getBasicBlock();
13012 MachineFunction::iterator I = MBB;
13015 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13016 "Unexpected number of operands");
13018 assert(MI->hasOneMemOperand() &&
13019 "Expected atomic-load-op32 to have one memoperand");
13021 // Memory Reference
13022 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13023 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13025 unsigned DstLoReg, DstHiReg;
13026 unsigned SrcLoReg, SrcHiReg;
13027 unsigned MemOpndSlot;
13029 unsigned CurOp = 0;
13031 DstLoReg = MI->getOperand(CurOp++).getReg();
13032 DstHiReg = MI->getOperand(CurOp++).getReg();
13033 MemOpndSlot = CurOp;
13034 CurOp += X86::AddrNumOperands;
13035 SrcLoReg = MI->getOperand(CurOp++).getReg();
13036 SrcHiReg = MI->getOperand(CurOp++).getReg();
13038 const TargetRegisterClass *RC = &X86::GR32RegClass;
13039 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13041 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13042 unsigned LOADOpc = X86::MOV32rm;
13044 // For the atomic load-arith operator, we generate
13047 // EAX = LOAD [MI.addr + 0]
13048 // EDX = LOAD [MI.addr + 4]
13050 // EBX = OP MI.vallo, EAX
13051 // ECX = OP MI.valhi, EDX
13052 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13056 MachineBasicBlock *thisMBB = MBB;
13057 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13058 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13059 MF->insert(I, mainMBB);
13060 MF->insert(I, sinkMBB);
13062 MachineInstrBuilder MIB;
13064 // Transfer the remainder of BB and its successor edges to sinkMBB.
13065 sinkMBB->splice(sinkMBB->begin(), MBB,
13066 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13067 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13071 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13072 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13073 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13074 MIB.setMemRefs(MMOBegin, MMOEnd);
13076 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13077 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13078 if (i == X86::AddrDisp)
13079 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13081 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13083 MIB.setMemRefs(MMOBegin, MMOEnd);
13085 thisMBB->addSuccessor(mainMBB);
13088 MachineBasicBlock *origMainMBB = mainMBB;
13089 mainMBB->addLiveIn(X86::EAX);
13090 mainMBB->addLiveIn(X86::EDX);
13092 // Copy EDX:EAX as they are used more than once.
13093 unsigned LoReg = MRI.createVirtualRegister(RC);
13094 unsigned HiReg = MRI.createVirtualRegister(RC);
13095 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13096 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13098 unsigned t1L = MRI.createVirtualRegister(RC);
13099 unsigned t1H = MRI.createVirtualRegister(RC);
13101 unsigned Opc = MI->getOpcode();
13104 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13105 case X86::ATOMAND6432:
13106 case X86::ATOMOR6432:
13107 case X86::ATOMXOR6432:
13108 case X86::ATOMADD6432:
13109 case X86::ATOMSUB6432: {
13111 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13112 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13113 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13116 case X86::ATOMNAND6432: {
13117 unsigned HiOpc, NOTOpc;
13118 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13119 unsigned t2L = MRI.createVirtualRegister(RC);
13120 unsigned t2H = MRI.createVirtualRegister(RC);
13121 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13122 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13123 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13124 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13127 case X86::ATOMMAX6432:
13128 case X86::ATOMMIN6432:
13129 case X86::ATOMUMAX6432:
13130 case X86::ATOMUMIN6432: {
13132 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13133 unsigned cL = MRI.createVirtualRegister(RC8);
13134 unsigned cH = MRI.createVirtualRegister(RC8);
13135 unsigned cL32 = MRI.createVirtualRegister(RC);
13136 unsigned cH32 = MRI.createVirtualRegister(RC);
13137 unsigned cc = MRI.createVirtualRegister(RC);
13138 // cl := cmp src_lo, lo
13139 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13140 .addReg(SrcLoReg).addReg(LoReg);
13141 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13142 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13143 // ch := cmp src_hi, hi
13144 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13145 .addReg(SrcHiReg).addReg(HiReg);
13146 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13147 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13148 // cc := if (src_hi == hi) ? cl : ch;
13149 if (Subtarget->hasCMov()) {
13150 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13151 .addReg(cH32).addReg(cL32);
13153 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13154 .addReg(cH32).addReg(cL32)
13155 .addImm(X86::COND_E);
13156 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13158 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13159 if (Subtarget->hasCMov()) {
13160 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13161 .addReg(SrcLoReg).addReg(LoReg);
13162 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13163 .addReg(SrcHiReg).addReg(HiReg);
13165 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13166 .addReg(SrcLoReg).addReg(LoReg)
13167 .addImm(X86::COND_NE);
13168 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13169 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13170 .addReg(SrcHiReg).addReg(HiReg)
13171 .addImm(X86::COND_NE);
13172 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13176 case X86::ATOMSWAP6432: {
13178 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13179 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13180 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13185 // Copy EDX:EAX back from HiReg:LoReg
13186 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13187 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13188 // Copy ECX:EBX from t1H:t1L
13189 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13190 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13192 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13193 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13194 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13195 MIB.setMemRefs(MMOBegin, MMOEnd);
13197 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13199 mainMBB->addSuccessor(origMainMBB);
13200 mainMBB->addSuccessor(sinkMBB);
13203 sinkMBB->addLiveIn(X86::EAX);
13204 sinkMBB->addLiveIn(X86::EDX);
13206 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13207 TII->get(TargetOpcode::COPY), DstLoReg)
13209 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13210 TII->get(TargetOpcode::COPY), DstHiReg)
13213 MI->eraseFromParent();
13217 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13218 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13219 // in the .td file.
13220 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13221 const TargetInstrInfo *TII) {
13223 switch (MI->getOpcode()) {
13224 default: llvm_unreachable("illegal opcode!");
13225 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
13226 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13227 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
13228 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13229 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
13230 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13231 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
13232 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13235 DebugLoc dl = MI->getDebugLoc();
13236 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13238 unsigned NumArgs = MI->getNumOperands();
13239 for (unsigned i = 1; i < NumArgs; ++i) {
13240 MachineOperand &Op = MI->getOperand(i);
13241 if (!(Op.isReg() && Op.isImplicit()))
13242 MIB.addOperand(Op);
13244 if (MI->hasOneMemOperand())
13245 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13247 BuildMI(*BB, MI, dl,
13248 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13249 .addReg(X86::XMM0);
13251 MI->eraseFromParent();
13255 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13256 // defs in an instruction pattern
13257 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13258 const TargetInstrInfo *TII) {
13260 switch (MI->getOpcode()) {
13261 default: llvm_unreachable("illegal opcode!");
13262 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
13263 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13264 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
13265 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13266 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13267 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13268 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13269 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13272 DebugLoc dl = MI->getDebugLoc();
13273 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13275 unsigned NumArgs = MI->getNumOperands(); // remove the results
13276 for (unsigned i = 1; i < NumArgs; ++i) {
13277 MachineOperand &Op = MI->getOperand(i);
13278 if (!(Op.isReg() && Op.isImplicit()))
13279 MIB.addOperand(Op);
13281 if (MI->hasOneMemOperand())
13282 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13284 BuildMI(*BB, MI, dl,
13285 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13288 MI->eraseFromParent();
13292 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13293 const TargetInstrInfo *TII,
13294 const X86Subtarget* Subtarget) {
13295 DebugLoc dl = MI->getDebugLoc();
13297 // Address into RAX/EAX, other two args into ECX, EDX.
13298 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13299 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13300 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13301 for (int i = 0; i < X86::AddrNumOperands; ++i)
13302 MIB.addOperand(MI->getOperand(i));
13304 unsigned ValOps = X86::AddrNumOperands;
13305 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13306 .addReg(MI->getOperand(ValOps).getReg());
13307 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13308 .addReg(MI->getOperand(ValOps+1).getReg());
13310 // The instruction doesn't actually take any operands though.
13311 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13313 MI->eraseFromParent(); // The pseudo is gone now.
13317 MachineBasicBlock *
13318 X86TargetLowering::EmitVAARG64WithCustomInserter(
13320 MachineBasicBlock *MBB) const {
13321 // Emit va_arg instruction on X86-64.
13323 // Operands to this pseudo-instruction:
13324 // 0 ) Output : destination address (reg)
13325 // 1-5) Input : va_list address (addr, i64mem)
13326 // 6 ) ArgSize : Size (in bytes) of vararg type
13327 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13328 // 8 ) Align : Alignment of type
13329 // 9 ) EFLAGS (implicit-def)
13331 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13332 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13334 unsigned DestReg = MI->getOperand(0).getReg();
13335 MachineOperand &Base = MI->getOperand(1);
13336 MachineOperand &Scale = MI->getOperand(2);
13337 MachineOperand &Index = MI->getOperand(3);
13338 MachineOperand &Disp = MI->getOperand(4);
13339 MachineOperand &Segment = MI->getOperand(5);
13340 unsigned ArgSize = MI->getOperand(6).getImm();
13341 unsigned ArgMode = MI->getOperand(7).getImm();
13342 unsigned Align = MI->getOperand(8).getImm();
13344 // Memory Reference
13345 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13346 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13347 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13349 // Machine Information
13350 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13351 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13352 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13353 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13354 DebugLoc DL = MI->getDebugLoc();
13356 // struct va_list {
13359 // i64 overflow_area (address)
13360 // i64 reg_save_area (address)
13362 // sizeof(va_list) = 24
13363 // alignment(va_list) = 8
13365 unsigned TotalNumIntRegs = 6;
13366 unsigned TotalNumXMMRegs = 8;
13367 bool UseGPOffset = (ArgMode == 1);
13368 bool UseFPOffset = (ArgMode == 2);
13369 unsigned MaxOffset = TotalNumIntRegs * 8 +
13370 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13372 /* Align ArgSize to a multiple of 8 */
13373 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13374 bool NeedsAlign = (Align > 8);
13376 MachineBasicBlock *thisMBB = MBB;
13377 MachineBasicBlock *overflowMBB;
13378 MachineBasicBlock *offsetMBB;
13379 MachineBasicBlock *endMBB;
13381 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13382 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13383 unsigned OffsetReg = 0;
13385 if (!UseGPOffset && !UseFPOffset) {
13386 // If we only pull from the overflow region, we don't create a branch.
13387 // We don't need to alter control flow.
13388 OffsetDestReg = 0; // unused
13389 OverflowDestReg = DestReg;
13392 overflowMBB = thisMBB;
13395 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13396 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13397 // If not, pull from overflow_area. (branch to overflowMBB)
13402 // offsetMBB overflowMBB
13407 // Registers for the PHI in endMBB
13408 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13409 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13411 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13412 MachineFunction *MF = MBB->getParent();
13413 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13414 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13415 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13417 MachineFunction::iterator MBBIter = MBB;
13420 // Insert the new basic blocks
13421 MF->insert(MBBIter, offsetMBB);
13422 MF->insert(MBBIter, overflowMBB);
13423 MF->insert(MBBIter, endMBB);
13425 // Transfer the remainder of MBB and its successor edges to endMBB.
13426 endMBB->splice(endMBB->begin(), thisMBB,
13427 llvm::next(MachineBasicBlock::iterator(MI)),
13429 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13431 // Make offsetMBB and overflowMBB successors of thisMBB
13432 thisMBB->addSuccessor(offsetMBB);
13433 thisMBB->addSuccessor(overflowMBB);
13435 // endMBB is a successor of both offsetMBB and overflowMBB
13436 offsetMBB->addSuccessor(endMBB);
13437 overflowMBB->addSuccessor(endMBB);
13439 // Load the offset value into a register
13440 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13441 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13445 .addDisp(Disp, UseFPOffset ? 4 : 0)
13446 .addOperand(Segment)
13447 .setMemRefs(MMOBegin, MMOEnd);
13449 // Check if there is enough room left to pull this argument.
13450 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13452 .addImm(MaxOffset + 8 - ArgSizeA8);
13454 // Branch to "overflowMBB" if offset >= max
13455 // Fall through to "offsetMBB" otherwise
13456 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13457 .addMBB(overflowMBB);
13460 // In offsetMBB, emit code to use the reg_save_area.
13462 assert(OffsetReg != 0);
13464 // Read the reg_save_area address.
13465 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13466 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13471 .addOperand(Segment)
13472 .setMemRefs(MMOBegin, MMOEnd);
13474 // Zero-extend the offset
13475 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13476 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13479 .addImm(X86::sub_32bit);
13481 // Add the offset to the reg_save_area to get the final address.
13482 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13483 .addReg(OffsetReg64)
13484 .addReg(RegSaveReg);
13486 // Compute the offset for the next argument
13487 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13488 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13490 .addImm(UseFPOffset ? 16 : 8);
13492 // Store it back into the va_list.
13493 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13497 .addDisp(Disp, UseFPOffset ? 4 : 0)
13498 .addOperand(Segment)
13499 .addReg(NextOffsetReg)
13500 .setMemRefs(MMOBegin, MMOEnd);
13503 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13508 // Emit code to use overflow area
13511 // Load the overflow_area address into a register.
13512 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13513 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13518 .addOperand(Segment)
13519 .setMemRefs(MMOBegin, MMOEnd);
13521 // If we need to align it, do so. Otherwise, just copy the address
13522 // to OverflowDestReg.
13524 // Align the overflow address
13525 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13526 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13528 // aligned_addr = (addr + (align-1)) & ~(align-1)
13529 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13530 .addReg(OverflowAddrReg)
13533 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13535 .addImm(~(uint64_t)(Align-1));
13537 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13538 .addReg(OverflowAddrReg);
13541 // Compute the next overflow address after this argument.
13542 // (the overflow address should be kept 8-byte aligned)
13543 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13544 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13545 .addReg(OverflowDestReg)
13546 .addImm(ArgSizeA8);
13548 // Store the new overflow address.
13549 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13554 .addOperand(Segment)
13555 .addReg(NextAddrReg)
13556 .setMemRefs(MMOBegin, MMOEnd);
13558 // If we branched, emit the PHI to the front of endMBB.
13560 BuildMI(*endMBB, endMBB->begin(), DL,
13561 TII->get(X86::PHI), DestReg)
13562 .addReg(OffsetDestReg).addMBB(offsetMBB)
13563 .addReg(OverflowDestReg).addMBB(overflowMBB);
13566 // Erase the pseudo instruction
13567 MI->eraseFromParent();
13572 MachineBasicBlock *
13573 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13575 MachineBasicBlock *MBB) const {
13576 // Emit code to save XMM registers to the stack. The ABI says that the
13577 // number of registers to save is given in %al, so it's theoretically
13578 // possible to do an indirect jump trick to avoid saving all of them,
13579 // however this code takes a simpler approach and just executes all
13580 // of the stores if %al is non-zero. It's less code, and it's probably
13581 // easier on the hardware branch predictor, and stores aren't all that
13582 // expensive anyway.
13584 // Create the new basic blocks. One block contains all the XMM stores,
13585 // and one block is the final destination regardless of whether any
13586 // stores were performed.
13587 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13588 MachineFunction *F = MBB->getParent();
13589 MachineFunction::iterator MBBIter = MBB;
13591 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13592 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13593 F->insert(MBBIter, XMMSaveMBB);
13594 F->insert(MBBIter, EndMBB);
13596 // Transfer the remainder of MBB and its successor edges to EndMBB.
13597 EndMBB->splice(EndMBB->begin(), MBB,
13598 llvm::next(MachineBasicBlock::iterator(MI)),
13600 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13602 // The original block will now fall through to the XMM save block.
13603 MBB->addSuccessor(XMMSaveMBB);
13604 // The XMMSaveMBB will fall through to the end block.
13605 XMMSaveMBB->addSuccessor(EndMBB);
13607 // Now add the instructions.
13608 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13609 DebugLoc DL = MI->getDebugLoc();
13611 unsigned CountReg = MI->getOperand(0).getReg();
13612 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13613 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13615 if (!Subtarget->isTargetWin64()) {
13616 // If %al is 0, branch around the XMM save block.
13617 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13618 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13619 MBB->addSuccessor(EndMBB);
13622 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13623 // In the XMM save block, save all the XMM argument registers.
13624 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13625 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13626 MachineMemOperand *MMO =
13627 F->getMachineMemOperand(
13628 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13629 MachineMemOperand::MOStore,
13630 /*Size=*/16, /*Align=*/16);
13631 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13632 .addFrameIndex(RegSaveFrameIndex)
13633 .addImm(/*Scale=*/1)
13634 .addReg(/*IndexReg=*/0)
13635 .addImm(/*Disp=*/Offset)
13636 .addReg(/*Segment=*/0)
13637 .addReg(MI->getOperand(i).getReg())
13638 .addMemOperand(MMO);
13641 MI->eraseFromParent(); // The pseudo instruction is gone now.
13646 // The EFLAGS operand of SelectItr might be missing a kill marker
13647 // because there were multiple uses of EFLAGS, and ISel didn't know
13648 // which to mark. Figure out whether SelectItr should have had a
13649 // kill marker, and set it if it should. Returns the correct kill
13651 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13652 MachineBasicBlock* BB,
13653 const TargetRegisterInfo* TRI) {
13654 // Scan forward through BB for a use/def of EFLAGS.
13655 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13656 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13657 const MachineInstr& mi = *miI;
13658 if (mi.readsRegister(X86::EFLAGS))
13660 if (mi.definesRegister(X86::EFLAGS))
13661 break; // Should have kill-flag - update below.
13664 // If we hit the end of the block, check whether EFLAGS is live into a
13666 if (miI == BB->end()) {
13667 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13668 sEnd = BB->succ_end();
13669 sItr != sEnd; ++sItr) {
13670 MachineBasicBlock* succ = *sItr;
13671 if (succ->isLiveIn(X86::EFLAGS))
13676 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13677 // out. SelectMI should have a kill flag on EFLAGS.
13678 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13682 MachineBasicBlock *
13683 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13684 MachineBasicBlock *BB) const {
13685 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13686 DebugLoc DL = MI->getDebugLoc();
13688 // To "insert" a SELECT_CC instruction, we actually have to insert the
13689 // diamond control-flow pattern. The incoming instruction knows the
13690 // destination vreg to set, the condition code register to branch on, the
13691 // true/false values to select between, and a branch opcode to use.
13692 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13693 MachineFunction::iterator It = BB;
13699 // cmpTY ccX, r1, r2
13701 // fallthrough --> copy0MBB
13702 MachineBasicBlock *thisMBB = BB;
13703 MachineFunction *F = BB->getParent();
13704 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13705 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13706 F->insert(It, copy0MBB);
13707 F->insert(It, sinkMBB);
13709 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13710 // live into the sink and copy blocks.
13711 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13712 if (!MI->killsRegister(X86::EFLAGS) &&
13713 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13714 copy0MBB->addLiveIn(X86::EFLAGS);
13715 sinkMBB->addLiveIn(X86::EFLAGS);
13718 // Transfer the remainder of BB and its successor edges to sinkMBB.
13719 sinkMBB->splice(sinkMBB->begin(), BB,
13720 llvm::next(MachineBasicBlock::iterator(MI)),
13722 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13724 // Add the true and fallthrough blocks as its successors.
13725 BB->addSuccessor(copy0MBB);
13726 BB->addSuccessor(sinkMBB);
13728 // Create the conditional branch instruction.
13730 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13731 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13734 // %FalseValue = ...
13735 // # fallthrough to sinkMBB
13736 copy0MBB->addSuccessor(sinkMBB);
13739 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13741 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13742 TII->get(X86::PHI), MI->getOperand(0).getReg())
13743 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13744 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13746 MI->eraseFromParent(); // The pseudo instruction is gone now.
13750 MachineBasicBlock *
13751 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13752 bool Is64Bit) const {
13753 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13754 DebugLoc DL = MI->getDebugLoc();
13755 MachineFunction *MF = BB->getParent();
13756 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13758 assert(getTargetMachine().Options.EnableSegmentedStacks);
13760 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13761 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13764 // ... [Till the alloca]
13765 // If stacklet is not large enough, jump to mallocMBB
13768 // Allocate by subtracting from RSP
13769 // Jump to continueMBB
13772 // Allocate by call to runtime
13776 // [rest of original BB]
13779 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13780 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13781 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13783 MachineRegisterInfo &MRI = MF->getRegInfo();
13784 const TargetRegisterClass *AddrRegClass =
13785 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13787 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13788 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13789 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13790 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13791 sizeVReg = MI->getOperand(1).getReg(),
13792 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13794 MachineFunction::iterator MBBIter = BB;
13797 MF->insert(MBBIter, bumpMBB);
13798 MF->insert(MBBIter, mallocMBB);
13799 MF->insert(MBBIter, continueMBB);
13801 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13802 (MachineBasicBlock::iterator(MI)), BB->end());
13803 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13805 // Add code to the main basic block to check if the stack limit has been hit,
13806 // and if so, jump to mallocMBB otherwise to bumpMBB.
13807 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13808 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13809 .addReg(tmpSPVReg).addReg(sizeVReg);
13810 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13811 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13812 .addReg(SPLimitVReg);
13813 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13815 // bumpMBB simply decreases the stack pointer, since we know the current
13816 // stacklet has enough space.
13817 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13818 .addReg(SPLimitVReg);
13819 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13820 .addReg(SPLimitVReg);
13821 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13823 // Calls into a routine in libgcc to allocate more space from the heap.
13824 const uint32_t *RegMask =
13825 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13827 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13829 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13830 .addExternalSymbol("__morestack_allocate_stack_space")
13831 .addRegMask(RegMask)
13832 .addReg(X86::RDI, RegState::Implicit)
13833 .addReg(X86::RAX, RegState::ImplicitDefine);
13835 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13837 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13838 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13839 .addExternalSymbol("__morestack_allocate_stack_space")
13840 .addRegMask(RegMask)
13841 .addReg(X86::EAX, RegState::ImplicitDefine);
13845 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13848 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13849 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13850 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13852 // Set up the CFG correctly.
13853 BB->addSuccessor(bumpMBB);
13854 BB->addSuccessor(mallocMBB);
13855 mallocMBB->addSuccessor(continueMBB);
13856 bumpMBB->addSuccessor(continueMBB);
13858 // Take care of the PHI nodes.
13859 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13860 MI->getOperand(0).getReg())
13861 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13862 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13864 // Delete the original pseudo instruction.
13865 MI->eraseFromParent();
13868 return continueMBB;
13871 MachineBasicBlock *
13872 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13873 MachineBasicBlock *BB) const {
13874 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13875 DebugLoc DL = MI->getDebugLoc();
13877 assert(!Subtarget->isTargetEnvMacho());
13879 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13880 // non-trivial part is impdef of ESP.
13882 if (Subtarget->isTargetWin64()) {
13883 if (Subtarget->isTargetCygMing()) {
13884 // ___chkstk(Mingw64):
13885 // Clobbers R10, R11, RAX and EFLAGS.
13887 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13888 .addExternalSymbol("___chkstk")
13889 .addReg(X86::RAX, RegState::Implicit)
13890 .addReg(X86::RSP, RegState::Implicit)
13891 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13892 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13893 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13895 // __chkstk(MSVCRT): does not update stack pointer.
13896 // Clobbers R10, R11 and EFLAGS.
13897 // FIXME: RAX(allocated size) might be reused and not killed.
13898 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13899 .addExternalSymbol("__chkstk")
13900 .addReg(X86::RAX, RegState::Implicit)
13901 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13902 // RAX has the offset to subtracted from RSP.
13903 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13908 const char *StackProbeSymbol =
13909 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13911 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13912 .addExternalSymbol(StackProbeSymbol)
13913 .addReg(X86::EAX, RegState::Implicit)
13914 .addReg(X86::ESP, RegState::Implicit)
13915 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13916 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13917 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13920 MI->eraseFromParent(); // The pseudo instruction is gone now.
13924 MachineBasicBlock *
13925 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13926 MachineBasicBlock *BB) const {
13927 // This is pretty easy. We're taking the value that we received from
13928 // our load from the relocation, sticking it in either RDI (x86-64)
13929 // or EAX and doing an indirect call. The return value will then
13930 // be in the normal return register.
13931 const X86InstrInfo *TII
13932 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13933 DebugLoc DL = MI->getDebugLoc();
13934 MachineFunction *F = BB->getParent();
13936 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13937 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13939 // Get a register mask for the lowered call.
13940 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13941 // proper register mask.
13942 const uint32_t *RegMask =
13943 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13944 if (Subtarget->is64Bit()) {
13945 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13946 TII->get(X86::MOV64rm), X86::RDI)
13948 .addImm(0).addReg(0)
13949 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13950 MI->getOperand(3).getTargetFlags())
13952 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13953 addDirectMem(MIB, X86::RDI);
13954 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13955 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13956 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13957 TII->get(X86::MOV32rm), X86::EAX)
13959 .addImm(0).addReg(0)
13960 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13961 MI->getOperand(3).getTargetFlags())
13963 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13964 addDirectMem(MIB, X86::EAX);
13965 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13967 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13968 TII->get(X86::MOV32rm), X86::EAX)
13969 .addReg(TII->getGlobalBaseReg(F))
13970 .addImm(0).addReg(0)
13971 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13972 MI->getOperand(3).getTargetFlags())
13974 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13975 addDirectMem(MIB, X86::EAX);
13976 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13979 MI->eraseFromParent(); // The pseudo instruction is gone now.
13983 MachineBasicBlock *
13984 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13985 MachineBasicBlock *MBB) const {
13986 DebugLoc DL = MI->getDebugLoc();
13987 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13989 MachineFunction *MF = MBB->getParent();
13990 MachineRegisterInfo &MRI = MF->getRegInfo();
13992 const BasicBlock *BB = MBB->getBasicBlock();
13993 MachineFunction::iterator I = MBB;
13996 // Memory Reference
13997 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13998 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14001 unsigned MemOpndSlot = 0;
14003 unsigned CurOp = 0;
14005 DstReg = MI->getOperand(CurOp++).getReg();
14006 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14007 assert(RC->hasType(MVT::i32) && "Invalid destination!");
14008 unsigned mainDstReg = MRI.createVirtualRegister(RC);
14009 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14011 MemOpndSlot = CurOp;
14013 MVT PVT = getPointerTy();
14014 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14015 "Invalid Pointer Size!");
14017 // For v = setjmp(buf), we generate
14020 // buf[LabelOffset] = restoreMBB
14021 // SjLjSetup restoreMBB
14027 // v = phi(main, restore)
14032 MachineBasicBlock *thisMBB = MBB;
14033 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14034 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14035 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14036 MF->insert(I, mainMBB);
14037 MF->insert(I, sinkMBB);
14038 MF->push_back(restoreMBB);
14040 MachineInstrBuilder MIB;
14042 // Transfer the remainder of BB and its successor edges to sinkMBB.
14043 sinkMBB->splice(sinkMBB->begin(), MBB,
14044 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14045 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14048 unsigned PtrStoreOpc = 0;
14049 unsigned LabelReg = 0;
14050 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14051 Reloc::Model RM = getTargetMachine().getRelocationModel();
14052 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14053 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14055 // Prepare IP either in reg or imm.
14056 if (!UseImmLabel) {
14057 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14058 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14059 LabelReg = MRI.createVirtualRegister(PtrRC);
14060 if (Subtarget->is64Bit()) {
14061 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14065 .addMBB(restoreMBB)
14068 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14069 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14070 .addReg(XII->getGlobalBaseReg(MF))
14073 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14077 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14079 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14080 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14081 if (i == X86::AddrDisp)
14082 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14084 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14087 MIB.addReg(LabelReg);
14089 MIB.addMBB(restoreMBB);
14090 MIB.setMemRefs(MMOBegin, MMOEnd);
14092 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14093 .addMBB(restoreMBB);
14094 MIB.addRegMask(RegInfo->getNoPreservedMask());
14095 thisMBB->addSuccessor(mainMBB);
14096 thisMBB->addSuccessor(restoreMBB);
14100 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14101 mainMBB->addSuccessor(sinkMBB);
14104 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14105 TII->get(X86::PHI), DstReg)
14106 .addReg(mainDstReg).addMBB(mainMBB)
14107 .addReg(restoreDstReg).addMBB(restoreMBB);
14110 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14111 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14112 restoreMBB->addSuccessor(sinkMBB);
14114 MI->eraseFromParent();
14118 MachineBasicBlock *
14119 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14120 MachineBasicBlock *MBB) const {
14121 DebugLoc DL = MI->getDebugLoc();
14122 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14124 MachineFunction *MF = MBB->getParent();
14125 MachineRegisterInfo &MRI = MF->getRegInfo();
14127 // Memory Reference
14128 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14129 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14131 MVT PVT = getPointerTy();
14132 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14133 "Invalid Pointer Size!");
14135 const TargetRegisterClass *RC =
14136 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14137 unsigned Tmp = MRI.createVirtualRegister(RC);
14138 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14139 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14140 unsigned SP = RegInfo->getStackRegister();
14142 MachineInstrBuilder MIB;
14144 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14145 const int64_t SPOffset = 2 * PVT.getStoreSize();
14147 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14148 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14151 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14152 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14153 MIB.addOperand(MI->getOperand(i));
14154 MIB.setMemRefs(MMOBegin, MMOEnd);
14156 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14157 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14158 if (i == X86::AddrDisp)
14159 MIB.addDisp(MI->getOperand(i), LabelOffset);
14161 MIB.addOperand(MI->getOperand(i));
14163 MIB.setMemRefs(MMOBegin, MMOEnd);
14165 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14166 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14167 if (i == X86::AddrDisp)
14168 MIB.addDisp(MI->getOperand(i), SPOffset);
14170 MIB.addOperand(MI->getOperand(i));
14172 MIB.setMemRefs(MMOBegin, MMOEnd);
14174 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14176 MI->eraseFromParent();
14180 MachineBasicBlock *
14181 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14182 MachineBasicBlock *BB) const {
14183 switch (MI->getOpcode()) {
14184 default: llvm_unreachable("Unexpected instr type to insert");
14185 case X86::TAILJMPd64:
14186 case X86::TAILJMPr64:
14187 case X86::TAILJMPm64:
14188 llvm_unreachable("TAILJMP64 would not be touched here.");
14189 case X86::TCRETURNdi64:
14190 case X86::TCRETURNri64:
14191 case X86::TCRETURNmi64:
14193 case X86::WIN_ALLOCA:
14194 return EmitLoweredWinAlloca(MI, BB);
14195 case X86::SEG_ALLOCA_32:
14196 return EmitLoweredSegAlloca(MI, BB, false);
14197 case X86::SEG_ALLOCA_64:
14198 return EmitLoweredSegAlloca(MI, BB, true);
14199 case X86::TLSCall_32:
14200 case X86::TLSCall_64:
14201 return EmitLoweredTLSCall(MI, BB);
14202 case X86::CMOV_GR8:
14203 case X86::CMOV_FR32:
14204 case X86::CMOV_FR64:
14205 case X86::CMOV_V4F32:
14206 case X86::CMOV_V2F64:
14207 case X86::CMOV_V2I64:
14208 case X86::CMOV_V8F32:
14209 case X86::CMOV_V4F64:
14210 case X86::CMOV_V4I64:
14211 case X86::CMOV_GR16:
14212 case X86::CMOV_GR32:
14213 case X86::CMOV_RFP32:
14214 case X86::CMOV_RFP64:
14215 case X86::CMOV_RFP80:
14216 return EmitLoweredSelect(MI, BB);
14218 case X86::FP32_TO_INT16_IN_MEM:
14219 case X86::FP32_TO_INT32_IN_MEM:
14220 case X86::FP32_TO_INT64_IN_MEM:
14221 case X86::FP64_TO_INT16_IN_MEM:
14222 case X86::FP64_TO_INT32_IN_MEM:
14223 case X86::FP64_TO_INT64_IN_MEM:
14224 case X86::FP80_TO_INT16_IN_MEM:
14225 case X86::FP80_TO_INT32_IN_MEM:
14226 case X86::FP80_TO_INT64_IN_MEM: {
14227 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14228 DebugLoc DL = MI->getDebugLoc();
14230 // Change the floating point control register to use "round towards zero"
14231 // mode when truncating to an integer value.
14232 MachineFunction *F = BB->getParent();
14233 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14234 addFrameReference(BuildMI(*BB, MI, DL,
14235 TII->get(X86::FNSTCW16m)), CWFrameIdx);
14237 // Load the old value of the high byte of the control word...
14239 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14240 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14243 // Set the high part to be round to zero...
14244 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14247 // Reload the modified control word now...
14248 addFrameReference(BuildMI(*BB, MI, DL,
14249 TII->get(X86::FLDCW16m)), CWFrameIdx);
14251 // Restore the memory image of control word to original value
14252 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14255 // Get the X86 opcode to use.
14257 switch (MI->getOpcode()) {
14258 default: llvm_unreachable("illegal opcode!");
14259 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14260 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14261 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14262 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14263 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14264 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14265 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14266 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14267 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14271 MachineOperand &Op = MI->getOperand(0);
14273 AM.BaseType = X86AddressMode::RegBase;
14274 AM.Base.Reg = Op.getReg();
14276 AM.BaseType = X86AddressMode::FrameIndexBase;
14277 AM.Base.FrameIndex = Op.getIndex();
14279 Op = MI->getOperand(1);
14281 AM.Scale = Op.getImm();
14282 Op = MI->getOperand(2);
14284 AM.IndexReg = Op.getImm();
14285 Op = MI->getOperand(3);
14286 if (Op.isGlobal()) {
14287 AM.GV = Op.getGlobal();
14289 AM.Disp = Op.getImm();
14291 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14292 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14294 // Reload the original control word now.
14295 addFrameReference(BuildMI(*BB, MI, DL,
14296 TII->get(X86::FLDCW16m)), CWFrameIdx);
14298 MI->eraseFromParent(); // The pseudo instruction is gone now.
14301 // String/text processing lowering.
14302 case X86::PCMPISTRM128REG:
14303 case X86::VPCMPISTRM128REG:
14304 case X86::PCMPISTRM128MEM:
14305 case X86::VPCMPISTRM128MEM:
14306 case X86::PCMPESTRM128REG:
14307 case X86::VPCMPESTRM128REG:
14308 case X86::PCMPESTRM128MEM:
14309 case X86::VPCMPESTRM128MEM:
14310 assert(Subtarget->hasSSE42() &&
14311 "Target must have SSE4.2 or AVX features enabled");
14312 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14314 // String/text processing lowering.
14315 case X86::PCMPISTRIREG:
14316 case X86::VPCMPISTRIREG:
14317 case X86::PCMPISTRIMEM:
14318 case X86::VPCMPISTRIMEM:
14319 case X86::PCMPESTRIREG:
14320 case X86::VPCMPESTRIREG:
14321 case X86::PCMPESTRIMEM:
14322 case X86::VPCMPESTRIMEM:
14323 assert(Subtarget->hasSSE42() &&
14324 "Target must have SSE4.2 or AVX features enabled");
14325 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14327 // Thread synchronization.
14329 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14333 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14335 // Atomic Lowering.
14336 case X86::ATOMAND8:
14337 case X86::ATOMAND16:
14338 case X86::ATOMAND32:
14339 case X86::ATOMAND64:
14342 case X86::ATOMOR16:
14343 case X86::ATOMOR32:
14344 case X86::ATOMOR64:
14346 case X86::ATOMXOR16:
14347 case X86::ATOMXOR8:
14348 case X86::ATOMXOR32:
14349 case X86::ATOMXOR64:
14351 case X86::ATOMNAND8:
14352 case X86::ATOMNAND16:
14353 case X86::ATOMNAND32:
14354 case X86::ATOMNAND64:
14356 case X86::ATOMMAX8:
14357 case X86::ATOMMAX16:
14358 case X86::ATOMMAX32:
14359 case X86::ATOMMAX64:
14361 case X86::ATOMMIN8:
14362 case X86::ATOMMIN16:
14363 case X86::ATOMMIN32:
14364 case X86::ATOMMIN64:
14366 case X86::ATOMUMAX8:
14367 case X86::ATOMUMAX16:
14368 case X86::ATOMUMAX32:
14369 case X86::ATOMUMAX64:
14371 case X86::ATOMUMIN8:
14372 case X86::ATOMUMIN16:
14373 case X86::ATOMUMIN32:
14374 case X86::ATOMUMIN64:
14375 return EmitAtomicLoadArith(MI, BB);
14377 // This group does 64-bit operations on a 32-bit host.
14378 case X86::ATOMAND6432:
14379 case X86::ATOMOR6432:
14380 case X86::ATOMXOR6432:
14381 case X86::ATOMNAND6432:
14382 case X86::ATOMADD6432:
14383 case X86::ATOMSUB6432:
14384 case X86::ATOMMAX6432:
14385 case X86::ATOMMIN6432:
14386 case X86::ATOMUMAX6432:
14387 case X86::ATOMUMIN6432:
14388 case X86::ATOMSWAP6432:
14389 return EmitAtomicLoadArith6432(MI, BB);
14391 case X86::VASTART_SAVE_XMM_REGS:
14392 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14394 case X86::VAARG_64:
14395 return EmitVAARG64WithCustomInserter(MI, BB);
14397 case X86::EH_SjLj_SetJmp32:
14398 case X86::EH_SjLj_SetJmp64:
14399 return emitEHSjLjSetJmp(MI, BB);
14401 case X86::EH_SjLj_LongJmp32:
14402 case X86::EH_SjLj_LongJmp64:
14403 return emitEHSjLjLongJmp(MI, BB);
14407 //===----------------------------------------------------------------------===//
14408 // X86 Optimization Hooks
14409 //===----------------------------------------------------------------------===//
14411 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14414 const SelectionDAG &DAG,
14415 unsigned Depth) const {
14416 unsigned BitWidth = KnownZero.getBitWidth();
14417 unsigned Opc = Op.getOpcode();
14418 assert((Opc >= ISD::BUILTIN_OP_END ||
14419 Opc == ISD::INTRINSIC_WO_CHAIN ||
14420 Opc == ISD::INTRINSIC_W_CHAIN ||
14421 Opc == ISD::INTRINSIC_VOID) &&
14422 "Should use MaskedValueIsZero if you don't know whether Op"
14423 " is a target node!");
14425 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14439 // These nodes' second result is a boolean.
14440 if (Op.getResNo() == 0)
14443 case X86ISD::SETCC:
14444 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14446 case ISD::INTRINSIC_WO_CHAIN: {
14447 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14448 unsigned NumLoBits = 0;
14451 case Intrinsic::x86_sse_movmsk_ps:
14452 case Intrinsic::x86_avx_movmsk_ps_256:
14453 case Intrinsic::x86_sse2_movmsk_pd:
14454 case Intrinsic::x86_avx_movmsk_pd_256:
14455 case Intrinsic::x86_mmx_pmovmskb:
14456 case Intrinsic::x86_sse2_pmovmskb_128:
14457 case Intrinsic::x86_avx2_pmovmskb: {
14458 // High bits of movmskp{s|d}, pmovmskb are known zero.
14460 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14461 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
14462 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
14463 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
14464 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
14465 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
14466 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
14467 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
14469 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14478 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14479 unsigned Depth) const {
14480 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14481 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14482 return Op.getValueType().getScalarType().getSizeInBits();
14488 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14489 /// node is a GlobalAddress + offset.
14490 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14491 const GlobalValue* &GA,
14492 int64_t &Offset) const {
14493 if (N->getOpcode() == X86ISD::Wrapper) {
14494 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14495 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14496 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14500 return TargetLowering::isGAPlusOffset(N, GA, Offset);
14503 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14504 /// same as extracting the high 128-bit part of 256-bit vector and then
14505 /// inserting the result into the low part of a new 256-bit vector
14506 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14507 EVT VT = SVOp->getValueType(0);
14508 unsigned NumElems = VT.getVectorNumElements();
14510 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14511 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14512 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14513 SVOp->getMaskElt(j) >= 0)
14519 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14520 /// same as extracting the low 128-bit part of 256-bit vector and then
14521 /// inserting the result into the high part of a new 256-bit vector
14522 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14523 EVT VT = SVOp->getValueType(0);
14524 unsigned NumElems = VT.getVectorNumElements();
14526 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14527 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14528 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14529 SVOp->getMaskElt(j) >= 0)
14535 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14536 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14537 TargetLowering::DAGCombinerInfo &DCI,
14538 const X86Subtarget* Subtarget) {
14539 DebugLoc dl = N->getDebugLoc();
14540 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14541 SDValue V1 = SVOp->getOperand(0);
14542 SDValue V2 = SVOp->getOperand(1);
14543 EVT VT = SVOp->getValueType(0);
14544 unsigned NumElems = VT.getVectorNumElements();
14546 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14547 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14551 // V UNDEF BUILD_VECTOR UNDEF
14553 // CONCAT_VECTOR CONCAT_VECTOR
14556 // RESULT: V + zero extended
14558 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14559 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14560 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14563 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14566 // To match the shuffle mask, the first half of the mask should
14567 // be exactly the first vector, and all the rest a splat with the
14568 // first element of the second one.
14569 for (unsigned i = 0; i != NumElems/2; ++i)
14570 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14571 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14574 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14575 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14576 if (Ld->hasNUsesOfValue(1, 0)) {
14577 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14578 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14580 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14582 Ld->getPointerInfo(),
14583 Ld->getAlignment(),
14584 false/*isVolatile*/, true/*ReadMem*/,
14585 false/*WriteMem*/);
14587 // Make sure the newly-created LOAD is in the same position as Ld in
14588 // terms of dependency. We create a TokenFactor for Ld and ResNode,
14589 // and update uses of Ld's output chain to use the TokenFactor.
14590 if (Ld->hasAnyUseOfValue(1)) {
14591 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14592 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14593 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14594 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14595 SDValue(ResNode.getNode(), 1));
14598 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14602 // Emit a zeroed vector and insert the desired subvector on its
14604 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14605 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14606 return DCI.CombineTo(N, InsV);
14609 //===--------------------------------------------------------------------===//
14610 // Combine some shuffles into subvector extracts and inserts:
14613 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14614 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14615 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14616 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14617 return DCI.CombineTo(N, InsV);
14620 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14621 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14622 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14623 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14624 return DCI.CombineTo(N, InsV);
14630 /// PerformShuffleCombine - Performs several different shuffle combines.
14631 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14632 TargetLowering::DAGCombinerInfo &DCI,
14633 const X86Subtarget *Subtarget) {
14634 DebugLoc dl = N->getDebugLoc();
14635 EVT VT = N->getValueType(0);
14637 // Don't create instructions with illegal types after legalize types has run.
14638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14639 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14642 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14643 if (Subtarget->hasFp256() && VT.is256BitVector() &&
14644 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14645 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14647 // Only handle 128 wide vector from here on.
14648 if (!VT.is128BitVector())
14651 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14652 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14653 // consecutive, non-overlapping, and in the right order.
14654 SmallVector<SDValue, 16> Elts;
14655 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14656 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14658 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14661 /// PerformTruncateCombine - Converts truncate operation to
14662 /// a sequence of vector shuffle operations.
14663 /// It is possible when we truncate 256-bit vector to 128-bit vector
14664 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14665 TargetLowering::DAGCombinerInfo &DCI,
14666 const X86Subtarget *Subtarget) {
14670 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14671 /// specific shuffle of a load can be folded into a single element load.
14672 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14673 /// shuffles have been customed lowered so we need to handle those here.
14674 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14675 TargetLowering::DAGCombinerInfo &DCI) {
14676 if (DCI.isBeforeLegalizeOps())
14679 SDValue InVec = N->getOperand(0);
14680 SDValue EltNo = N->getOperand(1);
14682 if (!isa<ConstantSDNode>(EltNo))
14685 EVT VT = InVec.getValueType();
14687 bool HasShuffleIntoBitcast = false;
14688 if (InVec.getOpcode() == ISD::BITCAST) {
14689 // Don't duplicate a load with other uses.
14690 if (!InVec.hasOneUse())
14692 EVT BCVT = InVec.getOperand(0).getValueType();
14693 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14695 InVec = InVec.getOperand(0);
14696 HasShuffleIntoBitcast = true;
14699 if (!isTargetShuffle(InVec.getOpcode()))
14702 // Don't duplicate a load with other uses.
14703 if (!InVec.hasOneUse())
14706 SmallVector<int, 16> ShuffleMask;
14708 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14712 // Select the input vector, guarding against out of range extract vector.
14713 unsigned NumElems = VT.getVectorNumElements();
14714 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14715 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14716 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14717 : InVec.getOperand(1);
14719 // If inputs to shuffle are the same for both ops, then allow 2 uses
14720 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14722 if (LdNode.getOpcode() == ISD::BITCAST) {
14723 // Don't duplicate a load with other uses.
14724 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14727 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14728 LdNode = LdNode.getOperand(0);
14731 if (!ISD::isNormalLoad(LdNode.getNode()))
14734 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14736 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14739 if (HasShuffleIntoBitcast) {
14740 // If there's a bitcast before the shuffle, check if the load type and
14741 // alignment is valid.
14742 unsigned Align = LN0->getAlignment();
14743 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14744 unsigned NewAlign = TLI.getDataLayout()->
14745 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14747 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14751 // All checks match so transform back to vector_shuffle so that DAG combiner
14752 // can finish the job
14753 DebugLoc dl = N->getDebugLoc();
14755 // Create shuffle node taking into account the case that its a unary shuffle
14756 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14757 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14758 InVec.getOperand(0), Shuffle,
14760 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14761 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14765 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14766 /// generation and convert it from being a bunch of shuffles and extracts
14767 /// to a simple store and scalar loads to extract the elements.
14768 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14769 TargetLowering::DAGCombinerInfo &DCI) {
14770 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14771 if (NewOp.getNode())
14774 SDValue InputVector = N->getOperand(0);
14775 // Detect whether we are trying to convert from mmx to i32 and the bitcast
14776 // from mmx to v2i32 has a single usage.
14777 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14778 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14779 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14780 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14781 N->getValueType(0),
14782 InputVector.getNode()->getOperand(0));
14784 // Only operate on vectors of 4 elements, where the alternative shuffling
14785 // gets to be more expensive.
14786 if (InputVector.getValueType() != MVT::v4i32)
14789 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14790 // single use which is a sign-extend or zero-extend, and all elements are
14792 SmallVector<SDNode *, 4> Uses;
14793 unsigned ExtractedElements = 0;
14794 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14795 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14796 if (UI.getUse().getResNo() != InputVector.getResNo())
14799 SDNode *Extract = *UI;
14800 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14803 if (Extract->getValueType(0) != MVT::i32)
14805 if (!Extract->hasOneUse())
14807 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14808 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14810 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14813 // Record which element was extracted.
14814 ExtractedElements |=
14815 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14817 Uses.push_back(Extract);
14820 // If not all the elements were used, this may not be worthwhile.
14821 if (ExtractedElements != 15)
14824 // Ok, we've now decided to do the transformation.
14825 DebugLoc dl = InputVector.getDebugLoc();
14827 // Store the value to a temporary stack slot.
14828 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14829 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14830 MachinePointerInfo(), false, false, 0);
14832 // Replace each use (extract) with a load of the appropriate element.
14833 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14834 UE = Uses.end(); UI != UE; ++UI) {
14835 SDNode *Extract = *UI;
14837 // cOMpute the element's address.
14838 SDValue Idx = Extract->getOperand(1);
14840 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14841 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14842 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14843 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14845 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14846 StackPtr, OffsetVal);
14848 // Load the scalar.
14849 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14850 ScalarAddr, MachinePointerInfo(),
14851 false, false, false, 0);
14853 // Replace the exact with the load.
14854 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14857 // The replacement was made in place; don't return anything.
14861 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14862 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14863 SDValue RHS, SelectionDAG &DAG,
14864 const X86Subtarget *Subtarget) {
14865 if (!VT.isVector())
14868 switch (VT.getSimpleVT().SimpleTy) {
14873 if (!Subtarget->hasAVX2())
14878 if (!Subtarget->hasSSE2())
14882 // SSE2 has only a small subset of the operations.
14883 bool hasUnsigned = Subtarget->hasSSE41() ||
14884 (Subtarget->hasSSE2() && VT == MVT::v16i8);
14885 bool hasSigned = Subtarget->hasSSE41() ||
14886 (Subtarget->hasSSE2() && VT == MVT::v8i16);
14888 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14890 // Check for x CC y ? x : y.
14891 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14892 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14897 return hasUnsigned ? X86ISD::UMIN : 0;
14900 return hasUnsigned ? X86ISD::UMAX : 0;
14903 return hasSigned ? X86ISD::SMIN : 0;
14906 return hasSigned ? X86ISD::SMAX : 0;
14908 // Check for x CC y ? y : x -- a min/max with reversed arms.
14909 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14910 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14915 return hasUnsigned ? X86ISD::UMAX : 0;
14918 return hasUnsigned ? X86ISD::UMIN : 0;
14921 return hasSigned ? X86ISD::SMAX : 0;
14924 return hasSigned ? X86ISD::SMIN : 0;
14931 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14933 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14934 TargetLowering::DAGCombinerInfo &DCI,
14935 const X86Subtarget *Subtarget) {
14936 DebugLoc DL = N->getDebugLoc();
14937 SDValue Cond = N->getOperand(0);
14938 // Get the LHS/RHS of the select.
14939 SDValue LHS = N->getOperand(1);
14940 SDValue RHS = N->getOperand(2);
14941 EVT VT = LHS.getValueType();
14943 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14944 // instructions match the semantics of the common C idiom x<y?x:y but not
14945 // x<=y?x:y, because of how they handle negative zero (which can be
14946 // ignored in unsafe-math mode).
14947 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14948 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14949 (Subtarget->hasSSE2() ||
14950 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14951 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14953 unsigned Opcode = 0;
14954 // Check for x CC y ? x : y.
14955 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14956 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14960 // Converting this to a min would handle NaNs incorrectly, and swapping
14961 // the operands would cause it to handle comparisons between positive
14962 // and negative zero incorrectly.
14963 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14964 if (!DAG.getTarget().Options.UnsafeFPMath &&
14965 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14967 std::swap(LHS, RHS);
14969 Opcode = X86ISD::FMIN;
14972 // Converting this to a min would handle comparisons between positive
14973 // and negative zero incorrectly.
14974 if (!DAG.getTarget().Options.UnsafeFPMath &&
14975 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14977 Opcode = X86ISD::FMIN;
14980 // Converting this to a min would handle both negative zeros and NaNs
14981 // incorrectly, but we can swap the operands to fix both.
14982 std::swap(LHS, RHS);
14986 Opcode = X86ISD::FMIN;
14990 // Converting this to a max would handle comparisons between positive
14991 // and negative zero incorrectly.
14992 if (!DAG.getTarget().Options.UnsafeFPMath &&
14993 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14995 Opcode = X86ISD::FMAX;
14998 // Converting this to a max would handle NaNs incorrectly, and swapping
14999 // the operands would cause it to handle comparisons between positive
15000 // and negative zero incorrectly.
15001 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15002 if (!DAG.getTarget().Options.UnsafeFPMath &&
15003 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15005 std::swap(LHS, RHS);
15007 Opcode = X86ISD::FMAX;
15010 // Converting this to a max would handle both negative zeros and NaNs
15011 // incorrectly, but we can swap the operands to fix both.
15012 std::swap(LHS, RHS);
15016 Opcode = X86ISD::FMAX;
15019 // Check for x CC y ? y : x -- a min/max with reversed arms.
15020 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15021 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15025 // Converting this to a min would handle comparisons between positive
15026 // and negative zero incorrectly, and swapping the operands would
15027 // cause it to handle NaNs incorrectly.
15028 if (!DAG.getTarget().Options.UnsafeFPMath &&
15029 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15030 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15032 std::swap(LHS, RHS);
15034 Opcode = X86ISD::FMIN;
15037 // Converting this to a min would handle NaNs incorrectly.
15038 if (!DAG.getTarget().Options.UnsafeFPMath &&
15039 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15041 Opcode = X86ISD::FMIN;
15044 // Converting this to a min would handle both negative zeros and NaNs
15045 // incorrectly, but we can swap the operands to fix both.
15046 std::swap(LHS, RHS);
15050 Opcode = X86ISD::FMIN;
15054 // Converting this to a max would handle NaNs incorrectly.
15055 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15057 Opcode = X86ISD::FMAX;
15060 // Converting this to a max would handle comparisons between positive
15061 // and negative zero incorrectly, and swapping the operands would
15062 // cause it to handle NaNs incorrectly.
15063 if (!DAG.getTarget().Options.UnsafeFPMath &&
15064 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15065 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15067 std::swap(LHS, RHS);
15069 Opcode = X86ISD::FMAX;
15072 // Converting this to a max would handle both negative zeros and NaNs
15073 // incorrectly, but we can swap the operands to fix both.
15074 std::swap(LHS, RHS);
15078 Opcode = X86ISD::FMAX;
15084 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15087 // If this is a select between two integer constants, try to do some
15089 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15090 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15091 // Don't do this for crazy integer types.
15092 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15093 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15094 // so that TrueC (the true value) is larger than FalseC.
15095 bool NeedsCondInvert = false;
15097 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15098 // Efficiently invertible.
15099 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15100 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15101 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15102 NeedsCondInvert = true;
15103 std::swap(TrueC, FalseC);
15106 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15107 if (FalseC->getAPIntValue() == 0 &&
15108 TrueC->getAPIntValue().isPowerOf2()) {
15109 if (NeedsCondInvert) // Invert the condition if needed.
15110 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15111 DAG.getConstant(1, Cond.getValueType()));
15113 // Zero extend the condition if needed.
15114 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15116 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15117 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15118 DAG.getConstant(ShAmt, MVT::i8));
15121 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15122 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15123 if (NeedsCondInvert) // Invert the condition if needed.
15124 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15125 DAG.getConstant(1, Cond.getValueType()));
15127 // Zero extend the condition if needed.
15128 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15129 FalseC->getValueType(0), Cond);
15130 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15131 SDValue(FalseC, 0));
15134 // Optimize cases that will turn into an LEA instruction. This requires
15135 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15136 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15137 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15138 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15140 bool isFastMultiplier = false;
15142 switch ((unsigned char)Diff) {
15144 case 1: // result = add base, cond
15145 case 2: // result = lea base( , cond*2)
15146 case 3: // result = lea base(cond, cond*2)
15147 case 4: // result = lea base( , cond*4)
15148 case 5: // result = lea base(cond, cond*4)
15149 case 8: // result = lea base( , cond*8)
15150 case 9: // result = lea base(cond, cond*8)
15151 isFastMultiplier = true;
15156 if (isFastMultiplier) {
15157 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15158 if (NeedsCondInvert) // Invert the condition if needed.
15159 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15160 DAG.getConstant(1, Cond.getValueType()));
15162 // Zero extend the condition if needed.
15163 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15165 // Scale the condition by the difference.
15167 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15168 DAG.getConstant(Diff, Cond.getValueType()));
15170 // Add the base if non-zero.
15171 if (FalseC->getAPIntValue() != 0)
15172 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15173 SDValue(FalseC, 0));
15180 // Canonicalize max and min:
15181 // (x > y) ? x : y -> (x >= y) ? x : y
15182 // (x < y) ? x : y -> (x <= y) ? x : y
15183 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15184 // the need for an extra compare
15185 // against zero. e.g.
15186 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15188 // testl %edi, %edi
15190 // cmovgl %edi, %eax
15194 // cmovsl %eax, %edi
15195 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15196 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15197 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15198 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15203 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15204 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15205 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15206 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15211 // Match VSELECTs into subs with unsigned saturation.
15212 if (!DCI.isBeforeLegalize() &&
15213 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15214 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15215 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15216 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15217 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15219 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15220 // left side invert the predicate to simplify logic below.
15222 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15224 CC = ISD::getSetCCInverse(CC, true);
15225 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15229 if (Other.getNode() && Other->getNumOperands() == 2 &&
15230 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15231 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15232 SDValue CondRHS = Cond->getOperand(1);
15234 // Look for a general sub with unsigned saturation first.
15235 // x >= y ? x-y : 0 --> subus x, y
15236 // x > y ? x-y : 0 --> subus x, y
15237 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15238 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15239 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15241 // If the RHS is a constant we have to reverse the const canonicalization.
15242 // x > C-1 ? x+-C : 0 --> subus x, C
15243 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15244 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15245 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15246 if (CondRHS.getConstantOperandVal(0) == -A-1) {
15247 SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15248 DAG.getConstant(-A, VT.getScalarType()));
15249 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15250 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15251 V.data(), V.size()));
15255 // Another special case: If C was a sign bit, the sub has been
15256 // canonicalized into a xor.
15257 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15258 // it's safe to decanonicalize the xor?
15259 // x s< 0 ? x^C : 0 --> subus x, C
15260 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15261 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15262 isSplatVector(OpRHS.getNode())) {
15263 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15265 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15270 // Try to match a min/max vector operation.
15271 if (!DCI.isBeforeLegalize() &&
15272 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15273 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15274 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15276 // If we know that this node is legal then we know that it is going to be
15277 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15278 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15279 // to simplify previous instructions.
15280 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15281 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15282 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15283 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15285 // Don't optimize vector selects that map to mask-registers.
15289 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15290 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15292 APInt KnownZero, KnownOne;
15293 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15294 DCI.isBeforeLegalizeOps());
15295 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15296 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15297 DCI.CommitTargetLoweringOpt(TLO);
15303 // Check whether a boolean test is testing a boolean value generated by
15304 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15307 // Simplify the following patterns:
15308 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15309 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15310 // to (Op EFLAGS Cond)
15312 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15313 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15314 // to (Op EFLAGS !Cond)
15316 // where Op could be BRCOND or CMOV.
15318 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15319 // Quit if not CMP and SUB with its value result used.
15320 if (Cmp.getOpcode() != X86ISD::CMP &&
15321 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15324 // Quit if not used as a boolean value.
15325 if (CC != X86::COND_E && CC != X86::COND_NE)
15328 // Check CMP operands. One of them should be 0 or 1 and the other should be
15329 // an SetCC or extended from it.
15330 SDValue Op1 = Cmp.getOperand(0);
15331 SDValue Op2 = Cmp.getOperand(1);
15334 const ConstantSDNode* C = 0;
15335 bool needOppositeCond = (CC == X86::COND_E);
15337 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15339 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15341 else // Quit if all operands are not constants.
15344 if (C->getZExtValue() == 1)
15345 needOppositeCond = !needOppositeCond;
15346 else if (C->getZExtValue() != 0)
15347 // Quit if the constant is neither 0 or 1.
15350 // Skip 'zext' node.
15351 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15352 SetCC = SetCC.getOperand(0);
15354 switch (SetCC.getOpcode()) {
15355 case X86ISD::SETCC:
15356 // Set the condition code or opposite one if necessary.
15357 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15358 if (needOppositeCond)
15359 CC = X86::GetOppositeBranchCondition(CC);
15360 return SetCC.getOperand(1);
15361 case X86ISD::CMOV: {
15362 // Check whether false/true value has canonical one, i.e. 0 or 1.
15363 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15364 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15365 // Quit if true value is not a constant.
15368 // Quit if false value is not a constant.
15370 // A special case for rdrand, where 0 is set if false cond is found.
15371 SDValue Op = SetCC.getOperand(0);
15372 if (Op.getOpcode() != X86ISD::RDRAND)
15375 // Quit if false value is not the constant 0 or 1.
15376 bool FValIsFalse = true;
15377 if (FVal && FVal->getZExtValue() != 0) {
15378 if (FVal->getZExtValue() != 1)
15380 // If FVal is 1, opposite cond is needed.
15381 needOppositeCond = !needOppositeCond;
15382 FValIsFalse = false;
15384 // Quit if TVal is not the constant opposite of FVal.
15385 if (FValIsFalse && TVal->getZExtValue() != 1)
15387 if (!FValIsFalse && TVal->getZExtValue() != 0)
15389 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15390 if (needOppositeCond)
15391 CC = X86::GetOppositeBranchCondition(CC);
15392 return SetCC.getOperand(3);
15399 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15400 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15401 TargetLowering::DAGCombinerInfo &DCI,
15402 const X86Subtarget *Subtarget) {
15403 DebugLoc DL = N->getDebugLoc();
15405 // If the flag operand isn't dead, don't touch this CMOV.
15406 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15409 SDValue FalseOp = N->getOperand(0);
15410 SDValue TrueOp = N->getOperand(1);
15411 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15412 SDValue Cond = N->getOperand(3);
15414 if (CC == X86::COND_E || CC == X86::COND_NE) {
15415 switch (Cond.getOpcode()) {
15419 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15420 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15421 return (CC == X86::COND_E) ? FalseOp : TrueOp;
15427 Flags = checkBoolTestSetCCCombine(Cond, CC);
15428 if (Flags.getNode() &&
15429 // Extra check as FCMOV only supports a subset of X86 cond.
15430 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15431 SDValue Ops[] = { FalseOp, TrueOp,
15432 DAG.getConstant(CC, MVT::i8), Flags };
15433 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15434 Ops, array_lengthof(Ops));
15437 // If this is a select between two integer constants, try to do some
15438 // optimizations. Note that the operands are ordered the opposite of SELECT
15440 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15441 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15442 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15443 // larger than FalseC (the false value).
15444 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15445 CC = X86::GetOppositeBranchCondition(CC);
15446 std::swap(TrueC, FalseC);
15447 std::swap(TrueOp, FalseOp);
15450 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
15451 // This is efficient for any integer data type (including i8/i16) and
15453 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15454 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15455 DAG.getConstant(CC, MVT::i8), Cond);
15457 // Zero extend the condition if needed.
15458 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15460 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15461 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15462 DAG.getConstant(ShAmt, MVT::i8));
15463 if (N->getNumValues() == 2) // Dead flag value?
15464 return DCI.CombineTo(N, Cond, SDValue());
15468 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
15469 // for any integer data type, including i8/i16.
15470 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15471 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15472 DAG.getConstant(CC, MVT::i8), Cond);
15474 // Zero extend the condition if needed.
15475 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15476 FalseC->getValueType(0), Cond);
15477 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15478 SDValue(FalseC, 0));
15480 if (N->getNumValues() == 2) // Dead flag value?
15481 return DCI.CombineTo(N, Cond, SDValue());
15485 // Optimize cases that will turn into an LEA instruction. This requires
15486 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15487 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15488 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15489 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15491 bool isFastMultiplier = false;
15493 switch ((unsigned char)Diff) {
15495 case 1: // result = add base, cond
15496 case 2: // result = lea base( , cond*2)
15497 case 3: // result = lea base(cond, cond*2)
15498 case 4: // result = lea base( , cond*4)
15499 case 5: // result = lea base(cond, cond*4)
15500 case 8: // result = lea base( , cond*8)
15501 case 9: // result = lea base(cond, cond*8)
15502 isFastMultiplier = true;
15507 if (isFastMultiplier) {
15508 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15509 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15510 DAG.getConstant(CC, MVT::i8), Cond);
15511 // Zero extend the condition if needed.
15512 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15514 // Scale the condition by the difference.
15516 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15517 DAG.getConstant(Diff, Cond.getValueType()));
15519 // Add the base if non-zero.
15520 if (FalseC->getAPIntValue() != 0)
15521 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15522 SDValue(FalseC, 0));
15523 if (N->getNumValues() == 2) // Dead flag value?
15524 return DCI.CombineTo(N, Cond, SDValue());
15531 // Handle these cases:
15532 // (select (x != c), e, c) -> select (x != c), e, x),
15533 // (select (x == c), c, e) -> select (x == c), x, e)
15534 // where the c is an integer constant, and the "select" is the combination
15535 // of CMOV and CMP.
15537 // The rationale for this change is that the conditional-move from a constant
15538 // needs two instructions, however, conditional-move from a register needs
15539 // only one instruction.
15541 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15542 // some instruction-combining opportunities. This opt needs to be
15543 // postponed as late as possible.
15545 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15546 // the DCI.xxxx conditions are provided to postpone the optimization as
15547 // late as possible.
15549 ConstantSDNode *CmpAgainst = 0;
15550 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15551 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15552 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15554 if (CC == X86::COND_NE &&
15555 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15556 CC = X86::GetOppositeBranchCondition(CC);
15557 std::swap(TrueOp, FalseOp);
15560 if (CC == X86::COND_E &&
15561 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15562 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15563 DAG.getConstant(CC, MVT::i8), Cond };
15564 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15565 array_lengthof(Ops));
15573 /// PerformMulCombine - Optimize a single multiply with constant into two
15574 /// in order to implement it with two cheaper instructions, e.g.
15575 /// LEA + SHL, LEA + LEA.
15576 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15577 TargetLowering::DAGCombinerInfo &DCI) {
15578 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15581 EVT VT = N->getValueType(0);
15582 if (VT != MVT::i64)
15585 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15588 uint64_t MulAmt = C->getZExtValue();
15589 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15592 uint64_t MulAmt1 = 0;
15593 uint64_t MulAmt2 = 0;
15594 if ((MulAmt % 9) == 0) {
15596 MulAmt2 = MulAmt / 9;
15597 } else if ((MulAmt % 5) == 0) {
15599 MulAmt2 = MulAmt / 5;
15600 } else if ((MulAmt % 3) == 0) {
15602 MulAmt2 = MulAmt / 3;
15605 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15606 DebugLoc DL = N->getDebugLoc();
15608 if (isPowerOf2_64(MulAmt2) &&
15609 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15610 // If second multiplifer is pow2, issue it first. We want the multiply by
15611 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15613 std::swap(MulAmt1, MulAmt2);
15616 if (isPowerOf2_64(MulAmt1))
15617 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15618 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15620 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15621 DAG.getConstant(MulAmt1, VT));
15623 if (isPowerOf2_64(MulAmt2))
15624 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15625 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15627 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15628 DAG.getConstant(MulAmt2, VT));
15630 // Do not add new nodes to DAG combiner worklist.
15631 DCI.CombineTo(N, NewMul, false);
15636 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15637 SDValue N0 = N->getOperand(0);
15638 SDValue N1 = N->getOperand(1);
15639 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15640 EVT VT = N0.getValueType();
15642 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15643 // since the result of setcc_c is all zero's or all ones.
15644 if (VT.isInteger() && !VT.isVector() &&
15645 N1C && N0.getOpcode() == ISD::AND &&
15646 N0.getOperand(1).getOpcode() == ISD::Constant) {
15647 SDValue N00 = N0.getOperand(0);
15648 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15649 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15650 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15651 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15652 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15653 APInt ShAmt = N1C->getAPIntValue();
15654 Mask = Mask.shl(ShAmt);
15656 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15657 N00, DAG.getConstant(Mask, VT));
15661 // Hardware support for vector shifts is sparse which makes us scalarize the
15662 // vector operations in many cases. Also, on sandybridge ADD is faster than
15664 // (shl V, 1) -> add V,V
15665 if (isSplatVector(N1.getNode())) {
15666 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15667 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15668 // We shift all of the values by one. In many cases we do not have
15669 // hardware support for this operation. This is better expressed as an ADD
15671 if (N1C && (1 == N1C->getZExtValue())) {
15672 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15679 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15681 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15682 TargetLowering::DAGCombinerInfo &DCI,
15683 const X86Subtarget *Subtarget) {
15684 EVT VT = N->getValueType(0);
15685 if (N->getOpcode() == ISD::SHL) {
15686 SDValue V = PerformSHLCombine(N, DAG);
15687 if (V.getNode()) return V;
15690 // On X86 with SSE2 support, we can transform this to a vector shift if
15691 // all elements are shifted by the same amount. We can't do this in legalize
15692 // because the a constant vector is typically transformed to a constant pool
15693 // so we have no knowledge of the shift amount.
15694 if (!Subtarget->hasSSE2())
15697 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15698 (!Subtarget->hasInt256() ||
15699 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15702 SDValue ShAmtOp = N->getOperand(1);
15703 EVT EltVT = VT.getVectorElementType();
15704 DebugLoc DL = N->getDebugLoc();
15705 SDValue BaseShAmt = SDValue();
15706 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15707 unsigned NumElts = VT.getVectorNumElements();
15709 for (; i != NumElts; ++i) {
15710 SDValue Arg = ShAmtOp.getOperand(i);
15711 if (Arg.getOpcode() == ISD::UNDEF) continue;
15715 // Handle the case where the build_vector is all undef
15716 // FIXME: Should DAG allow this?
15720 for (; i != NumElts; ++i) {
15721 SDValue Arg = ShAmtOp.getOperand(i);
15722 if (Arg.getOpcode() == ISD::UNDEF) continue;
15723 if (Arg != BaseShAmt) {
15727 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15728 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15729 SDValue InVec = ShAmtOp.getOperand(0);
15730 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15731 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15733 for (; i != NumElts; ++i) {
15734 SDValue Arg = InVec.getOperand(i);
15735 if (Arg.getOpcode() == ISD::UNDEF) continue;
15739 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15740 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15741 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15742 if (C->getZExtValue() == SplatIdx)
15743 BaseShAmt = InVec.getOperand(1);
15746 if (BaseShAmt.getNode() == 0) {
15747 // Don't create instructions with illegal types after legalize
15749 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15750 !DCI.isBeforeLegalize())
15753 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15754 DAG.getIntPtrConstant(0));
15759 // The shift amount is an i32.
15760 if (EltVT.bitsGT(MVT::i32))
15761 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15762 else if (EltVT.bitsLT(MVT::i32))
15763 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15765 // The shift amount is identical so we can do a vector shift.
15766 SDValue ValOp = N->getOperand(0);
15767 switch (N->getOpcode()) {
15769 llvm_unreachable("Unknown shift opcode!");
15771 switch (VT.getSimpleVT().SimpleTy) {
15772 default: return SDValue();
15779 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15782 switch (VT.getSimpleVT().SimpleTy) {
15783 default: return SDValue();
15788 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15791 switch (VT.getSimpleVT().SimpleTy) {
15792 default: return SDValue();
15799 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15804 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15805 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15806 // and friends. Likewise for OR -> CMPNEQSS.
15807 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15808 TargetLowering::DAGCombinerInfo &DCI,
15809 const X86Subtarget *Subtarget) {
15812 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15813 // we're requiring SSE2 for both.
15814 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15815 SDValue N0 = N->getOperand(0);
15816 SDValue N1 = N->getOperand(1);
15817 SDValue CMP0 = N0->getOperand(1);
15818 SDValue CMP1 = N1->getOperand(1);
15819 DebugLoc DL = N->getDebugLoc();
15821 // The SETCCs should both refer to the same CMP.
15822 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15825 SDValue CMP00 = CMP0->getOperand(0);
15826 SDValue CMP01 = CMP0->getOperand(1);
15827 EVT VT = CMP00.getValueType();
15829 if (VT == MVT::f32 || VT == MVT::f64) {
15830 bool ExpectingFlags = false;
15831 // Check for any users that want flags:
15832 for (SDNode::use_iterator UI = N->use_begin(),
15834 !ExpectingFlags && UI != UE; ++UI)
15835 switch (UI->getOpcode()) {
15840 ExpectingFlags = true;
15842 case ISD::CopyToReg:
15843 case ISD::SIGN_EXTEND:
15844 case ISD::ZERO_EXTEND:
15845 case ISD::ANY_EXTEND:
15849 if (!ExpectingFlags) {
15850 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15851 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15853 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15854 X86::CondCode tmp = cc0;
15859 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15860 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15861 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15862 X86ISD::NodeType NTOperator = is64BitFP ?
15863 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15864 // FIXME: need symbolic constants for these magic numbers.
15865 // See X86ATTInstPrinter.cpp:printSSECC().
15866 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15867 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15868 DAG.getConstant(x86cc, MVT::i8));
15869 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15871 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15872 DAG.getConstant(1, MVT::i32));
15873 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15874 return OneBitOfTruth;
15882 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15883 /// so it can be folded inside ANDNP.
15884 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15885 EVT VT = N->getValueType(0);
15887 // Match direct AllOnes for 128 and 256-bit vectors
15888 if (ISD::isBuildVectorAllOnes(N))
15891 // Look through a bit convert.
15892 if (N->getOpcode() == ISD::BITCAST)
15893 N = N->getOperand(0).getNode();
15895 // Sometimes the operand may come from a insert_subvector building a 256-bit
15897 if (VT.is256BitVector() &&
15898 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15899 SDValue V1 = N->getOperand(0);
15900 SDValue V2 = N->getOperand(1);
15902 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15903 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15904 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15905 ISD::isBuildVectorAllOnes(V2.getNode()))
15912 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
15913 // register. In most cases we actually compare or select YMM-sized registers
15914 // and mixing the two types creates horrible code. This method optimizes
15915 // some of the transition sequences.
15916 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
15917 TargetLowering::DAGCombinerInfo &DCI,
15918 const X86Subtarget *Subtarget) {
15919 EVT VT = N->getValueType(0);
15920 if (VT.getSizeInBits() != 256)
15923 assert((N->getOpcode() == ISD::ANY_EXTEND ||
15924 N->getOpcode() == ISD::ZERO_EXTEND ||
15925 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
15927 SDValue Narrow = N->getOperand(0);
15928 EVT NarrowVT = Narrow->getValueType(0);
15929 if (NarrowVT.getSizeInBits() != 128)
15932 if (Narrow->getOpcode() != ISD::XOR &&
15933 Narrow->getOpcode() != ISD::AND &&
15934 Narrow->getOpcode() != ISD::OR)
15937 SDValue N0 = Narrow->getOperand(0);
15938 SDValue N1 = Narrow->getOperand(1);
15939 DebugLoc DL = Narrow->getDebugLoc();
15941 // The Left side has to be a trunc.
15942 if (N0.getOpcode() != ISD::TRUNCATE)
15945 // The type of the truncated inputs.
15946 EVT WideVT = N0->getOperand(0)->getValueType(0);
15950 // The right side has to be a 'trunc' or a constant vector.
15951 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
15952 bool RHSConst = (isSplatVector(N1.getNode()) &&
15953 isa<ConstantSDNode>(N1->getOperand(0)));
15954 if (!RHSTrunc && !RHSConst)
15957 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15959 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
15962 // Set N0 and N1 to hold the inputs to the new wide operation.
15963 N0 = N0->getOperand(0);
15965 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
15966 N1->getOperand(0));
15967 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
15968 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
15969 } else if (RHSTrunc) {
15970 N1 = N1->getOperand(0);
15973 // Generate the wide operation.
15974 SDValue Op = DAG.getNode(N->getOpcode(), DL, WideVT, N0, N1);
15975 unsigned Opcode = N->getOpcode();
15977 case ISD::ANY_EXTEND:
15979 case ISD::ZERO_EXTEND: {
15980 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
15981 APInt Mask = APInt::getAllOnesValue(InBits);
15982 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
15983 return DAG.getNode(ISD::AND, DL, VT,
15984 Op, DAG.getConstant(Mask, VT));
15986 case ISD::SIGN_EXTEND:
15987 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
15988 Op, DAG.getValueType(NarrowVT));
15990 llvm_unreachable("Unexpected opcode");
15994 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15995 TargetLowering::DAGCombinerInfo &DCI,
15996 const X86Subtarget *Subtarget) {
15997 EVT VT = N->getValueType(0);
15998 if (DCI.isBeforeLegalizeOps())
16001 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16005 // Create BLSI, and BLSR instructions
16006 // BLSI is X & (-X)
16007 // BLSR is X & (X-1)
16008 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16009 SDValue N0 = N->getOperand(0);
16010 SDValue N1 = N->getOperand(1);
16011 DebugLoc DL = N->getDebugLoc();
16013 // Check LHS for neg
16014 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16015 isZero(N0.getOperand(0)))
16016 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16018 // Check RHS for neg
16019 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16020 isZero(N1.getOperand(0)))
16021 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16023 // Check LHS for X-1
16024 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16025 isAllOnes(N0.getOperand(1)))
16026 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16028 // Check RHS for X-1
16029 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16030 isAllOnes(N1.getOperand(1)))
16031 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16036 // Want to form ANDNP nodes:
16037 // 1) In the hopes of then easily combining them with OR and AND nodes
16038 // to form PBLEND/PSIGN.
16039 // 2) To match ANDN packed intrinsics
16040 if (VT != MVT::v2i64 && VT != MVT::v4i64)
16043 SDValue N0 = N->getOperand(0);
16044 SDValue N1 = N->getOperand(1);
16045 DebugLoc DL = N->getDebugLoc();
16047 // Check LHS for vnot
16048 if (N0.getOpcode() == ISD::XOR &&
16049 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16050 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16051 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16053 // Check RHS for vnot
16054 if (N1.getOpcode() == ISD::XOR &&
16055 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16056 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16057 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16062 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16063 TargetLowering::DAGCombinerInfo &DCI,
16064 const X86Subtarget *Subtarget) {
16065 EVT VT = N->getValueType(0);
16066 if (DCI.isBeforeLegalizeOps())
16069 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16073 SDValue N0 = N->getOperand(0);
16074 SDValue N1 = N->getOperand(1);
16076 // look for psign/blend
16077 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16078 if (!Subtarget->hasSSSE3() ||
16079 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16082 // Canonicalize pandn to RHS
16083 if (N0.getOpcode() == X86ISD::ANDNP)
16085 // or (and (m, y), (pandn m, x))
16086 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16087 SDValue Mask = N1.getOperand(0);
16088 SDValue X = N1.getOperand(1);
16090 if (N0.getOperand(0) == Mask)
16091 Y = N0.getOperand(1);
16092 if (N0.getOperand(1) == Mask)
16093 Y = N0.getOperand(0);
16095 // Check to see if the mask appeared in both the AND and ANDNP and
16099 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16100 // Look through mask bitcast.
16101 if (Mask.getOpcode() == ISD::BITCAST)
16102 Mask = Mask.getOperand(0);
16103 if (X.getOpcode() == ISD::BITCAST)
16104 X = X.getOperand(0);
16105 if (Y.getOpcode() == ISD::BITCAST)
16106 Y = Y.getOperand(0);
16108 EVT MaskVT = Mask.getValueType();
16110 // Validate that the Mask operand is a vector sra node.
16111 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16112 // there is no psrai.b
16113 if (Mask.getOpcode() != X86ISD::VSRAI)
16116 // Check that the SRA is all signbits.
16117 SDValue SraC = Mask.getOperand(1);
16118 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16119 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16120 if ((SraAmt + 1) != EltBits)
16123 DebugLoc DL = N->getDebugLoc();
16125 // We are going to replace the AND, OR, NAND with either BLEND
16126 // or PSIGN, which only look at the MSB. The VSRAI instruction
16127 // does not affect the highest bit, so we can get rid of it.
16128 Mask = Mask.getOperand(0);
16130 // Now we know we at least have a plendvb with the mask val. See if
16131 // we can form a psignb/w/d.
16132 // psign = x.type == y.type == mask.type && y = sub(0, x);
16133 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16134 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16135 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16136 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16137 "Unsupported VT for PSIGN");
16138 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
16139 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16141 // PBLENDVB only available on SSE 4.1
16142 if (!Subtarget->hasSSE41())
16145 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16147 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16148 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16149 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16150 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16151 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16155 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16158 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16159 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16161 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16163 if (!N0.hasOneUse() || !N1.hasOneUse())
16166 SDValue ShAmt0 = N0.getOperand(1);
16167 if (ShAmt0.getValueType() != MVT::i8)
16169 SDValue ShAmt1 = N1.getOperand(1);
16170 if (ShAmt1.getValueType() != MVT::i8)
16172 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16173 ShAmt0 = ShAmt0.getOperand(0);
16174 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16175 ShAmt1 = ShAmt1.getOperand(0);
16177 DebugLoc DL = N->getDebugLoc();
16178 unsigned Opc = X86ISD::SHLD;
16179 SDValue Op0 = N0.getOperand(0);
16180 SDValue Op1 = N1.getOperand(0);
16181 if (ShAmt0.getOpcode() == ISD::SUB) {
16182 Opc = X86ISD::SHRD;
16183 std::swap(Op0, Op1);
16184 std::swap(ShAmt0, ShAmt1);
16187 unsigned Bits = VT.getSizeInBits();
16188 if (ShAmt1.getOpcode() == ISD::SUB) {
16189 SDValue Sum = ShAmt1.getOperand(0);
16190 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16191 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16192 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16193 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16194 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16195 return DAG.getNode(Opc, DL, VT,
16197 DAG.getNode(ISD::TRUNCATE, DL,
16200 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16201 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16203 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16204 return DAG.getNode(Opc, DL, VT,
16205 N0.getOperand(0), N1.getOperand(0),
16206 DAG.getNode(ISD::TRUNCATE, DL,
16213 // Generate NEG and CMOV for integer abs.
16214 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16215 EVT VT = N->getValueType(0);
16217 // Since X86 does not have CMOV for 8-bit integer, we don't convert
16218 // 8-bit integer abs to NEG and CMOV.
16219 if (VT.isInteger() && VT.getSizeInBits() == 8)
16222 SDValue N0 = N->getOperand(0);
16223 SDValue N1 = N->getOperand(1);
16224 DebugLoc DL = N->getDebugLoc();
16226 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16227 // and change it to SUB and CMOV.
16228 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16229 N0.getOpcode() == ISD::ADD &&
16230 N0.getOperand(1) == N1 &&
16231 N1.getOpcode() == ISD::SRA &&
16232 N1.getOperand(0) == N0.getOperand(0))
16233 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16234 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16235 // Generate SUB & CMOV.
16236 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16237 DAG.getConstant(0, VT), N0.getOperand(0));
16239 SDValue Ops[] = { N0.getOperand(0), Neg,
16240 DAG.getConstant(X86::COND_GE, MVT::i8),
16241 SDValue(Neg.getNode(), 1) };
16242 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16243 Ops, array_lengthof(Ops));
16248 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16249 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16250 TargetLowering::DAGCombinerInfo &DCI,
16251 const X86Subtarget *Subtarget) {
16252 EVT VT = N->getValueType(0);
16253 if (DCI.isBeforeLegalizeOps())
16256 if (Subtarget->hasCMov()) {
16257 SDValue RV = performIntegerAbsCombine(N, DAG);
16262 // Try forming BMI if it is available.
16263 if (!Subtarget->hasBMI())
16266 if (VT != MVT::i32 && VT != MVT::i64)
16269 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16271 // Create BLSMSK instructions by finding X ^ (X-1)
16272 SDValue N0 = N->getOperand(0);
16273 SDValue N1 = N->getOperand(1);
16274 DebugLoc DL = N->getDebugLoc();
16276 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16277 isAllOnes(N0.getOperand(1)))
16278 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16280 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16281 isAllOnes(N1.getOperand(1)))
16282 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16287 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16288 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16289 TargetLowering::DAGCombinerInfo &DCI,
16290 const X86Subtarget *Subtarget) {
16291 LoadSDNode *Ld = cast<LoadSDNode>(N);
16292 EVT RegVT = Ld->getValueType(0);
16293 EVT MemVT = Ld->getMemoryVT();
16294 DebugLoc dl = Ld->getDebugLoc();
16295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16297 ISD::LoadExtType Ext = Ld->getExtensionType();
16299 // If this is a vector EXT Load then attempt to optimize it using a
16300 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16301 // expansion is still better than scalar code.
16302 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16303 // emit a shuffle and a arithmetic shift.
16304 // TODO: It is possible to support ZExt by zeroing the undef values
16305 // during the shuffle phase or after the shuffle.
16306 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16307 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16308 assert(MemVT != RegVT && "Cannot extend to the same type");
16309 assert(MemVT.isVector() && "Must load a vector from memory");
16311 unsigned NumElems = RegVT.getVectorNumElements();
16312 unsigned RegSz = RegVT.getSizeInBits();
16313 unsigned MemSz = MemVT.getSizeInBits();
16314 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16316 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16319 // All sizes must be a power of two.
16320 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16323 // Attempt to load the original value using scalar loads.
16324 // Find the largest scalar type that divides the total loaded size.
16325 MVT SclrLoadTy = MVT::i8;
16326 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16327 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16328 MVT Tp = (MVT::SimpleValueType)tp;
16329 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16334 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16335 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16337 SclrLoadTy = MVT::f64;
16339 // Calculate the number of scalar loads that we need to perform
16340 // in order to load our vector from memory.
16341 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16342 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16345 unsigned loadRegZize = RegSz;
16346 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16349 // Represent our vector as a sequence of elements which are the
16350 // largest scalar that we can load.
16351 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16352 loadRegZize/SclrLoadTy.getSizeInBits());
16354 // Represent the data using the same element type that is stored in
16355 // memory. In practice, we ''widen'' MemVT.
16357 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16358 loadRegZize/MemVT.getScalarType().getSizeInBits());
16360 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16361 "Invalid vector type");
16363 // We can't shuffle using an illegal type.
16364 if (!TLI.isTypeLegal(WideVecVT))
16367 SmallVector<SDValue, 8> Chains;
16368 SDValue Ptr = Ld->getBasePtr();
16369 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16370 TLI.getPointerTy());
16371 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16373 for (unsigned i = 0; i < NumLoads; ++i) {
16374 // Perform a single load.
16375 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16376 Ptr, Ld->getPointerInfo(),
16377 Ld->isVolatile(), Ld->isNonTemporal(),
16378 Ld->isInvariant(), Ld->getAlignment());
16379 Chains.push_back(ScalarLoad.getValue(1));
16380 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16381 // another round of DAGCombining.
16383 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16385 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16386 ScalarLoad, DAG.getIntPtrConstant(i));
16388 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16391 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16394 // Bitcast the loaded value to a vector of the original element type, in
16395 // the size of the target vector type.
16396 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16397 unsigned SizeRatio = RegSz/MemSz;
16399 if (Ext == ISD::SEXTLOAD) {
16400 // If we have SSE4.1 we can directly emit a VSEXT node.
16401 if (Subtarget->hasSSE41()) {
16402 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16403 return DCI.CombineTo(N, Sext, TF, true);
16406 // Otherwise we'll shuffle the small elements in the high bits of the
16407 // larger type and perform an arithmetic shift. If the shift is not legal
16408 // it's better to scalarize.
16409 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16412 // Redistribute the loaded elements into the different locations.
16413 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16414 for (unsigned i = 0; i != NumElems; ++i)
16415 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16417 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16418 DAG.getUNDEF(WideVecVT),
16421 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16423 // Build the arithmetic shift.
16424 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16425 MemVT.getVectorElementType().getSizeInBits();
16426 SmallVector<SDValue, 8> C(NumElems,
16427 DAG.getConstant(Amt, RegVT.getScalarType()));
16428 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16429 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16431 return DCI.CombineTo(N, Shuff, TF, true);
16434 // Redistribute the loaded elements into the different locations.
16435 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16436 for (unsigned i = 0; i != NumElems; ++i)
16437 ShuffleVec[i*SizeRatio] = i;
16439 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16440 DAG.getUNDEF(WideVecVT),
16443 // Bitcast to the requested type.
16444 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16445 // Replace the original load with the new sequence
16446 // and return the new chain.
16447 return DCI.CombineTo(N, Shuff, TF, true);
16453 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16454 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16455 const X86Subtarget *Subtarget) {
16456 StoreSDNode *St = cast<StoreSDNode>(N);
16457 EVT VT = St->getValue().getValueType();
16458 EVT StVT = St->getMemoryVT();
16459 DebugLoc dl = St->getDebugLoc();
16460 SDValue StoredVal = St->getOperand(1);
16461 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16463 // If we are saving a concatenation of two XMM registers, perform two stores.
16464 // On Sandy Bridge, 256-bit memory operations are executed by two
16465 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16466 // memory operation.
16467 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16468 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
16469 StoredVal.getNumOperands() == 2) {
16470 SDValue Value0 = StoredVal.getOperand(0);
16471 SDValue Value1 = StoredVal.getOperand(1);
16473 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16474 SDValue Ptr0 = St->getBasePtr();
16475 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16477 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16478 St->getPointerInfo(), St->isVolatile(),
16479 St->isNonTemporal(), St->getAlignment());
16480 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16481 St->getPointerInfo(), St->isVolatile(),
16482 St->isNonTemporal(), St->getAlignment());
16483 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16486 // Optimize trunc store (of multiple scalars) to shuffle and store.
16487 // First, pack all of the elements in one place. Next, store to memory
16488 // in fewer chunks.
16489 if (St->isTruncatingStore() && VT.isVector()) {
16490 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16491 unsigned NumElems = VT.getVectorNumElements();
16492 assert(StVT != VT && "Cannot truncate to the same type");
16493 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16494 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16496 // From, To sizes and ElemCount must be pow of two
16497 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16498 // We are going to use the original vector elt for storing.
16499 // Accumulated smaller vector elements must be a multiple of the store size.
16500 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16502 unsigned SizeRatio = FromSz / ToSz;
16504 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16506 // Create a type on which we perform the shuffle
16507 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16508 StVT.getScalarType(), NumElems*SizeRatio);
16510 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16512 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16513 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16514 for (unsigned i = 0; i != NumElems; ++i)
16515 ShuffleVec[i] = i * SizeRatio;
16517 // Can't shuffle using an illegal type.
16518 if (!TLI.isTypeLegal(WideVecVT))
16521 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16522 DAG.getUNDEF(WideVecVT),
16524 // At this point all of the data is stored at the bottom of the
16525 // register. We now need to save it to mem.
16527 // Find the largest store unit
16528 MVT StoreType = MVT::i8;
16529 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16530 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16531 MVT Tp = (MVT::SimpleValueType)tp;
16532 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16536 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16537 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16538 (64 <= NumElems * ToSz))
16539 StoreType = MVT::f64;
16541 // Bitcast the original vector into a vector of store-size units
16542 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16543 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16544 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16545 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16546 SmallVector<SDValue, 8> Chains;
16547 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16548 TLI.getPointerTy());
16549 SDValue Ptr = St->getBasePtr();
16551 // Perform one or more big stores into memory.
16552 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16553 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16554 StoreType, ShuffWide,
16555 DAG.getIntPtrConstant(i));
16556 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16557 St->getPointerInfo(), St->isVolatile(),
16558 St->isNonTemporal(), St->getAlignment());
16559 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16560 Chains.push_back(Ch);
16563 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16567 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
16568 // the FP state in cases where an emms may be missing.
16569 // A preferable solution to the general problem is to figure out the right
16570 // places to insert EMMS. This qualifies as a quick hack.
16572 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16573 if (VT.getSizeInBits() != 64)
16576 const Function *F = DAG.getMachineFunction().getFunction();
16577 bool NoImplicitFloatOps = F->getFnAttributes().
16578 hasAttribute(Attribute::NoImplicitFloat);
16579 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16580 && Subtarget->hasSSE2();
16581 if ((VT.isVector() ||
16582 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16583 isa<LoadSDNode>(St->getValue()) &&
16584 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16585 St->getChain().hasOneUse() && !St->isVolatile()) {
16586 SDNode* LdVal = St->getValue().getNode();
16587 LoadSDNode *Ld = 0;
16588 int TokenFactorIndex = -1;
16589 SmallVector<SDValue, 8> Ops;
16590 SDNode* ChainVal = St->getChain().getNode();
16591 // Must be a store of a load. We currently handle two cases: the load
16592 // is a direct child, and it's under an intervening TokenFactor. It is
16593 // possible to dig deeper under nested TokenFactors.
16594 if (ChainVal == LdVal)
16595 Ld = cast<LoadSDNode>(St->getChain());
16596 else if (St->getValue().hasOneUse() &&
16597 ChainVal->getOpcode() == ISD::TokenFactor) {
16598 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16599 if (ChainVal->getOperand(i).getNode() == LdVal) {
16600 TokenFactorIndex = i;
16601 Ld = cast<LoadSDNode>(St->getValue());
16603 Ops.push_back(ChainVal->getOperand(i));
16607 if (!Ld || !ISD::isNormalLoad(Ld))
16610 // If this is not the MMX case, i.e. we are just turning i64 load/store
16611 // into f64 load/store, avoid the transformation if there are multiple
16612 // uses of the loaded value.
16613 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16616 DebugLoc LdDL = Ld->getDebugLoc();
16617 DebugLoc StDL = N->getDebugLoc();
16618 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16619 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16621 if (Subtarget->is64Bit() || F64IsLegal) {
16622 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16623 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16624 Ld->getPointerInfo(), Ld->isVolatile(),
16625 Ld->isNonTemporal(), Ld->isInvariant(),
16626 Ld->getAlignment());
16627 SDValue NewChain = NewLd.getValue(1);
16628 if (TokenFactorIndex != -1) {
16629 Ops.push_back(NewChain);
16630 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16633 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16634 St->getPointerInfo(),
16635 St->isVolatile(), St->isNonTemporal(),
16636 St->getAlignment());
16639 // Otherwise, lower to two pairs of 32-bit loads / stores.
16640 SDValue LoAddr = Ld->getBasePtr();
16641 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16642 DAG.getConstant(4, MVT::i32));
16644 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16645 Ld->getPointerInfo(),
16646 Ld->isVolatile(), Ld->isNonTemporal(),
16647 Ld->isInvariant(), Ld->getAlignment());
16648 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16649 Ld->getPointerInfo().getWithOffset(4),
16650 Ld->isVolatile(), Ld->isNonTemporal(),
16652 MinAlign(Ld->getAlignment(), 4));
16654 SDValue NewChain = LoLd.getValue(1);
16655 if (TokenFactorIndex != -1) {
16656 Ops.push_back(LoLd);
16657 Ops.push_back(HiLd);
16658 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16662 LoAddr = St->getBasePtr();
16663 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16664 DAG.getConstant(4, MVT::i32));
16666 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16667 St->getPointerInfo(),
16668 St->isVolatile(), St->isNonTemporal(),
16669 St->getAlignment());
16670 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16671 St->getPointerInfo().getWithOffset(4),
16673 St->isNonTemporal(),
16674 MinAlign(St->getAlignment(), 4));
16675 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16680 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16681 /// and return the operands for the horizontal operation in LHS and RHS. A
16682 /// horizontal operation performs the binary operation on successive elements
16683 /// of its first operand, then on successive elements of its second operand,
16684 /// returning the resulting values in a vector. For example, if
16685 /// A = < float a0, float a1, float a2, float a3 >
16687 /// B = < float b0, float b1, float b2, float b3 >
16688 /// then the result of doing a horizontal operation on A and B is
16689 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16690 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16691 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16692 /// set to A, RHS to B, and the routine returns 'true'.
16693 /// Note that the binary operation should have the property that if one of the
16694 /// operands is UNDEF then the result is UNDEF.
16695 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16696 // Look for the following pattern: if
16697 // A = < float a0, float a1, float a2, float a3 >
16698 // B = < float b0, float b1, float b2, float b3 >
16700 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16701 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16702 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16703 // which is A horizontal-op B.
16705 // At least one of the operands should be a vector shuffle.
16706 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16707 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16710 EVT VT = LHS.getValueType();
16712 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16713 "Unsupported vector type for horizontal add/sub");
16715 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16716 // operate independently on 128-bit lanes.
16717 unsigned NumElts = VT.getVectorNumElements();
16718 unsigned NumLanes = VT.getSizeInBits()/128;
16719 unsigned NumLaneElts = NumElts / NumLanes;
16720 assert((NumLaneElts % 2 == 0) &&
16721 "Vector type should have an even number of elements in each lane");
16722 unsigned HalfLaneElts = NumLaneElts/2;
16724 // View LHS in the form
16725 // LHS = VECTOR_SHUFFLE A, B, LMask
16726 // If LHS is not a shuffle then pretend it is the shuffle
16727 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16728 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16731 SmallVector<int, 16> LMask(NumElts);
16732 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16733 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16734 A = LHS.getOperand(0);
16735 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16736 B = LHS.getOperand(1);
16737 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16738 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16740 if (LHS.getOpcode() != ISD::UNDEF)
16742 for (unsigned i = 0; i != NumElts; ++i)
16746 // Likewise, view RHS in the form
16747 // RHS = VECTOR_SHUFFLE C, D, RMask
16749 SmallVector<int, 16> RMask(NumElts);
16750 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16751 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16752 C = RHS.getOperand(0);
16753 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16754 D = RHS.getOperand(1);
16755 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16756 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16758 if (RHS.getOpcode() != ISD::UNDEF)
16760 for (unsigned i = 0; i != NumElts; ++i)
16764 // Check that the shuffles are both shuffling the same vectors.
16765 if (!(A == C && B == D) && !(A == D && B == C))
16768 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16769 if (!A.getNode() && !B.getNode())
16772 // If A and B occur in reverse order in RHS, then "swap" them (which means
16773 // rewriting the mask).
16775 CommuteVectorShuffleMask(RMask, NumElts);
16777 // At this point LHS and RHS are equivalent to
16778 // LHS = VECTOR_SHUFFLE A, B, LMask
16779 // RHS = VECTOR_SHUFFLE A, B, RMask
16780 // Check that the masks correspond to performing a horizontal operation.
16781 for (unsigned i = 0; i != NumElts; ++i) {
16782 int LIdx = LMask[i], RIdx = RMask[i];
16784 // Ignore any UNDEF components.
16785 if (LIdx < 0 || RIdx < 0 ||
16786 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16787 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16790 // Check that successive elements are being operated on. If not, this is
16791 // not a horizontal operation.
16792 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16793 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16794 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16795 if (!(LIdx == Index && RIdx == Index + 1) &&
16796 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16800 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16801 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16805 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16806 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16807 const X86Subtarget *Subtarget) {
16808 EVT VT = N->getValueType(0);
16809 SDValue LHS = N->getOperand(0);
16810 SDValue RHS = N->getOperand(1);
16812 // Try to synthesize horizontal adds from adds of shuffles.
16813 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16814 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16815 isHorizontalBinOp(LHS, RHS, true))
16816 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16820 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16821 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16822 const X86Subtarget *Subtarget) {
16823 EVT VT = N->getValueType(0);
16824 SDValue LHS = N->getOperand(0);
16825 SDValue RHS = N->getOperand(1);
16827 // Try to synthesize horizontal subs from subs of shuffles.
16828 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16829 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16830 isHorizontalBinOp(LHS, RHS, false))
16831 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16835 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16836 /// X86ISD::FXOR nodes.
16837 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16838 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16839 // F[X]OR(0.0, x) -> x
16840 // F[X]OR(x, 0.0) -> x
16841 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16842 if (C->getValueAPF().isPosZero())
16843 return N->getOperand(1);
16844 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16845 if (C->getValueAPF().isPosZero())
16846 return N->getOperand(0);
16850 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16851 /// X86ISD::FMAX nodes.
16852 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16853 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16855 // Only perform optimizations if UnsafeMath is used.
16856 if (!DAG.getTarget().Options.UnsafeFPMath)
16859 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16860 // into FMINC and FMAXC, which are Commutative operations.
16861 unsigned NewOp = 0;
16862 switch (N->getOpcode()) {
16863 default: llvm_unreachable("unknown opcode");
16864 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16865 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16868 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16869 N->getOperand(0), N->getOperand(1));
16872 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16873 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16874 // FAND(0.0, x) -> 0.0
16875 // FAND(x, 0.0) -> 0.0
16876 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16877 if (C->getValueAPF().isPosZero())
16878 return N->getOperand(0);
16879 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16880 if (C->getValueAPF().isPosZero())
16881 return N->getOperand(1);
16885 static SDValue PerformBTCombine(SDNode *N,
16887 TargetLowering::DAGCombinerInfo &DCI) {
16888 // BT ignores high bits in the bit index operand.
16889 SDValue Op1 = N->getOperand(1);
16890 if (Op1.hasOneUse()) {
16891 unsigned BitWidth = Op1.getValueSizeInBits();
16892 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16893 APInt KnownZero, KnownOne;
16894 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16895 !DCI.isBeforeLegalizeOps());
16896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16897 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16898 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16899 DCI.CommitTargetLoweringOpt(TLO);
16904 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16905 SDValue Op = N->getOperand(0);
16906 if (Op.getOpcode() == ISD::BITCAST)
16907 Op = Op.getOperand(0);
16908 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16909 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16910 VT.getVectorElementType().getSizeInBits() ==
16911 OpVT.getVectorElementType().getSizeInBits()) {
16912 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16917 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16918 TargetLowering::DAGCombinerInfo &DCI,
16919 const X86Subtarget *Subtarget) {
16920 if (!DCI.isBeforeLegalizeOps())
16923 if (!Subtarget->hasFp256())
16926 EVT VT = N->getValueType(0);
16927 if (VT.isVector() && VT.getSizeInBits() == 256) {
16928 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
16936 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16937 const X86Subtarget* Subtarget) {
16938 DebugLoc dl = N->getDebugLoc();
16939 EVT VT = N->getValueType(0);
16941 // Let legalize expand this if it isn't a legal type yet.
16942 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16945 EVT ScalarVT = VT.getScalarType();
16946 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16947 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16950 SDValue A = N->getOperand(0);
16951 SDValue B = N->getOperand(1);
16952 SDValue C = N->getOperand(2);
16954 bool NegA = (A.getOpcode() == ISD::FNEG);
16955 bool NegB = (B.getOpcode() == ISD::FNEG);
16956 bool NegC = (C.getOpcode() == ISD::FNEG);
16958 // Negative multiplication when NegA xor NegB
16959 bool NegMul = (NegA != NegB);
16961 A = A.getOperand(0);
16963 B = B.getOperand(0);
16965 C = C.getOperand(0);
16969 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16971 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16973 return DAG.getNode(Opcode, dl, VT, A, B, C);
16976 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16977 TargetLowering::DAGCombinerInfo &DCI,
16978 const X86Subtarget *Subtarget) {
16979 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16980 // (and (i32 x86isd::setcc_carry), 1)
16981 // This eliminates the zext. This transformation is necessary because
16982 // ISD::SETCC is always legalized to i8.
16983 DebugLoc dl = N->getDebugLoc();
16984 SDValue N0 = N->getOperand(0);
16985 EVT VT = N->getValueType(0);
16987 if (N0.getOpcode() == ISD::AND &&
16989 N0.getOperand(0).hasOneUse()) {
16990 SDValue N00 = N0.getOperand(0);
16991 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
16992 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16993 if (!C || C->getZExtValue() != 1)
16995 return DAG.getNode(ISD::AND, dl, VT,
16996 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16997 N00.getOperand(0), N00.getOperand(1)),
16998 DAG.getConstant(1, VT));
17002 if (VT.isVector() && VT.getSizeInBits() == 256) {
17003 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17011 // Optimize x == -y --> x+y == 0
17012 // x != -y --> x+y != 0
17013 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17014 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17015 SDValue LHS = N->getOperand(0);
17016 SDValue RHS = N->getOperand(1);
17018 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17019 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17020 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17021 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17022 LHS.getValueType(), RHS, LHS.getOperand(1));
17023 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17024 addV, DAG.getConstant(0, addV.getValueType()), CC);
17026 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17028 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17029 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17030 RHS.getValueType(), LHS, RHS.getOperand(1));
17031 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17032 addV, DAG.getConstant(0, addV.getValueType()), CC);
17037 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17038 // as "sbb reg,reg", since it can be extended without zext and produces
17039 // an all-ones bit which is more useful than 0/1 in some cases.
17040 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17041 return DAG.getNode(ISD::AND, DL, MVT::i8,
17042 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17043 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17044 DAG.getConstant(1, MVT::i8));
17047 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17048 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17049 TargetLowering::DAGCombinerInfo &DCI,
17050 const X86Subtarget *Subtarget) {
17051 DebugLoc DL = N->getDebugLoc();
17052 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17053 SDValue EFLAGS = N->getOperand(1);
17055 if (CC == X86::COND_A) {
17056 // Try to convert COND_A into COND_B in an attempt to facilitate
17057 // materializing "setb reg".
17059 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17060 // cannot take an immediate as its first operand.
17062 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17063 EFLAGS.getValueType().isInteger() &&
17064 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17065 SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17066 EFLAGS.getNode()->getVTList(),
17067 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17068 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17069 return MaterializeSETB(DL, NewEFLAGS, DAG);
17073 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17074 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17076 if (CC == X86::COND_B)
17077 return MaterializeSETB(DL, EFLAGS, DAG);
17081 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17082 if (Flags.getNode()) {
17083 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17084 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17090 // Optimize branch condition evaluation.
17092 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17093 TargetLowering::DAGCombinerInfo &DCI,
17094 const X86Subtarget *Subtarget) {
17095 DebugLoc DL = N->getDebugLoc();
17096 SDValue Chain = N->getOperand(0);
17097 SDValue Dest = N->getOperand(1);
17098 SDValue EFLAGS = N->getOperand(3);
17099 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17103 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17104 if (Flags.getNode()) {
17105 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17106 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17113 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17114 const X86TargetLowering *XTLI) {
17115 SDValue Op0 = N->getOperand(0);
17116 EVT InVT = Op0->getValueType(0);
17118 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17119 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17120 DebugLoc dl = N->getDebugLoc();
17121 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17122 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17123 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17126 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17127 // a 32-bit target where SSE doesn't support i64->FP operations.
17128 if (Op0.getOpcode() == ISD::LOAD) {
17129 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17130 EVT VT = Ld->getValueType(0);
17131 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17132 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17133 !XTLI->getSubtarget()->is64Bit() &&
17134 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17135 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17136 Ld->getChain(), Op0, DAG);
17137 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17144 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17145 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17146 X86TargetLowering::DAGCombinerInfo &DCI) {
17147 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17148 // the result is either zero or one (depending on the input carry bit).
17149 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17150 if (X86::isZeroNode(N->getOperand(0)) &&
17151 X86::isZeroNode(N->getOperand(1)) &&
17152 // We don't have a good way to replace an EFLAGS use, so only do this when
17154 SDValue(N, 1).use_empty()) {
17155 DebugLoc DL = N->getDebugLoc();
17156 EVT VT = N->getValueType(0);
17157 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17158 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17159 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17160 DAG.getConstant(X86::COND_B,MVT::i8),
17162 DAG.getConstant(1, VT));
17163 return DCI.CombineTo(N, Res1, CarryOut);
17169 // fold (add Y, (sete X, 0)) -> adc 0, Y
17170 // (add Y, (setne X, 0)) -> sbb -1, Y
17171 // (sub (sete X, 0), Y) -> sbb 0, Y
17172 // (sub (setne X, 0), Y) -> adc -1, Y
17173 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17174 DebugLoc DL = N->getDebugLoc();
17176 // Look through ZExts.
17177 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17178 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17181 SDValue SetCC = Ext.getOperand(0);
17182 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17185 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17186 if (CC != X86::COND_E && CC != X86::COND_NE)
17189 SDValue Cmp = SetCC.getOperand(1);
17190 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17191 !X86::isZeroNode(Cmp.getOperand(1)) ||
17192 !Cmp.getOperand(0).getValueType().isInteger())
17195 SDValue CmpOp0 = Cmp.getOperand(0);
17196 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17197 DAG.getConstant(1, CmpOp0.getValueType()));
17199 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17200 if (CC == X86::COND_NE)
17201 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17202 DL, OtherVal.getValueType(), OtherVal,
17203 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17204 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17205 DL, OtherVal.getValueType(), OtherVal,
17206 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17209 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17210 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17211 const X86Subtarget *Subtarget) {
17212 EVT VT = N->getValueType(0);
17213 SDValue Op0 = N->getOperand(0);
17214 SDValue Op1 = N->getOperand(1);
17216 // Try to synthesize horizontal adds from adds of shuffles.
17217 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17218 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17219 isHorizontalBinOp(Op0, Op1, true))
17220 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17222 return OptimizeConditionalInDecrement(N, DAG);
17225 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17226 const X86Subtarget *Subtarget) {
17227 SDValue Op0 = N->getOperand(0);
17228 SDValue Op1 = N->getOperand(1);
17230 // X86 can't encode an immediate LHS of a sub. See if we can push the
17231 // negation into a preceding instruction.
17232 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17233 // If the RHS of the sub is a XOR with one use and a constant, invert the
17234 // immediate. Then add one to the LHS of the sub so we can turn
17235 // X-Y -> X+~Y+1, saving one register.
17236 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17237 isa<ConstantSDNode>(Op1.getOperand(1))) {
17238 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17239 EVT VT = Op0.getValueType();
17240 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17242 DAG.getConstant(~XorC, VT));
17243 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17244 DAG.getConstant(C->getAPIntValue()+1, VT));
17248 // Try to synthesize horizontal adds from adds of shuffles.
17249 EVT VT = N->getValueType(0);
17250 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17251 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17252 isHorizontalBinOp(Op0, Op1, true))
17253 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17255 return OptimizeConditionalInDecrement(N, DAG);
17258 /// performVZEXTCombine - Performs build vector combines
17259 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17260 TargetLowering::DAGCombinerInfo &DCI,
17261 const X86Subtarget *Subtarget) {
17262 // (vzext (bitcast (vzext (x)) -> (vzext x)
17263 SDValue In = N->getOperand(0);
17264 while (In.getOpcode() == ISD::BITCAST)
17265 In = In.getOperand(0);
17267 if (In.getOpcode() != X86ISD::VZEXT)
17270 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17273 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17274 DAGCombinerInfo &DCI) const {
17275 SelectionDAG &DAG = DCI.DAG;
17276 switch (N->getOpcode()) {
17278 case ISD::EXTRACT_VECTOR_ELT:
17279 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17281 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17282 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17283 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17284 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17285 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17286 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17289 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17290 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17291 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17292 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17293 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17294 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17295 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17296 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17297 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17299 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17301 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17302 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17303 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17304 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17305 case ISD::ANY_EXTEND:
17306 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17307 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17308 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17309 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17310 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17311 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17312 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17313 case X86ISD::SHUFP: // Handle all target specific shuffles
17314 case X86ISD::PALIGN:
17315 case X86ISD::UNPCKH:
17316 case X86ISD::UNPCKL:
17317 case X86ISD::MOVHLPS:
17318 case X86ISD::MOVLHPS:
17319 case X86ISD::PSHUFD:
17320 case X86ISD::PSHUFHW:
17321 case X86ISD::PSHUFLW:
17322 case X86ISD::MOVSS:
17323 case X86ISD::MOVSD:
17324 case X86ISD::VPERMILP:
17325 case X86ISD::VPERM2X128:
17326 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17327 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17333 /// isTypeDesirableForOp - Return true if the target has native support for
17334 /// the specified value type and it is 'desirable' to use the type for the
17335 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17336 /// instruction encodings are longer and some i16 instructions are slow.
17337 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17338 if (!isTypeLegal(VT))
17340 if (VT != MVT::i16)
17347 case ISD::SIGN_EXTEND:
17348 case ISD::ZERO_EXTEND:
17349 case ISD::ANY_EXTEND:
17362 /// IsDesirableToPromoteOp - This method query the target whether it is
17363 /// beneficial for dag combiner to promote the specified node. If true, it
17364 /// should return the desired promotion type by reference.
17365 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17366 EVT VT = Op.getValueType();
17367 if (VT != MVT::i16)
17370 bool Promote = false;
17371 bool Commute = false;
17372 switch (Op.getOpcode()) {
17375 LoadSDNode *LD = cast<LoadSDNode>(Op);
17376 // If the non-extending load has a single use and it's not live out, then it
17377 // might be folded.
17378 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17379 Op.hasOneUse()*/) {
17380 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17381 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17382 // The only case where we'd want to promote LOAD (rather then it being
17383 // promoted as an operand is when it's only use is liveout.
17384 if (UI->getOpcode() != ISD::CopyToReg)
17391 case ISD::SIGN_EXTEND:
17392 case ISD::ZERO_EXTEND:
17393 case ISD::ANY_EXTEND:
17398 SDValue N0 = Op.getOperand(0);
17399 // Look out for (store (shl (load), x)).
17400 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17413 SDValue N0 = Op.getOperand(0);
17414 SDValue N1 = Op.getOperand(1);
17415 if (!Commute && MayFoldLoad(N1))
17417 // Avoid disabling potential load folding opportunities.
17418 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17420 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17430 //===----------------------------------------------------------------------===//
17431 // X86 Inline Assembly Support
17432 //===----------------------------------------------------------------------===//
17435 // Helper to match a string separated by whitespace.
17436 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17437 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17439 for (unsigned i = 0, e = args.size(); i != e; ++i) {
17440 StringRef piece(*args[i]);
17441 if (!s.startswith(piece)) // Check if the piece matches.
17444 s = s.substr(piece.size());
17445 StringRef::size_type pos = s.find_first_not_of(" \t");
17446 if (pos == 0) // We matched a prefix.
17454 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17457 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17458 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17460 std::string AsmStr = IA->getAsmString();
17462 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17463 if (!Ty || Ty->getBitWidth() % 16 != 0)
17466 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17467 SmallVector<StringRef, 4> AsmPieces;
17468 SplitString(AsmStr, AsmPieces, ";\n");
17470 switch (AsmPieces.size()) {
17471 default: return false;
17473 // FIXME: this should verify that we are targeting a 486 or better. If not,
17474 // we will turn this bswap into something that will be lowered to logical
17475 // ops instead of emitting the bswap asm. For now, we don't support 486 or
17476 // lower so don't worry about this.
17478 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17479 matchAsm(AsmPieces[0], "bswapl", "$0") ||
17480 matchAsm(AsmPieces[0], "bswapq", "$0") ||
17481 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17482 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17483 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17484 // No need to check constraints, nothing other than the equivalent of
17485 // "=r,0" would be valid here.
17486 return IntrinsicLowering::LowerToByteSwap(CI);
17489 // rorw $$8, ${0:w} --> llvm.bswap.i16
17490 if (CI->getType()->isIntegerTy(16) &&
17491 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17492 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17493 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17495 const std::string &ConstraintsStr = IA->getConstraintString();
17496 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17497 std::sort(AsmPieces.begin(), AsmPieces.end());
17498 if (AsmPieces.size() == 4 &&
17499 AsmPieces[0] == "~{cc}" &&
17500 AsmPieces[1] == "~{dirflag}" &&
17501 AsmPieces[2] == "~{flags}" &&
17502 AsmPieces[3] == "~{fpsr}")
17503 return IntrinsicLowering::LowerToByteSwap(CI);
17507 if (CI->getType()->isIntegerTy(32) &&
17508 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17509 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17510 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17511 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17513 const std::string &ConstraintsStr = IA->getConstraintString();
17514 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17515 std::sort(AsmPieces.begin(), AsmPieces.end());
17516 if (AsmPieces.size() == 4 &&
17517 AsmPieces[0] == "~{cc}" &&
17518 AsmPieces[1] == "~{dirflag}" &&
17519 AsmPieces[2] == "~{flags}" &&
17520 AsmPieces[3] == "~{fpsr}")
17521 return IntrinsicLowering::LowerToByteSwap(CI);
17524 if (CI->getType()->isIntegerTy(64)) {
17525 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17526 if (Constraints.size() >= 2 &&
17527 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17528 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17529 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
17530 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17531 matchAsm(AsmPieces[1], "bswap", "%edx") &&
17532 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17533 return IntrinsicLowering::LowerToByteSwap(CI);
17541 /// getConstraintType - Given a constraint letter, return the type of
17542 /// constraint it is for this target.
17543 X86TargetLowering::ConstraintType
17544 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17545 if (Constraint.size() == 1) {
17546 switch (Constraint[0]) {
17557 return C_RegisterClass;
17581 return TargetLowering::getConstraintType(Constraint);
17584 /// Examine constraint type and operand type and determine a weight value.
17585 /// This object must already have been set up with the operand type
17586 /// and the current alternative constraint selected.
17587 TargetLowering::ConstraintWeight
17588 X86TargetLowering::getSingleConstraintMatchWeight(
17589 AsmOperandInfo &info, const char *constraint) const {
17590 ConstraintWeight weight = CW_Invalid;
17591 Value *CallOperandVal = info.CallOperandVal;
17592 // If we don't have a value, we can't do a match,
17593 // but allow it at the lowest weight.
17594 if (CallOperandVal == NULL)
17596 Type *type = CallOperandVal->getType();
17597 // Look at the constraint type.
17598 switch (*constraint) {
17600 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17611 if (CallOperandVal->getType()->isIntegerTy())
17612 weight = CW_SpecificReg;
17617 if (type->isFloatingPointTy())
17618 weight = CW_SpecificReg;
17621 if (type->isX86_MMXTy() && Subtarget->hasMMX())
17622 weight = CW_SpecificReg;
17626 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17627 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17628 weight = CW_Register;
17631 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17632 if (C->getZExtValue() <= 31)
17633 weight = CW_Constant;
17637 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17638 if (C->getZExtValue() <= 63)
17639 weight = CW_Constant;
17643 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17644 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17645 weight = CW_Constant;
17649 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17650 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17651 weight = CW_Constant;
17655 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17656 if (C->getZExtValue() <= 3)
17657 weight = CW_Constant;
17661 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17662 if (C->getZExtValue() <= 0xff)
17663 weight = CW_Constant;
17668 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17669 weight = CW_Constant;
17673 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17674 if ((C->getSExtValue() >= -0x80000000LL) &&
17675 (C->getSExtValue() <= 0x7fffffffLL))
17676 weight = CW_Constant;
17680 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17681 if (C->getZExtValue() <= 0xffffffff)
17682 weight = CW_Constant;
17689 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17690 /// with another that has more specific requirements based on the type of the
17691 /// corresponding operand.
17692 const char *X86TargetLowering::
17693 LowerXConstraint(EVT ConstraintVT) const {
17694 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17695 // 'f' like normal targets.
17696 if (ConstraintVT.isFloatingPoint()) {
17697 if (Subtarget->hasSSE2())
17699 if (Subtarget->hasSSE1())
17703 return TargetLowering::LowerXConstraint(ConstraintVT);
17706 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17707 /// vector. If it is invalid, don't add anything to Ops.
17708 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17709 std::string &Constraint,
17710 std::vector<SDValue>&Ops,
17711 SelectionDAG &DAG) const {
17712 SDValue Result(0, 0);
17714 // Only support length 1 constraints for now.
17715 if (Constraint.length() > 1) return;
17717 char ConstraintLetter = Constraint[0];
17718 switch (ConstraintLetter) {
17721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17722 if (C->getZExtValue() <= 31) {
17723 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17729 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17730 if (C->getZExtValue() <= 63) {
17731 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17737 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17738 if (isInt<8>(C->getSExtValue())) {
17739 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17745 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17746 if (C->getZExtValue() <= 255) {
17747 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17753 // 32-bit signed value
17754 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17755 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17756 C->getSExtValue())) {
17757 // Widen to 64 bits here to get it sign extended.
17758 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17761 // FIXME gcc accepts some relocatable values here too, but only in certain
17762 // memory models; it's complicated.
17767 // 32-bit unsigned value
17768 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17769 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17770 C->getZExtValue())) {
17771 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17775 // FIXME gcc accepts some relocatable values here too, but only in certain
17776 // memory models; it's complicated.
17780 // Literal immediates are always ok.
17781 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17782 // Widen to 64 bits here to get it sign extended.
17783 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17787 // In any sort of PIC mode addresses need to be computed at runtime by
17788 // adding in a register or some sort of table lookup. These can't
17789 // be used as immediates.
17790 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17793 // If we are in non-pic codegen mode, we allow the address of a global (with
17794 // an optional displacement) to be used with 'i'.
17795 GlobalAddressSDNode *GA = 0;
17796 int64_t Offset = 0;
17798 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17800 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17801 Offset += GA->getOffset();
17803 } else if (Op.getOpcode() == ISD::ADD) {
17804 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17805 Offset += C->getZExtValue();
17806 Op = Op.getOperand(0);
17809 } else if (Op.getOpcode() == ISD::SUB) {
17810 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17811 Offset += -C->getZExtValue();
17812 Op = Op.getOperand(0);
17817 // Otherwise, this isn't something we can handle, reject it.
17821 const GlobalValue *GV = GA->getGlobal();
17822 // If we require an extra load to get this address, as in PIC mode, we
17823 // can't accept it.
17824 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17825 getTargetMachine())))
17828 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17829 GA->getValueType(0), Offset);
17834 if (Result.getNode()) {
17835 Ops.push_back(Result);
17838 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17841 std::pair<unsigned, const TargetRegisterClass*>
17842 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17844 // First, see if this is a constraint that directly corresponds to an LLVM
17846 if (Constraint.size() == 1) {
17847 // GCC Constraint Letters
17848 switch (Constraint[0]) {
17850 // TODO: Slight differences here in allocation order and leaving
17851 // RIP in the class. Do they matter any more here than they do
17852 // in the normal allocation?
17853 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17854 if (Subtarget->is64Bit()) {
17855 if (VT == MVT::i32 || VT == MVT::f32)
17856 return std::make_pair(0U, &X86::GR32RegClass);
17857 if (VT == MVT::i16)
17858 return std::make_pair(0U, &X86::GR16RegClass);
17859 if (VT == MVT::i8 || VT == MVT::i1)
17860 return std::make_pair(0U, &X86::GR8RegClass);
17861 if (VT == MVT::i64 || VT == MVT::f64)
17862 return std::make_pair(0U, &X86::GR64RegClass);
17865 // 32-bit fallthrough
17866 case 'Q': // Q_REGS
17867 if (VT == MVT::i32 || VT == MVT::f32)
17868 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17869 if (VT == MVT::i16)
17870 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17871 if (VT == MVT::i8 || VT == MVT::i1)
17872 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17873 if (VT == MVT::i64)
17874 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17876 case 'r': // GENERAL_REGS
17877 case 'l': // INDEX_REGS
17878 if (VT == MVT::i8 || VT == MVT::i1)
17879 return std::make_pair(0U, &X86::GR8RegClass);
17880 if (VT == MVT::i16)
17881 return std::make_pair(0U, &X86::GR16RegClass);
17882 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17883 return std::make_pair(0U, &X86::GR32RegClass);
17884 return std::make_pair(0U, &X86::GR64RegClass);
17885 case 'R': // LEGACY_REGS
17886 if (VT == MVT::i8 || VT == MVT::i1)
17887 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17888 if (VT == MVT::i16)
17889 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17890 if (VT == MVT::i32 || !Subtarget->is64Bit())
17891 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17892 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17893 case 'f': // FP Stack registers.
17894 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17895 // value to the correct fpstack register class.
17896 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17897 return std::make_pair(0U, &X86::RFP32RegClass);
17898 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17899 return std::make_pair(0U, &X86::RFP64RegClass);
17900 return std::make_pair(0U, &X86::RFP80RegClass);
17901 case 'y': // MMX_REGS if MMX allowed.
17902 if (!Subtarget->hasMMX()) break;
17903 return std::make_pair(0U, &X86::VR64RegClass);
17904 case 'Y': // SSE_REGS if SSE2 allowed
17905 if (!Subtarget->hasSSE2()) break;
17907 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17908 if (!Subtarget->hasSSE1()) break;
17910 switch (VT.getSimpleVT().SimpleTy) {
17912 // Scalar SSE types.
17915 return std::make_pair(0U, &X86::FR32RegClass);
17918 return std::make_pair(0U, &X86::FR64RegClass);
17926 return std::make_pair(0U, &X86::VR128RegClass);
17934 return std::make_pair(0U, &X86::VR256RegClass);
17940 // Use the default implementation in TargetLowering to convert the register
17941 // constraint into a member of a register class.
17942 std::pair<unsigned, const TargetRegisterClass*> Res;
17943 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17945 // Not found as a standard register?
17946 if (Res.second == 0) {
17947 // Map st(0) -> st(7) -> ST0
17948 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17949 tolower(Constraint[1]) == 's' &&
17950 tolower(Constraint[2]) == 't' &&
17951 Constraint[3] == '(' &&
17952 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17953 Constraint[5] == ')' &&
17954 Constraint[6] == '}') {
17956 Res.first = X86::ST0+Constraint[4]-'0';
17957 Res.second = &X86::RFP80RegClass;
17961 // GCC allows "st(0)" to be called just plain "st".
17962 if (StringRef("{st}").equals_lower(Constraint)) {
17963 Res.first = X86::ST0;
17964 Res.second = &X86::RFP80RegClass;
17969 if (StringRef("{flags}").equals_lower(Constraint)) {
17970 Res.first = X86::EFLAGS;
17971 Res.second = &X86::CCRRegClass;
17975 // 'A' means EAX + EDX.
17976 if (Constraint == "A") {
17977 Res.first = X86::EAX;
17978 Res.second = &X86::GR32_ADRegClass;
17984 // Otherwise, check to see if this is a register class of the wrong value
17985 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17986 // turn into {ax},{dx}.
17987 if (Res.second->hasType(VT))
17988 return Res; // Correct type already, nothing to do.
17990 // All of the single-register GCC register classes map their values onto
17991 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17992 // really want an 8-bit or 32-bit register, map to the appropriate register
17993 // class and return the appropriate register.
17994 if (Res.second == &X86::GR16RegClass) {
17995 if (VT == MVT::i8) {
17996 unsigned DestReg = 0;
17997 switch (Res.first) {
17999 case X86::AX: DestReg = X86::AL; break;
18000 case X86::DX: DestReg = X86::DL; break;
18001 case X86::CX: DestReg = X86::CL; break;
18002 case X86::BX: DestReg = X86::BL; break;
18005 Res.first = DestReg;
18006 Res.second = &X86::GR8RegClass;
18008 } else if (VT == MVT::i32) {
18009 unsigned DestReg = 0;
18010 switch (Res.first) {
18012 case X86::AX: DestReg = X86::EAX; break;
18013 case X86::DX: DestReg = X86::EDX; break;
18014 case X86::CX: DestReg = X86::ECX; break;
18015 case X86::BX: DestReg = X86::EBX; break;
18016 case X86::SI: DestReg = X86::ESI; break;
18017 case X86::DI: DestReg = X86::EDI; break;
18018 case X86::BP: DestReg = X86::EBP; break;
18019 case X86::SP: DestReg = X86::ESP; break;
18022 Res.first = DestReg;
18023 Res.second = &X86::GR32RegClass;
18025 } else if (VT == MVT::i64) {
18026 unsigned DestReg = 0;
18027 switch (Res.first) {
18029 case X86::AX: DestReg = X86::RAX; break;
18030 case X86::DX: DestReg = X86::RDX; break;
18031 case X86::CX: DestReg = X86::RCX; break;
18032 case X86::BX: DestReg = X86::RBX; break;
18033 case X86::SI: DestReg = X86::RSI; break;
18034 case X86::DI: DestReg = X86::RDI; break;
18035 case X86::BP: DestReg = X86::RBP; break;
18036 case X86::SP: DestReg = X86::RSP; break;
18039 Res.first = DestReg;
18040 Res.second = &X86::GR64RegClass;
18043 } else if (Res.second == &X86::FR32RegClass ||
18044 Res.second == &X86::FR64RegClass ||
18045 Res.second == &X86::VR128RegClass) {
18046 // Handle references to XMM physical registers that got mapped into the
18047 // wrong class. This can happen with constraints like {xmm0} where the
18048 // target independent register mapper will just pick the first match it can
18049 // find, ignoring the required type.
18051 if (VT == MVT::f32 || VT == MVT::i32)
18052 Res.second = &X86::FR32RegClass;
18053 else if (VT == MVT::f64 || VT == MVT::i64)
18054 Res.second = &X86::FR64RegClass;
18055 else if (X86::VR128RegClass.hasType(VT))
18056 Res.second = &X86::VR128RegClass;
18057 else if (X86::VR256RegClass.hasType(VT))
18058 Res.second = &X86::VR256RegClass;
18064 //===----------------------------------------------------------------------===//
18068 //===----------------------------------------------------------------------===//
18070 struct X86CostTblEntry {
18077 FindInTable(const X86CostTblEntry *Tbl, unsigned len, int ISD, MVT Ty) {
18078 for (unsigned int i = 0; i < len; ++i)
18079 if (Tbl[i].ISD == ISD && Tbl[i].Type == Ty)
18082 // Could not find an entry.
18086 struct X86TypeConversionCostTblEntry {
18094 FindInConvertTable(const X86TypeConversionCostTblEntry *Tbl, unsigned len,
18095 int ISD, MVT Dst, MVT Src) {
18096 for (unsigned int i = 0; i < len; ++i)
18097 if (Tbl[i].ISD == ISD && Tbl[i].Src == Src && Tbl[i].Dst == Dst)
18100 // Could not find an entry.
18104 ScalarTargetTransformInfo::PopcntHwSupport
18105 X86ScalarTargetTransformImpl::getPopcntHwSupport(unsigned TyWidth) const {
18106 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
18107 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18109 // TODO: Currently the __builtin_popcount() implementation using SSE3
18110 // instructions is inefficient. Once the problem is fixed, we should
18111 // call ST.hasSSE3() instead of ST.hasSSE4().
18112 return ST.hasSSE41() ? Fast : None;
18116 X86VectorTargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
18118 // Legalize the type.
18119 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Ty);
18121 int ISD = InstructionOpcodeToISD(Opcode);
18122 assert(ISD && "Invalid opcode");
18124 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18126 static const X86CostTblEntry AVX1CostTable[] = {
18127 // We don't have to scalarize unsupported ops. We can issue two half-sized
18128 // operations and we only need to extract the upper YMM half.
18129 // Two ops + 1 extract + 1 insert = 4.
18130 { ISD::MUL, MVT::v8i32, 4 },
18131 { ISD::SUB, MVT::v8i32, 4 },
18132 { ISD::ADD, MVT::v8i32, 4 },
18133 { ISD::MUL, MVT::v4i64, 4 },
18134 { ISD::SUB, MVT::v4i64, 4 },
18135 { ISD::ADD, MVT::v4i64, 4 },
18138 // Look for AVX1 lowering tricks.
18140 int Idx = FindInTable(AVX1CostTable, array_lengthof(AVX1CostTable), ISD,
18143 return LT.first * AVX1CostTable[Idx].Cost;
18145 // Fallback to the default implementation.
18146 return VectorTargetTransformImpl::getArithmeticInstrCost(Opcode, Ty);
18150 X86VectorTargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
18151 unsigned Alignment,
18152 unsigned AddressSpace) const {
18153 // Legalize the type.
18154 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Src);
18155 assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
18158 const X86Subtarget &ST =
18159 TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18161 // Each load/store unit costs 1.
18162 unsigned Cost = LT.first * 1;
18164 // On Sandybridge 256bit load/stores are double pumped
18165 // (but not on Haswell).
18166 if (LT.second.getSizeInBits() > 128 && !ST.hasAVX2())
18173 X86VectorTargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
18174 unsigned Index) const {
18175 assert(Val->isVectorTy() && "This must be a vector type");
18177 if (Index != -1U) {
18178 // Legalize the type.
18179 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Val);
18181 // This type is legalized to a scalar type.
18182 if (!LT.second.isVector())
18185 // The type may be split. Normalize the index to the new type.
18186 unsigned Width = LT.second.getVectorNumElements();
18187 Index = Index % Width;
18189 // Floating point scalars are already located in index #0.
18190 if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
18194 return VectorTargetTransformImpl::getVectorInstrCost(Opcode, Val, Index);
18197 unsigned X86VectorTargetTransformInfo::getCmpSelInstrCost(unsigned Opcode,
18199 Type *CondTy) const {
18200 // Legalize the type.
18201 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(ValTy);
18203 MVT MTy = LT.second;
18205 int ISD = InstructionOpcodeToISD(Opcode);
18206 assert(ISD && "Invalid opcode");
18208 const X86Subtarget &ST =
18209 TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18211 static const X86CostTblEntry SSE42CostTbl[] = {
18212 { ISD::SETCC, MVT::v2f64, 1 },
18213 { ISD::SETCC, MVT::v4f32, 1 },
18214 { ISD::SETCC, MVT::v2i64, 1 },
18215 { ISD::SETCC, MVT::v4i32, 1 },
18216 { ISD::SETCC, MVT::v8i16, 1 },
18217 { ISD::SETCC, MVT::v16i8, 1 },
18220 static const X86CostTblEntry AVX1CostTbl[] = {
18221 { ISD::SETCC, MVT::v4f64, 1 },
18222 { ISD::SETCC, MVT::v8f32, 1 },
18223 // AVX1 does not support 8-wide integer compare.
18224 { ISD::SETCC, MVT::v4i64, 4 },
18225 { ISD::SETCC, MVT::v8i32, 4 },
18226 { ISD::SETCC, MVT::v16i16, 4 },
18227 { ISD::SETCC, MVT::v32i8, 4 },
18230 static const X86CostTblEntry AVX2CostTbl[] = {
18231 { ISD::SETCC, MVT::v4i64, 1 },
18232 { ISD::SETCC, MVT::v8i32, 1 },
18233 { ISD::SETCC, MVT::v16i16, 1 },
18234 { ISD::SETCC, MVT::v32i8, 1 },
18237 if (ST.hasAVX2()) {
18238 int Idx = FindInTable(AVX2CostTbl, array_lengthof(AVX2CostTbl), ISD, MTy);
18240 return LT.first * AVX2CostTbl[Idx].Cost;
18244 int Idx = FindInTable(AVX1CostTbl, array_lengthof(AVX1CostTbl), ISD, MTy);
18246 return LT.first * AVX1CostTbl[Idx].Cost;
18249 if (ST.hasSSE42()) {
18250 int Idx = FindInTable(SSE42CostTbl, array_lengthof(SSE42CostTbl), ISD, MTy);
18252 return LT.first * SSE42CostTbl[Idx].Cost;
18255 return VectorTargetTransformImpl::getCmpSelInstrCost(Opcode, ValTy, CondTy);
18258 unsigned X86VectorTargetTransformInfo::getCastInstrCost(unsigned Opcode,
18261 int ISD = InstructionOpcodeToISD(Opcode);
18262 assert(ISD && "Invalid opcode");
18264 EVT SrcTy = TLI->getValueType(Src);
18265 EVT DstTy = TLI->getValueType(Dst);
18267 if (!SrcTy.isSimple() || !DstTy.isSimple())
18268 return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18270 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18272 static const X86TypeConversionCostTblEntry AVXConversionTbl[] = {
18273 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18274 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18275 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18276 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18277 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 1 },
18278 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 1 },
18279 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 1 },
18280 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 1 },
18281 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 1 },
18282 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 1 },
18283 { ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f32, 1 },
18284 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 1 },
18285 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1, 6 },
18286 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1, 9 },
18287 { ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 3 },
18291 int Idx = FindInConvertTable(AVXConversionTbl,
18292 array_lengthof(AVXConversionTbl),
18293 ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT());
18295 return AVXConversionTbl[Idx].Cost;
18298 return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18302 unsigned X86VectorTargetTransformInfo::getShuffleCost(ShuffleKind Kind, Type *Tp,
18304 // We only estimate the cost of reverse shuffles.
18305 if (Kind != Reverse)
18306 return VectorTargetTransformImpl::getShuffleCost(Kind, Tp, Index);
18308 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Tp);
18310 if (LT.second.getSizeInBits() > 128)
18311 Cost = 3; // Extract + insert + copy.
18313 // Multiple by the number of parts.
18314 return Cost * LT.first;