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"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.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.getConstant(NormalizedIdxVal, MVT::i32);
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.getConstant(NormalizedIdxVal, MVT::i32);
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();
161 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
163 RegInfo = TM.getRegisterInfo();
164 TD = getTargetData();
166 // Set up the TargetLowering object.
167 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
169 // X86 is weird, it always uses i8 for shift amounts and setcc results.
170 setBooleanContents(ZeroOrOneBooleanContent);
171 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 // For 64-bit since we have so many registers use the ILP scheduler, for
175 // 32-bit code use the register pressure specific scheduling.
176 // For Atom, always use ILP scheduling.
177 if (Subtarget->isAtom())
178 setSchedulingPreference(Sched::ILP);
179 else if (Subtarget->is64Bit())
180 setSchedulingPreference(Sched::ILP);
182 setSchedulingPreference(Sched::RegPressure);
183 setStackPointerRegisterToSaveRestore(X86StackPtr);
185 // Bypass i32 with i8 on Atom when compiling with O2
186 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187 addBypassSlowDivType(Type::getInt32Ty(getGlobalContext()), Type::getInt8Ty(getGlobalContext()));
189 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190 // Setup Windows compiler runtime calls.
191 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193 setLibcallName(RTLIB::SREM_I64, "_allrem");
194 setLibcallName(RTLIB::UREM_I64, "_aullrem");
195 setLibcallName(RTLIB::MUL_I64, "_allmul");
196 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
202 // The _ftol2 runtime function has an unusual calling conv, which
203 // is modeled by a special pseudo-instruction.
204 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
210 if (Subtarget->isTargetDarwin()) {
211 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212 setUseUnderscoreSetJmp(false);
213 setUseUnderscoreLongJmp(false);
214 } else if (Subtarget->isTargetMingw()) {
215 // MS runtime is weird: it exports _setjmp, but longjmp!
216 setUseUnderscoreSetJmp(true);
217 setUseUnderscoreLongJmp(false);
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(true);
223 // Set up the register classes.
224 addRegisterClass(MVT::i8, &X86::GR8RegClass);
225 addRegisterClass(MVT::i16, &X86::GR16RegClass);
226 addRegisterClass(MVT::i32, &X86::GR32RegClass);
227 if (Subtarget->is64Bit())
228 addRegisterClass(MVT::i64, &X86::GR64RegClass);
230 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
232 // We don't accept any truncstore of integer registers.
233 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
240 // SETOEQ and SETUNE require checking two conditions.
241 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
248 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
250 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
252 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
257 } else if (!TM.Options.UseSoftFloat) {
258 // We have an algorithm for SSE2->double, and we turn this into a
259 // 64-bit FILD followed by conditional FADD for other targets.
260 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
261 // We have an algorithm for SSE2, and we turn this into a 64-bit
262 // FILD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
266 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
268 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
269 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
271 if (!TM.Options.UseSoftFloat) {
272 // SSE has no i16 to fp conversion, only i32
273 if (X86ScalarSSEf32) {
274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
275 // f32 and f64 cases are Legal, f80 case is not
276 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
283 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
286 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
287 // are Legal, f80 is custom lowered.
288 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
289 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
291 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
293 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
294 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
296 if (X86ScalarSSEf32) {
297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
298 // f32 and f64 cases are Legal, f80 case is not
299 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
305 // Handle FP_TO_UINT by promoting the destination to a larger signed
307 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
309 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
311 if (Subtarget->is64Bit()) {
312 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
313 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
314 } else if (!TM.Options.UseSoftFloat) {
315 // Since AVX is a superset of SSE3, only check for SSE here.
316 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317 // Expand FP_TO_UINT into a select.
318 // FIXME: We would like to use a Custom expander here eventually to do
319 // the optimal thing for SSE vs. the default expansion in the legalizer.
320 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
322 // With SSE3 we can use fisttpll to convert to a signed i64; without
323 // SSE, we're stuck with a fistpll.
324 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
327 if (isTargetFTOL()) {
328 // Use the _ftol2 runtime function, which has a pseudo-instruction
329 // to handle its weird calling convention.
330 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
333 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334 if (!X86ScalarSSEf64) {
335 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
336 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
337 if (Subtarget->is64Bit()) {
338 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
339 // Without SSE, i64->f64 goes through memory.
340 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
344 // Scalar integer divide and remainder are lowered to use operations that
345 // produce two results, to match the available instructions. This exposes
346 // the two-result form to trivial CSE, which is able to combine x/y and x%y
347 // into a single instruction.
349 // Scalar integer multiply-high is also lowered to use two-result
350 // operations, to match the available instructions. However, plain multiply
351 // (low) operations are left as Legal, as there are single-result
352 // instructions for this in x86. Using the two-result multiply instructions
353 // when both high and low results are needed must be arranged by dagcombine.
354 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
356 setOperationAction(ISD::MULHS, VT, Expand);
357 setOperationAction(ISD::MULHU, VT, Expand);
358 setOperationAction(ISD::SDIV, VT, Expand);
359 setOperationAction(ISD::UDIV, VT, Expand);
360 setOperationAction(ISD::SREM, VT, Expand);
361 setOperationAction(ISD::UREM, VT, Expand);
363 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364 setOperationAction(ISD::ADDC, VT, Custom);
365 setOperationAction(ISD::ADDE, VT, Custom);
366 setOperationAction(ISD::SUBC, VT, Custom);
367 setOperationAction(ISD::SUBE, VT, Custom);
370 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
371 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
372 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
373 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
374 if (Subtarget->is64Bit())
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
378 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
379 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f32 , Expand);
381 setOperationAction(ISD::FREM , MVT::f64 , Expand);
382 setOperationAction(ISD::FREM , MVT::f80 , Expand);
383 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
385 // Promote the i8 variants and force them on up to i32 which has a shorter
387 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
388 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
390 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
391 if (Subtarget->hasBMI()) {
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
393 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
394 if (Subtarget->is64Bit())
395 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
397 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
398 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
399 if (Subtarget->is64Bit())
400 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
403 if (Subtarget->hasLZCNT()) {
404 // When promoting the i8 variants, force them to i32 for a shorter
406 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
407 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
409 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
411 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
412 if (Subtarget->is64Bit())
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
420 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
421 if (Subtarget->is64Bit()) {
422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
427 if (Subtarget->hasPOPCNT()) {
428 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
430 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
432 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
433 if (Subtarget->is64Bit())
434 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
437 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
438 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
440 // These should be promoted to a larger select which is supported.
441 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
442 // X86 wants to expand cmov itself.
443 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
445 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
448 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
451 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
454 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
457 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
459 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
462 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
463 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
464 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
465 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
466 if (Subtarget->is64Bit())
467 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
468 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
469 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
470 if (Subtarget->is64Bit()) {
471 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
472 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
473 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
474 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
475 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
477 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
478 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
479 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
480 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
481 if (Subtarget->is64Bit()) {
482 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
483 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
484 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
487 if (Subtarget->hasSSE1())
488 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
490 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
491 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
493 // On X86 and X86-64, atomic operations are lowered to locked instructions.
494 // Locked instructions, in turn, have implicit fence semantics (all memory
495 // operations are flushed before issuing the locked instruction, and they
496 // are not buffered), so we can fold away the common pattern of
497 // fence-atomic-fence.
498 setShouldFoldAtomicFences(true);
500 // Expand certain atomics
501 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
503 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
504 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
508 if (!Subtarget->is64Bit()) {
509 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
512 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
514 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
515 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
516 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
519 if (Subtarget->hasCmpxchg16b()) {
520 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
523 // FIXME - use subtarget debug flags
524 if (!Subtarget->isTargetDarwin() &&
525 !Subtarget->isTargetELF() &&
526 !Subtarget->isTargetCygMing()) {
527 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
530 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
531 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
532 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
533 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
534 if (Subtarget->is64Bit()) {
535 setExceptionPointerRegister(X86::RAX);
536 setExceptionSelectorRegister(X86::RDX);
538 setExceptionPointerRegister(X86::EAX);
539 setExceptionSelectorRegister(X86::EDX);
541 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
542 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
544 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
545 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
547 setOperationAction(ISD::TRAP, MVT::Other, Legal);
549 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
550 setOperationAction(ISD::VASTART , MVT::Other, Custom);
551 setOperationAction(ISD::VAEND , MVT::Other, Expand);
552 if (Subtarget->is64Bit()) {
553 setOperationAction(ISD::VAARG , MVT::Other, Custom);
554 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
556 setOperationAction(ISD::VAARG , MVT::Other, Expand);
557 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
560 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
561 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
563 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
564 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
565 MVT::i64 : MVT::i32, Custom);
566 else if (TM.Options.EnableSegmentedStacks)
567 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
568 MVT::i64 : MVT::i32, Custom);
570 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
571 MVT::i64 : MVT::i32, Expand);
573 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
574 // f32 and f64 use SSE.
575 // Set up the FP register classes.
576 addRegisterClass(MVT::f32, &X86::FR32RegClass);
577 addRegisterClass(MVT::f64, &X86::FR64RegClass);
579 // Use ANDPD to simulate FABS.
580 setOperationAction(ISD::FABS , MVT::f64, Custom);
581 setOperationAction(ISD::FABS , MVT::f32, Custom);
583 // Use XORP to simulate FNEG.
584 setOperationAction(ISD::FNEG , MVT::f64, Custom);
585 setOperationAction(ISD::FNEG , MVT::f32, Custom);
587 // Use ANDPD and ORPD to simulate FCOPYSIGN.
588 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
589 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
591 // Lower this to FGETSIGNx86 plus an AND.
592 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
593 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
595 // We don't support sin/cos/fmod
596 setOperationAction(ISD::FSIN , MVT::f64, Expand);
597 setOperationAction(ISD::FCOS , MVT::f64, Expand);
598 setOperationAction(ISD::FSIN , MVT::f32, Expand);
599 setOperationAction(ISD::FCOS , MVT::f32, Expand);
601 // Expand FP immediates into loads from the stack, except for the special
603 addLegalFPImmediate(APFloat(+0.0)); // xorpd
604 addLegalFPImmediate(APFloat(+0.0f)); // xorps
605 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
606 // Use SSE for f32, x87 for f64.
607 // Set up the FP register classes.
608 addRegisterClass(MVT::f32, &X86::FR32RegClass);
609 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
611 // Use ANDPS to simulate FABS.
612 setOperationAction(ISD::FABS , MVT::f32, Custom);
614 // Use XORP to simulate FNEG.
615 setOperationAction(ISD::FNEG , MVT::f32, Custom);
617 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
619 // Use ANDPS and ORPS to simulate FCOPYSIGN.
620 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
623 // We don't support sin/cos/fmod
624 setOperationAction(ISD::FSIN , MVT::f32, Expand);
625 setOperationAction(ISD::FCOS , MVT::f32, Expand);
627 // Special cases we handle for FP constants.
628 addLegalFPImmediate(APFloat(+0.0f)); // xorps
629 addLegalFPImmediate(APFloat(+0.0)); // FLD0
630 addLegalFPImmediate(APFloat(+1.0)); // FLD1
631 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
634 if (!TM.Options.UnsafeFPMath) {
635 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
636 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
638 } else if (!TM.Options.UseSoftFloat) {
639 // f32 and f64 in x87.
640 // Set up the FP register classes.
641 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
642 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
644 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
645 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
646 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
647 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
649 if (!TM.Options.UnsafeFPMath) {
650 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
651 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
653 addLegalFPImmediate(APFloat(+0.0)); // FLD0
654 addLegalFPImmediate(APFloat(+1.0)); // FLD1
655 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
656 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
657 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
658 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
659 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
660 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
663 // We don't support FMA.
664 setOperationAction(ISD::FMA, MVT::f64, Expand);
665 setOperationAction(ISD::FMA, MVT::f32, Expand);
667 // Long double always uses X87.
668 if (!TM.Options.UseSoftFloat) {
669 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
670 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
671 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
673 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
674 addLegalFPImmediate(TmpFlt); // FLD0
676 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
679 APFloat TmpFlt2(+1.0);
680 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
682 addLegalFPImmediate(TmpFlt2); // FLD1
683 TmpFlt2.changeSign();
684 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
687 if (!TM.Options.UnsafeFPMath) {
688 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
689 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
692 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
693 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
694 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
695 setOperationAction(ISD::FRINT, MVT::f80, Expand);
696 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
697 setOperationAction(ISD::FMA, MVT::f80, Expand);
700 // Always use a library call for pow.
701 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
702 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
703 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
705 setOperationAction(ISD::FLOG, MVT::f80, Expand);
706 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
707 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
708 setOperationAction(ISD::FEXP, MVT::f80, Expand);
709 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
711 // First set operation action for all vector types to either promote
712 // (for widening) or expand (for scalarization). Then we will selectively
713 // turn on ones that can be effectively codegen'd.
714 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
715 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
716 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
731 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
733 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
734 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
769 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
770 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
774 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
775 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
776 setTruncStoreAction((MVT::SimpleValueType)VT,
777 (MVT::SimpleValueType)InnerVT, Expand);
778 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
779 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
780 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
783 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
784 // with -msoft-float, disable use of MMX as well.
785 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
786 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
787 // No operations on x86mmx supported, everything uses intrinsics.
790 // MMX-sized vectors (other than x86mmx) are expected to be expanded
791 // into smaller operations.
792 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
793 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
794 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
795 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
796 setOperationAction(ISD::AND, MVT::v8i8, Expand);
797 setOperationAction(ISD::AND, MVT::v4i16, Expand);
798 setOperationAction(ISD::AND, MVT::v2i32, Expand);
799 setOperationAction(ISD::AND, MVT::v1i64, Expand);
800 setOperationAction(ISD::OR, MVT::v8i8, Expand);
801 setOperationAction(ISD::OR, MVT::v4i16, Expand);
802 setOperationAction(ISD::OR, MVT::v2i32, Expand);
803 setOperationAction(ISD::OR, MVT::v1i64, Expand);
804 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
805 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
806 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
807 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
808 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
809 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
810 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
811 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
812 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
813 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
814 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
815 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
816 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
817 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
818 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
819 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
820 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
822 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
823 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
825 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
826 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
827 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
828 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
829 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
830 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
831 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
832 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
833 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
834 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
835 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
838 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
839 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
841 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
842 // registers cannot be used even for integer operations.
843 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
844 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
845 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
846 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
848 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
849 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
850 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
851 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
852 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
853 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
854 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
855 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
856 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
857 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
858 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
859 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
860 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
861 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
862 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
863 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
865 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
866 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
867 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
868 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
870 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
871 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
872 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
873 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
874 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
876 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
877 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
878 MVT VT = (MVT::SimpleValueType)i;
879 // Do not attempt to custom lower non-power-of-2 vectors
880 if (!isPowerOf2_32(VT.getVectorNumElements()))
882 // Do not attempt to custom lower non-128-bit vectors
883 if (!VT.is128BitVector())
885 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
890 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
891 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
892 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
893 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
894 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
895 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
897 if (Subtarget->is64Bit()) {
898 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
899 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
902 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
903 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
904 MVT VT = (MVT::SimpleValueType)i;
906 // Do not attempt to promote non-128-bit vectors
907 if (!VT.is128BitVector())
910 setOperationAction(ISD::AND, VT, Promote);
911 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
912 setOperationAction(ISD::OR, VT, Promote);
913 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
914 setOperationAction(ISD::XOR, VT, Promote);
915 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
916 setOperationAction(ISD::LOAD, VT, Promote);
917 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
918 setOperationAction(ISD::SELECT, VT, Promote);
919 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
922 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
924 // Custom lower v2i64 and v2f64 selects.
925 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
926 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
927 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
928 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
930 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
931 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
934 if (Subtarget->hasSSE41()) {
935 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
936 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
937 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
938 setOperationAction(ISD::FRINT, MVT::f32, Legal);
939 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
940 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
941 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
942 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
943 setOperationAction(ISD::FRINT, MVT::f64, Legal);
944 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
946 // FIXME: Do we need to handle scalar-to-vector here?
947 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
949 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
950 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
951 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
952 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
953 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
955 // i8 and i16 vectors are custom , because the source register and source
956 // source memory operand types are not the same width. f32 vectors are
957 // custom since the immediate controlling the insert encodes additional
959 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
960 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
961 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
964 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
965 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
966 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
967 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
969 // FIXME: these should be Legal but thats only for the case where
970 // the index is constant. For now custom expand to deal with that.
971 if (Subtarget->is64Bit()) {
972 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
973 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
977 if (Subtarget->hasSSE2()) {
978 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
979 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
981 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
982 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
984 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
985 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
987 if (Subtarget->hasAVX2()) {
988 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
989 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
991 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
992 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
994 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
996 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
997 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
999 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1000 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1002 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1006 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1007 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1008 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1009 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1010 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1011 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1012 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1014 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1015 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1016 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1018 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1019 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1020 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1021 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1022 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1023 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1025 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1026 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1027 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1028 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1029 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1030 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1032 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1033 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1034 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1036 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1037 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1039 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1040 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1042 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1043 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1045 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1046 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1047 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1048 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1050 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1051 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1052 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1054 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1055 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1056 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1057 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1059 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1060 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1061 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1062 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1063 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1064 setOperationAction(ISD::FMA, MVT::f32, Custom);
1065 setOperationAction(ISD::FMA, MVT::f64, Custom);
1068 if (Subtarget->hasAVX2()) {
1069 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1070 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1071 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1072 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1074 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1075 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1076 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1077 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1079 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1080 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1081 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1082 // Don't lower v32i8 because there is no 128-bit byte mul
1084 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1086 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1087 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1089 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1090 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1092 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1094 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1095 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1096 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1097 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1099 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1100 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1101 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1102 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1104 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1105 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1106 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1107 // Don't lower v32i8 because there is no 128-bit byte mul
1109 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1110 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1112 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1113 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1115 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1118 // Custom lower several nodes for 256-bit types.
1119 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1120 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1121 MVT VT = (MVT::SimpleValueType)i;
1123 // Extract subvector is special because the value type
1124 // (result) is 128-bit but the source is 256-bit wide.
1125 if (VT.is128BitVector())
1126 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1128 // Do not attempt to custom lower other non-256-bit vectors
1129 if (!VT.is256BitVector())
1132 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1133 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1134 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1135 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1136 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1137 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1138 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1141 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1142 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1143 MVT VT = (MVT::SimpleValueType)i;
1145 // Do not attempt to promote non-256-bit vectors
1146 if (!VT.is256BitVector())
1149 setOperationAction(ISD::AND, VT, Promote);
1150 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1151 setOperationAction(ISD::OR, VT, Promote);
1152 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1153 setOperationAction(ISD::XOR, VT, Promote);
1154 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1155 setOperationAction(ISD::LOAD, VT, Promote);
1156 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1157 setOperationAction(ISD::SELECT, VT, Promote);
1158 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1162 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1163 // of this type with custom code.
1164 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1165 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1166 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1170 // We want to custom lower some of our intrinsics.
1171 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1172 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1175 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1176 // handle type legalization for these operations here.
1178 // FIXME: We really should do custom legalization for addition and
1179 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1180 // than generic legalization for 64-bit multiplication-with-overflow, though.
1181 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1182 // Add/Sub/Mul with overflow operations are custom lowered.
1184 setOperationAction(ISD::SADDO, VT, Custom);
1185 setOperationAction(ISD::UADDO, VT, Custom);
1186 setOperationAction(ISD::SSUBO, VT, Custom);
1187 setOperationAction(ISD::USUBO, VT, Custom);
1188 setOperationAction(ISD::SMULO, VT, Custom);
1189 setOperationAction(ISD::UMULO, VT, Custom);
1192 // There are no 8-bit 3-address imul/mul instructions
1193 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1194 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1196 if (!Subtarget->is64Bit()) {
1197 // These libcalls are not available in 32-bit.
1198 setLibcallName(RTLIB::SHL_I128, 0);
1199 setLibcallName(RTLIB::SRL_I128, 0);
1200 setLibcallName(RTLIB::SRA_I128, 0);
1203 // We have target-specific dag combine patterns for the following nodes:
1204 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1205 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1206 setTargetDAGCombine(ISD::VSELECT);
1207 setTargetDAGCombine(ISD::SELECT);
1208 setTargetDAGCombine(ISD::SHL);
1209 setTargetDAGCombine(ISD::SRA);
1210 setTargetDAGCombine(ISD::SRL);
1211 setTargetDAGCombine(ISD::OR);
1212 setTargetDAGCombine(ISD::AND);
1213 setTargetDAGCombine(ISD::ADD);
1214 setTargetDAGCombine(ISD::FADD);
1215 setTargetDAGCombine(ISD::FSUB);
1216 setTargetDAGCombine(ISD::FMA);
1217 setTargetDAGCombine(ISD::SUB);
1218 setTargetDAGCombine(ISD::LOAD);
1219 setTargetDAGCombine(ISD::STORE);
1220 setTargetDAGCombine(ISD::ZERO_EXTEND);
1221 setTargetDAGCombine(ISD::ANY_EXTEND);
1222 setTargetDAGCombine(ISD::SIGN_EXTEND);
1223 setTargetDAGCombine(ISD::TRUNCATE);
1224 setTargetDAGCombine(ISD::UINT_TO_FP);
1225 setTargetDAGCombine(ISD::SINT_TO_FP);
1226 setTargetDAGCombine(ISD::SETCC);
1227 setTargetDAGCombine(ISD::FP_TO_SINT);
1228 if (Subtarget->is64Bit())
1229 setTargetDAGCombine(ISD::MUL);
1230 setTargetDAGCombine(ISD::XOR);
1232 computeRegisterProperties();
1234 // On Darwin, -Os means optimize for size without hurting performance,
1235 // do not reduce the limit.
1236 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1237 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1238 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1239 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1240 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1241 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1242 setPrefLoopAlignment(4); // 2^4 bytes.
1243 benefitFromCodePlacementOpt = true;
1245 // Predictable cmov don't hurt on atom because it's in-order.
1246 predictableSelectIsExpensive = !Subtarget->isAtom();
1248 setPrefFunctionAlignment(4); // 2^4 bytes.
1252 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1253 if (!VT.isVector()) return MVT::i8;
1254 return VT.changeVectorElementTypeToInteger();
1258 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1259 /// the desired ByVal argument alignment.
1260 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1263 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1264 if (VTy->getBitWidth() == 128)
1266 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1267 unsigned EltAlign = 0;
1268 getMaxByValAlign(ATy->getElementType(), EltAlign);
1269 if (EltAlign > MaxAlign)
1270 MaxAlign = EltAlign;
1271 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1272 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1273 unsigned EltAlign = 0;
1274 getMaxByValAlign(STy->getElementType(i), EltAlign);
1275 if (EltAlign > MaxAlign)
1276 MaxAlign = EltAlign;
1283 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1284 /// function arguments in the caller parameter area. For X86, aggregates
1285 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1286 /// are at 4-byte boundaries.
1287 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1288 if (Subtarget->is64Bit()) {
1289 // Max of 8 and alignment of type.
1290 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1297 if (Subtarget->hasSSE1())
1298 getMaxByValAlign(Ty, Align);
1302 /// getOptimalMemOpType - Returns the target specific optimal type for load
1303 /// and store operations as a result of memset, memcpy, and memmove
1304 /// lowering. If DstAlign is zero that means it's safe to destination
1305 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1306 /// means there isn't a need to check it against alignment requirement,
1307 /// probably because the source does not need to be loaded. If
1308 /// 'IsZeroVal' is true, that means it's safe to return a
1309 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1310 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1311 /// constant so it does not need to be loaded.
1312 /// It returns EVT::Other if the type should be determined using generic
1313 /// target-independent logic.
1315 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1316 unsigned DstAlign, unsigned SrcAlign,
1319 MachineFunction &MF) const {
1320 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1321 // linux. This is because the stack realignment code can't handle certain
1322 // cases like PR2962. This should be removed when PR2962 is fixed.
1323 const Function *F = MF.getFunction();
1325 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1327 (Subtarget->isUnalignedMemAccessFast() ||
1328 ((DstAlign == 0 || DstAlign >= 16) &&
1329 (SrcAlign == 0 || SrcAlign >= 16))) &&
1330 Subtarget->getStackAlignment() >= 16) {
1331 if (Subtarget->getStackAlignment() >= 32) {
1332 if (Subtarget->hasAVX2())
1334 if (Subtarget->hasAVX())
1337 if (Subtarget->hasSSE2())
1339 if (Subtarget->hasSSE1())
1341 } else if (!MemcpyStrSrc && Size >= 8 &&
1342 !Subtarget->is64Bit() &&
1343 Subtarget->getStackAlignment() >= 8 &&
1344 Subtarget->hasSSE2()) {
1345 // Do not use f64 to lower memcpy if source is string constant. It's
1346 // better to use i32 to avoid the loads.
1350 if (Subtarget->is64Bit() && Size >= 8)
1355 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1356 /// current function. The returned value is a member of the
1357 /// MachineJumpTableInfo::JTEntryKind enum.
1358 unsigned X86TargetLowering::getJumpTableEncoding() const {
1359 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1361 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1362 Subtarget->isPICStyleGOT())
1363 return MachineJumpTableInfo::EK_Custom32;
1365 // Otherwise, use the normal jump table encoding heuristics.
1366 return TargetLowering::getJumpTableEncoding();
1370 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1371 const MachineBasicBlock *MBB,
1372 unsigned uid,MCContext &Ctx) const{
1373 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1374 Subtarget->isPICStyleGOT());
1375 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1377 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1378 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1381 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1383 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1384 SelectionDAG &DAG) const {
1385 if (!Subtarget->is64Bit())
1386 // This doesn't have DebugLoc associated with it, but is not really the
1387 // same as a Register.
1388 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1392 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1393 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1395 const MCExpr *X86TargetLowering::
1396 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1397 MCContext &Ctx) const {
1398 // X86-64 uses RIP relative addressing based on the jump table label.
1399 if (Subtarget->isPICStyleRIPRel())
1400 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1402 // Otherwise, the reference is relative to the PIC base.
1403 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1406 // FIXME: Why this routine is here? Move to RegInfo!
1407 std::pair<const TargetRegisterClass*, uint8_t>
1408 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1409 const TargetRegisterClass *RRC = 0;
1411 switch (VT.getSimpleVT().SimpleTy) {
1413 return TargetLowering::findRepresentativeClass(VT);
1414 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1415 RRC = Subtarget->is64Bit() ?
1416 (const TargetRegisterClass*)&X86::GR64RegClass :
1417 (const TargetRegisterClass*)&X86::GR32RegClass;
1420 RRC = &X86::VR64RegClass;
1422 case MVT::f32: case MVT::f64:
1423 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1424 case MVT::v4f32: case MVT::v2f64:
1425 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1427 RRC = &X86::VR128RegClass;
1430 return std::make_pair(RRC, Cost);
1433 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1434 unsigned &Offset) const {
1435 if (!Subtarget->isTargetLinux())
1438 if (Subtarget->is64Bit()) {
1439 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1441 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1454 //===----------------------------------------------------------------------===//
1455 // Return Value Calling Convention Implementation
1456 //===----------------------------------------------------------------------===//
1458 #include "X86GenCallingConv.inc"
1461 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1462 MachineFunction &MF, bool isVarArg,
1463 const SmallVectorImpl<ISD::OutputArg> &Outs,
1464 LLVMContext &Context) const {
1465 SmallVector<CCValAssign, 16> RVLocs;
1466 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1468 return CCInfo.CheckReturn(Outs, RetCC_X86);
1472 X86TargetLowering::LowerReturn(SDValue Chain,
1473 CallingConv::ID CallConv, bool isVarArg,
1474 const SmallVectorImpl<ISD::OutputArg> &Outs,
1475 const SmallVectorImpl<SDValue> &OutVals,
1476 DebugLoc dl, SelectionDAG &DAG) const {
1477 MachineFunction &MF = DAG.getMachineFunction();
1478 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1480 SmallVector<CCValAssign, 16> RVLocs;
1481 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1482 RVLocs, *DAG.getContext());
1483 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1485 // Add the regs to the liveout set for the function.
1486 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1487 for (unsigned i = 0; i != RVLocs.size(); ++i)
1488 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1489 MRI.addLiveOut(RVLocs[i].getLocReg());
1493 SmallVector<SDValue, 6> RetOps;
1494 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1495 // Operand #1 = Bytes To Pop
1496 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1499 // Copy the result values into the output registers.
1500 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1501 CCValAssign &VA = RVLocs[i];
1502 assert(VA.isRegLoc() && "Can only return in registers!");
1503 SDValue ValToCopy = OutVals[i];
1504 EVT ValVT = ValToCopy.getValueType();
1506 // Promote values to the appropriate types
1507 if (VA.getLocInfo() == CCValAssign::SExt)
1508 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1509 else if (VA.getLocInfo() == CCValAssign::ZExt)
1510 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1511 else if (VA.getLocInfo() == CCValAssign::AExt)
1512 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1513 else if (VA.getLocInfo() == CCValAssign::BCvt)
1514 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1516 // If this is x86-64, and we disabled SSE, we can't return FP values,
1517 // or SSE or MMX vectors.
1518 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1519 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1520 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1521 report_fatal_error("SSE register return with SSE disabled");
1523 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1524 // llvm-gcc has never done it right and no one has noticed, so this
1525 // should be OK for now.
1526 if (ValVT == MVT::f64 &&
1527 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1528 report_fatal_error("SSE2 register return with SSE2 disabled");
1530 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1531 // the RET instruction and handled by the FP Stackifier.
1532 if (VA.getLocReg() == X86::ST0 ||
1533 VA.getLocReg() == X86::ST1) {
1534 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1535 // change the value to the FP stack register class.
1536 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1537 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1538 RetOps.push_back(ValToCopy);
1539 // Don't emit a copytoreg.
1543 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1544 // which is returned in RAX / RDX.
1545 if (Subtarget->is64Bit()) {
1546 if (ValVT == MVT::x86mmx) {
1547 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1548 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1549 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1551 // If we don't have SSE2 available, convert to v4f32 so the generated
1552 // register is legal.
1553 if (!Subtarget->hasSSE2())
1554 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1559 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1560 Flag = Chain.getValue(1);
1563 // The x86-64 ABI for returning structs by value requires that we copy
1564 // the sret argument into %rax for the return. We saved the argument into
1565 // a virtual register in the entry block, so now we copy the value out
1567 if (Subtarget->is64Bit() &&
1568 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1569 MachineFunction &MF = DAG.getMachineFunction();
1570 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1571 unsigned Reg = FuncInfo->getSRetReturnReg();
1573 "SRetReturnReg should have been set in LowerFormalArguments().");
1574 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1576 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1577 Flag = Chain.getValue(1);
1579 // RAX now acts like a return value.
1580 MRI.addLiveOut(X86::RAX);
1583 RetOps[0] = Chain; // Update chain.
1585 // Add the flag if we have it.
1587 RetOps.push_back(Flag);
1589 return DAG.getNode(X86ISD::RET_FLAG, dl,
1590 MVT::Other, &RetOps[0], RetOps.size());
1593 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1594 if (N->getNumValues() != 1)
1596 if (!N->hasNUsesOfValue(1, 0))
1599 SDValue TCChain = Chain;
1600 SDNode *Copy = *N->use_begin();
1601 if (Copy->getOpcode() == ISD::CopyToReg) {
1602 // If the copy has a glue operand, we conservatively assume it isn't safe to
1603 // perform a tail call.
1604 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1606 TCChain = Copy->getOperand(0);
1607 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1610 bool HasRet = false;
1611 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1613 if (UI->getOpcode() != X86ISD::RET_FLAG)
1626 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1627 ISD::NodeType ExtendKind) const {
1629 // TODO: Is this also valid on 32-bit?
1630 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1631 ReturnMVT = MVT::i8;
1633 ReturnMVT = MVT::i32;
1635 EVT MinVT = getRegisterType(Context, ReturnMVT);
1636 return VT.bitsLT(MinVT) ? MinVT : VT;
1639 /// LowerCallResult - Lower the result values of a call into the
1640 /// appropriate copies out of appropriate physical registers.
1643 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1644 CallingConv::ID CallConv, bool isVarArg,
1645 const SmallVectorImpl<ISD::InputArg> &Ins,
1646 DebugLoc dl, SelectionDAG &DAG,
1647 SmallVectorImpl<SDValue> &InVals) const {
1649 // Assign locations to each value returned by this call.
1650 SmallVector<CCValAssign, 16> RVLocs;
1651 bool Is64Bit = Subtarget->is64Bit();
1652 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1653 getTargetMachine(), RVLocs, *DAG.getContext());
1654 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1656 // Copy all of the result registers out of their specified physreg.
1657 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1658 CCValAssign &VA = RVLocs[i];
1659 EVT CopyVT = VA.getValVT();
1661 // If this is x86-64, and we disabled SSE, we can't return FP values
1662 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1663 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1664 report_fatal_error("SSE register return with SSE disabled");
1669 // If this is a call to a function that returns an fp value on the floating
1670 // point stack, we must guarantee the value is popped from the stack, so
1671 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1672 // if the return value is not used. We use the FpPOP_RETVAL instruction
1674 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1675 // If we prefer to use the value in xmm registers, copy it out as f80 and
1676 // use a truncate to move it from fp stack reg to xmm reg.
1677 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1678 SDValue Ops[] = { Chain, InFlag };
1679 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1680 MVT::Other, MVT::Glue, Ops, 2), 1);
1681 Val = Chain.getValue(0);
1683 // Round the f80 to the right size, which also moves it to the appropriate
1685 if (CopyVT != VA.getValVT())
1686 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1687 // This truncation won't change the value.
1688 DAG.getIntPtrConstant(1));
1690 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1691 CopyVT, InFlag).getValue(1);
1692 Val = Chain.getValue(0);
1694 InFlag = Chain.getValue(2);
1695 InVals.push_back(Val);
1702 //===----------------------------------------------------------------------===//
1703 // C & StdCall & Fast Calling Convention implementation
1704 //===----------------------------------------------------------------------===//
1705 // StdCall calling convention seems to be standard for many Windows' API
1706 // routines and around. It differs from C calling convention just a little:
1707 // callee should clean up the stack, not caller. Symbols should be also
1708 // decorated in some fancy way :) It doesn't support any vector arguments.
1709 // For info on fast calling convention see Fast Calling Convention (tail call)
1710 // implementation LowerX86_32FastCCCallTo.
1712 /// CallIsStructReturn - Determines whether a call uses struct return
1714 enum StructReturnType {
1719 static StructReturnType
1720 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1722 return NotStructReturn;
1724 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1725 if (!Flags.isSRet())
1726 return NotStructReturn;
1727 if (Flags.isInReg())
1728 return RegStructReturn;
1729 return StackStructReturn;
1732 /// ArgsAreStructReturn - Determines whether a function uses struct
1733 /// return semantics.
1734 static StructReturnType
1735 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1737 return NotStructReturn;
1739 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1740 if (!Flags.isSRet())
1741 return NotStructReturn;
1742 if (Flags.isInReg())
1743 return RegStructReturn;
1744 return StackStructReturn;
1747 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1748 /// by "Src" to address "Dst" with size and alignment information specified by
1749 /// the specific parameter attribute. The copy will be passed as a byval
1750 /// function parameter.
1752 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1753 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1755 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1757 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1758 /*isVolatile*/false, /*AlwaysInline=*/true,
1759 MachinePointerInfo(), MachinePointerInfo());
1762 /// IsTailCallConvention - Return true if the calling convention is one that
1763 /// supports tail call optimization.
1764 static bool IsTailCallConvention(CallingConv::ID CC) {
1765 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1768 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1769 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1773 CallingConv::ID CalleeCC = CS.getCallingConv();
1774 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1780 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1781 /// a tailcall target by changing its ABI.
1782 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1783 bool GuaranteedTailCallOpt) {
1784 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1788 X86TargetLowering::LowerMemArgument(SDValue Chain,
1789 CallingConv::ID CallConv,
1790 const SmallVectorImpl<ISD::InputArg> &Ins,
1791 DebugLoc dl, SelectionDAG &DAG,
1792 const CCValAssign &VA,
1793 MachineFrameInfo *MFI,
1795 // Create the nodes corresponding to a load from this parameter slot.
1796 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1797 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1798 getTargetMachine().Options.GuaranteedTailCallOpt);
1799 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1802 // If value is passed by pointer we have address passed instead of the value
1804 if (VA.getLocInfo() == CCValAssign::Indirect)
1805 ValVT = VA.getLocVT();
1807 ValVT = VA.getValVT();
1809 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1810 // changed with more analysis.
1811 // In case of tail call optimization mark all arguments mutable. Since they
1812 // could be overwritten by lowering of arguments in case of a tail call.
1813 if (Flags.isByVal()) {
1814 unsigned Bytes = Flags.getByValSize();
1815 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1816 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1817 return DAG.getFrameIndex(FI, getPointerTy());
1819 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1820 VA.getLocMemOffset(), isImmutable);
1821 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1822 return DAG.getLoad(ValVT, dl, Chain, FIN,
1823 MachinePointerInfo::getFixedStack(FI),
1824 false, false, false, 0);
1829 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1830 CallingConv::ID CallConv,
1832 const SmallVectorImpl<ISD::InputArg> &Ins,
1835 SmallVectorImpl<SDValue> &InVals)
1837 MachineFunction &MF = DAG.getMachineFunction();
1838 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1840 const Function* Fn = MF.getFunction();
1841 if (Fn->hasExternalLinkage() &&
1842 Subtarget->isTargetCygMing() &&
1843 Fn->getName() == "main")
1844 FuncInfo->setForceFramePointer(true);
1846 MachineFrameInfo *MFI = MF.getFrameInfo();
1847 bool Is64Bit = Subtarget->is64Bit();
1848 bool IsWindows = Subtarget->isTargetWindows();
1849 bool IsWin64 = Subtarget->isTargetWin64();
1851 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1852 "Var args not supported with calling convention fastcc or ghc");
1854 // Assign locations to all of the incoming arguments.
1855 SmallVector<CCValAssign, 16> ArgLocs;
1856 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1857 ArgLocs, *DAG.getContext());
1859 // Allocate shadow area for Win64
1861 CCInfo.AllocateStack(32, 8);
1864 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1866 unsigned LastVal = ~0U;
1868 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1869 CCValAssign &VA = ArgLocs[i];
1870 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1872 assert(VA.getValNo() != LastVal &&
1873 "Don't support value assigned to multiple locs yet");
1875 LastVal = VA.getValNo();
1877 if (VA.isRegLoc()) {
1878 EVT RegVT = VA.getLocVT();
1879 const TargetRegisterClass *RC;
1880 if (RegVT == MVT::i32)
1881 RC = &X86::GR32RegClass;
1882 else if (Is64Bit && RegVT == MVT::i64)
1883 RC = &X86::GR64RegClass;
1884 else if (RegVT == MVT::f32)
1885 RC = &X86::FR32RegClass;
1886 else if (RegVT == MVT::f64)
1887 RC = &X86::FR64RegClass;
1888 else if (RegVT.is256BitVector())
1889 RC = &X86::VR256RegClass;
1890 else if (RegVT.is128BitVector())
1891 RC = &X86::VR128RegClass;
1892 else if (RegVT == MVT::x86mmx)
1893 RC = &X86::VR64RegClass;
1895 llvm_unreachable("Unknown argument type!");
1897 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1898 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1900 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1901 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1903 if (VA.getLocInfo() == CCValAssign::SExt)
1904 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1905 DAG.getValueType(VA.getValVT()));
1906 else if (VA.getLocInfo() == CCValAssign::ZExt)
1907 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1908 DAG.getValueType(VA.getValVT()));
1909 else if (VA.getLocInfo() == CCValAssign::BCvt)
1910 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1912 if (VA.isExtInLoc()) {
1913 // Handle MMX values passed in XMM regs.
1914 if (RegVT.isVector()) {
1915 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1918 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1921 assert(VA.isMemLoc());
1922 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1925 // If value is passed via pointer - do a load.
1926 if (VA.getLocInfo() == CCValAssign::Indirect)
1927 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1928 MachinePointerInfo(), false, false, false, 0);
1930 InVals.push_back(ArgValue);
1933 // The x86-64 ABI for returning structs by value requires that we copy
1934 // the sret argument into %rax for the return. Save the argument into
1935 // a virtual register so that we can access it from the return points.
1936 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1937 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1938 unsigned Reg = FuncInfo->getSRetReturnReg();
1940 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1941 FuncInfo->setSRetReturnReg(Reg);
1943 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1944 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1947 unsigned StackSize = CCInfo.getNextStackOffset();
1948 // Align stack specially for tail calls.
1949 if (FuncIsMadeTailCallSafe(CallConv,
1950 MF.getTarget().Options.GuaranteedTailCallOpt))
1951 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1953 // If the function takes variable number of arguments, make a frame index for
1954 // the start of the first vararg value... for expansion of llvm.va_start.
1956 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1957 CallConv != CallingConv::X86_ThisCall)) {
1958 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1961 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1963 // FIXME: We should really autogenerate these arrays
1964 static const uint16_t GPR64ArgRegsWin64[] = {
1965 X86::RCX, X86::RDX, X86::R8, X86::R9
1967 static const uint16_t GPR64ArgRegs64Bit[] = {
1968 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1970 static const uint16_t XMMArgRegs64Bit[] = {
1971 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1972 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1974 const uint16_t *GPR64ArgRegs;
1975 unsigned NumXMMRegs = 0;
1978 // The XMM registers which might contain var arg parameters are shadowed
1979 // in their paired GPR. So we only need to save the GPR to their home
1981 TotalNumIntRegs = 4;
1982 GPR64ArgRegs = GPR64ArgRegsWin64;
1984 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1985 GPR64ArgRegs = GPR64ArgRegs64Bit;
1987 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1990 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1993 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1994 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1995 "SSE register cannot be used when SSE is disabled!");
1996 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1997 NoImplicitFloatOps) &&
1998 "SSE register cannot be used when SSE is disabled!");
1999 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2000 !Subtarget->hasSSE1())
2001 // Kernel mode asks for SSE to be disabled, so don't push them
2003 TotalNumXMMRegs = 0;
2006 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2007 // Get to the caller-allocated home save location. Add 8 to account
2008 // for the return address.
2009 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2010 FuncInfo->setRegSaveFrameIndex(
2011 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2012 // Fixup to set vararg frame on shadow area (4 x i64).
2014 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2016 // For X86-64, if there are vararg parameters that are passed via
2017 // registers, then we must store them to their spots on the stack so
2018 // they may be loaded by deferencing the result of va_next.
2019 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2020 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2021 FuncInfo->setRegSaveFrameIndex(
2022 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2026 // Store the integer parameter registers.
2027 SmallVector<SDValue, 8> MemOps;
2028 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2030 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2031 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2032 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2033 DAG.getIntPtrConstant(Offset));
2034 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2035 &X86::GR64RegClass);
2036 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2038 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2039 MachinePointerInfo::getFixedStack(
2040 FuncInfo->getRegSaveFrameIndex(), Offset),
2042 MemOps.push_back(Store);
2046 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2047 // Now store the XMM (fp + vector) parameter registers.
2048 SmallVector<SDValue, 11> SaveXMMOps;
2049 SaveXMMOps.push_back(Chain);
2051 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2052 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2053 SaveXMMOps.push_back(ALVal);
2055 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2056 FuncInfo->getRegSaveFrameIndex()));
2057 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2058 FuncInfo->getVarArgsFPOffset()));
2060 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2061 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2062 &X86::VR128RegClass);
2063 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2064 SaveXMMOps.push_back(Val);
2066 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2068 &SaveXMMOps[0], SaveXMMOps.size()));
2071 if (!MemOps.empty())
2072 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2073 &MemOps[0], MemOps.size());
2077 // Some CCs need callee pop.
2078 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2079 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2080 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2082 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2083 // If this is an sret function, the return should pop the hidden pointer.
2084 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2085 argsAreStructReturn(Ins) == StackStructReturn)
2086 FuncInfo->setBytesToPopOnReturn(4);
2090 // RegSaveFrameIndex is X86-64 only.
2091 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2092 if (CallConv == CallingConv::X86_FastCall ||
2093 CallConv == CallingConv::X86_ThisCall)
2094 // fastcc functions can't have varargs.
2095 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2098 FuncInfo->setArgumentStackSize(StackSize);
2104 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2105 SDValue StackPtr, SDValue Arg,
2106 DebugLoc dl, SelectionDAG &DAG,
2107 const CCValAssign &VA,
2108 ISD::ArgFlagsTy Flags) const {
2109 unsigned LocMemOffset = VA.getLocMemOffset();
2110 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2111 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2112 if (Flags.isByVal())
2113 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2115 return DAG.getStore(Chain, dl, Arg, PtrOff,
2116 MachinePointerInfo::getStack(LocMemOffset),
2120 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2121 /// optimization is performed and it is required.
2123 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2124 SDValue &OutRetAddr, SDValue Chain,
2125 bool IsTailCall, bool Is64Bit,
2126 int FPDiff, DebugLoc dl) const {
2127 // Adjust the Return address stack slot.
2128 EVT VT = getPointerTy();
2129 OutRetAddr = getReturnAddressFrameIndex(DAG);
2131 // Load the "old" Return address.
2132 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2133 false, false, false, 0);
2134 return SDValue(OutRetAddr.getNode(), 1);
2137 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2138 /// optimization is performed and it is required (FPDiff!=0).
2140 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2141 SDValue Chain, SDValue RetAddrFrIdx,
2142 bool Is64Bit, int FPDiff, DebugLoc dl) {
2143 // Store the return address to the appropriate stack slot.
2144 if (!FPDiff) return Chain;
2145 // Calculate the new stack slot for the return address.
2146 int SlotSize = Is64Bit ? 8 : 4;
2147 int NewReturnAddrFI =
2148 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2149 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2150 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2151 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2152 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2158 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2159 SmallVectorImpl<SDValue> &InVals) const {
2160 SelectionDAG &DAG = CLI.DAG;
2161 DebugLoc &dl = CLI.DL;
2162 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2163 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2164 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2165 SDValue Chain = CLI.Chain;
2166 SDValue Callee = CLI.Callee;
2167 CallingConv::ID CallConv = CLI.CallConv;
2168 bool &isTailCall = CLI.IsTailCall;
2169 bool isVarArg = CLI.IsVarArg;
2171 MachineFunction &MF = DAG.getMachineFunction();
2172 bool Is64Bit = Subtarget->is64Bit();
2173 bool IsWin64 = Subtarget->isTargetWin64();
2174 bool IsWindows = Subtarget->isTargetWindows();
2175 StructReturnType SR = callIsStructReturn(Outs);
2176 bool IsSibcall = false;
2178 if (MF.getTarget().Options.DisableTailCalls)
2182 // Check if it's really possible to do a tail call.
2183 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2184 isVarArg, SR != NotStructReturn,
2185 MF.getFunction()->hasStructRetAttr(),
2186 Outs, OutVals, Ins, DAG);
2188 // Sibcalls are automatically detected tailcalls which do not require
2190 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2197 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2198 "Var args not supported with calling convention fastcc or ghc");
2200 // Analyze operands of the call, assigning locations to each operand.
2201 SmallVector<CCValAssign, 16> ArgLocs;
2202 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2203 ArgLocs, *DAG.getContext());
2205 // Allocate shadow area for Win64
2207 CCInfo.AllocateStack(32, 8);
2210 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2212 // Get a count of how many bytes are to be pushed on the stack.
2213 unsigned NumBytes = CCInfo.getNextStackOffset();
2215 // This is a sibcall. The memory operands are available in caller's
2216 // own caller's stack.
2218 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2219 IsTailCallConvention(CallConv))
2220 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2223 if (isTailCall && !IsSibcall) {
2224 // Lower arguments at fp - stackoffset + fpdiff.
2225 unsigned NumBytesCallerPushed =
2226 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2227 FPDiff = NumBytesCallerPushed - NumBytes;
2229 // Set the delta of movement of the returnaddr stackslot.
2230 // But only set if delta is greater than previous delta.
2231 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2232 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2236 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2238 SDValue RetAddrFrIdx;
2239 // Load return address for tail calls.
2240 if (isTailCall && FPDiff)
2241 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2242 Is64Bit, FPDiff, dl);
2244 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2245 SmallVector<SDValue, 8> MemOpChains;
2248 // Walk the register/memloc assignments, inserting copies/loads. In the case
2249 // of tail call optimization arguments are handle later.
2250 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2251 CCValAssign &VA = ArgLocs[i];
2252 EVT RegVT = VA.getLocVT();
2253 SDValue Arg = OutVals[i];
2254 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2255 bool isByVal = Flags.isByVal();
2257 // Promote the value if needed.
2258 switch (VA.getLocInfo()) {
2259 default: llvm_unreachable("Unknown loc info!");
2260 case CCValAssign::Full: break;
2261 case CCValAssign::SExt:
2262 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2264 case CCValAssign::ZExt:
2265 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2267 case CCValAssign::AExt:
2268 if (RegVT.is128BitVector()) {
2269 // Special case: passing MMX values in XMM registers.
2270 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2271 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2272 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2274 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2276 case CCValAssign::BCvt:
2277 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2279 case CCValAssign::Indirect: {
2280 // Store the argument.
2281 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2282 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2283 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2284 MachinePointerInfo::getFixedStack(FI),
2291 if (VA.isRegLoc()) {
2292 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2293 if (isVarArg && IsWin64) {
2294 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2295 // shadow reg if callee is a varargs function.
2296 unsigned ShadowReg = 0;
2297 switch (VA.getLocReg()) {
2298 case X86::XMM0: ShadowReg = X86::RCX; break;
2299 case X86::XMM1: ShadowReg = X86::RDX; break;
2300 case X86::XMM2: ShadowReg = X86::R8; break;
2301 case X86::XMM3: ShadowReg = X86::R9; break;
2304 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2306 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2307 assert(VA.isMemLoc());
2308 if (StackPtr.getNode() == 0)
2309 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2310 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2311 dl, DAG, VA, Flags));
2315 if (!MemOpChains.empty())
2316 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2317 &MemOpChains[0], MemOpChains.size());
2319 if (Subtarget->isPICStyleGOT()) {
2320 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2323 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2324 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2326 // If we are tail calling and generating PIC/GOT style code load the
2327 // address of the callee into ECX. The value in ecx is used as target of
2328 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2329 // for tail calls on PIC/GOT architectures. Normally we would just put the
2330 // address of GOT into ebx and then call target@PLT. But for tail calls
2331 // ebx would be restored (since ebx is callee saved) before jumping to the
2334 // Note: The actual moving to ECX is done further down.
2335 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2336 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2337 !G->getGlobal()->hasProtectedVisibility())
2338 Callee = LowerGlobalAddress(Callee, DAG);
2339 else if (isa<ExternalSymbolSDNode>(Callee))
2340 Callee = LowerExternalSymbol(Callee, DAG);
2344 if (Is64Bit && isVarArg && !IsWin64) {
2345 // From AMD64 ABI document:
2346 // For calls that may call functions that use varargs or stdargs
2347 // (prototype-less calls or calls to functions containing ellipsis (...) in
2348 // the declaration) %al is used as hidden argument to specify the number
2349 // of SSE registers used. The contents of %al do not need to match exactly
2350 // the number of registers, but must be an ubound on the number of SSE
2351 // registers used and is in the range 0 - 8 inclusive.
2353 // Count the number of XMM registers allocated.
2354 static const uint16_t XMMArgRegs[] = {
2355 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2356 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2358 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2359 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2360 && "SSE registers cannot be used when SSE is disabled");
2362 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2363 DAG.getConstant(NumXMMRegs, MVT::i8)));
2366 // For tail calls lower the arguments to the 'real' stack slot.
2368 // Force all the incoming stack arguments to be loaded from the stack
2369 // before any new outgoing arguments are stored to the stack, because the
2370 // outgoing stack slots may alias the incoming argument stack slots, and
2371 // the alias isn't otherwise explicit. This is slightly more conservative
2372 // than necessary, because it means that each store effectively depends
2373 // on every argument instead of just those arguments it would clobber.
2374 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2376 SmallVector<SDValue, 8> MemOpChains2;
2379 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2380 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381 CCValAssign &VA = ArgLocs[i];
2384 assert(VA.isMemLoc());
2385 SDValue Arg = OutVals[i];
2386 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2387 // Create frame index.
2388 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2389 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2390 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2391 FIN = DAG.getFrameIndex(FI, getPointerTy());
2393 if (Flags.isByVal()) {
2394 // Copy relative to framepointer.
2395 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2396 if (StackPtr.getNode() == 0)
2397 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2399 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2401 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2405 // Store relative to framepointer.
2406 MemOpChains2.push_back(
2407 DAG.getStore(ArgChain, dl, Arg, FIN,
2408 MachinePointerInfo::getFixedStack(FI),
2414 if (!MemOpChains2.empty())
2415 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2416 &MemOpChains2[0], MemOpChains2.size());
2418 // Store the return address to the appropriate stack slot.
2419 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2423 // Build a sequence of copy-to-reg nodes chained together with token chain
2424 // and flag operands which copy the outgoing args into registers.
2426 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2427 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2428 RegsToPass[i].second, InFlag);
2429 InFlag = Chain.getValue(1);
2432 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2433 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2434 // In the 64-bit large code model, we have to make all calls
2435 // through a register, since the call instruction's 32-bit
2436 // pc-relative offset may not be large enough to hold the whole
2438 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2439 // If the callee is a GlobalAddress node (quite common, every direct call
2440 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2443 // We should use extra load for direct calls to dllimported functions in
2445 const GlobalValue *GV = G->getGlobal();
2446 if (!GV->hasDLLImportLinkage()) {
2447 unsigned char OpFlags = 0;
2448 bool ExtraLoad = false;
2449 unsigned WrapperKind = ISD::DELETED_NODE;
2451 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2452 // external symbols most go through the PLT in PIC mode. If the symbol
2453 // has hidden or protected visibility, or if it is static or local, then
2454 // we don't need to use the PLT - we can directly call it.
2455 if (Subtarget->isTargetELF() &&
2456 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2457 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2458 OpFlags = X86II::MO_PLT;
2459 } else if (Subtarget->isPICStyleStubAny() &&
2460 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2461 (!Subtarget->getTargetTriple().isMacOSX() ||
2462 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2463 // PC-relative references to external symbols should go through $stub,
2464 // unless we're building with the leopard linker or later, which
2465 // automatically synthesizes these stubs.
2466 OpFlags = X86II::MO_DARWIN_STUB;
2467 } else if (Subtarget->isPICStyleRIPRel() &&
2468 isa<Function>(GV) &&
2469 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2470 // If the function is marked as non-lazy, generate an indirect call
2471 // which loads from the GOT directly. This avoids runtime overhead
2472 // at the cost of eager binding (and one extra byte of encoding).
2473 OpFlags = X86II::MO_GOTPCREL;
2474 WrapperKind = X86ISD::WrapperRIP;
2478 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2479 G->getOffset(), OpFlags);
2481 // Add a wrapper if needed.
2482 if (WrapperKind != ISD::DELETED_NODE)
2483 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2484 // Add extra indirection if needed.
2486 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2487 MachinePointerInfo::getGOT(),
2488 false, false, false, 0);
2490 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2491 unsigned char OpFlags = 0;
2493 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2494 // external symbols should go through the PLT.
2495 if (Subtarget->isTargetELF() &&
2496 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2497 OpFlags = X86II::MO_PLT;
2498 } else if (Subtarget->isPICStyleStubAny() &&
2499 (!Subtarget->getTargetTriple().isMacOSX() ||
2500 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2501 // PC-relative references to external symbols should go through $stub,
2502 // unless we're building with the leopard linker or later, which
2503 // automatically synthesizes these stubs.
2504 OpFlags = X86II::MO_DARWIN_STUB;
2507 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2511 // Returns a chain & a flag for retval copy to use.
2512 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2513 SmallVector<SDValue, 8> Ops;
2515 if (!IsSibcall && isTailCall) {
2516 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2517 DAG.getIntPtrConstant(0, true), InFlag);
2518 InFlag = Chain.getValue(1);
2521 Ops.push_back(Chain);
2522 Ops.push_back(Callee);
2525 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2527 // Add argument registers to the end of the list so that they are known live
2529 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2530 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2531 RegsToPass[i].second.getValueType()));
2533 // Add a register mask operand representing the call-preserved registers.
2534 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2535 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2536 assert(Mask && "Missing call preserved mask for calling convention");
2537 Ops.push_back(DAG.getRegisterMask(Mask));
2539 if (InFlag.getNode())
2540 Ops.push_back(InFlag);
2544 //// If this is the first return lowered for this function, add the regs
2545 //// to the liveout set for the function.
2546 // This isn't right, although it's probably harmless on x86; liveouts
2547 // should be computed from returns not tail calls. Consider a void
2548 // function making a tail call to a function returning int.
2549 return DAG.getNode(X86ISD::TC_RETURN, dl,
2550 NodeTys, &Ops[0], Ops.size());
2553 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2554 InFlag = Chain.getValue(1);
2556 // Create the CALLSEQ_END node.
2557 unsigned NumBytesForCalleeToPush;
2558 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2559 getTargetMachine().Options.GuaranteedTailCallOpt))
2560 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2561 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2562 SR == StackStructReturn)
2563 // If this is a call to a struct-return function, the callee
2564 // pops the hidden struct pointer, so we have to push it back.
2565 // This is common for Darwin/X86, Linux & Mingw32 targets.
2566 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2567 NumBytesForCalleeToPush = 4;
2569 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2571 // Returns a flag for retval copy to use.
2573 Chain = DAG.getCALLSEQ_END(Chain,
2574 DAG.getIntPtrConstant(NumBytes, true),
2575 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2578 InFlag = Chain.getValue(1);
2581 // Handle result values, copying them out of physregs into vregs that we
2583 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2584 Ins, dl, DAG, InVals);
2588 //===----------------------------------------------------------------------===//
2589 // Fast Calling Convention (tail call) implementation
2590 //===----------------------------------------------------------------------===//
2592 // Like std call, callee cleans arguments, convention except that ECX is
2593 // reserved for storing the tail called function address. Only 2 registers are
2594 // free for argument passing (inreg). Tail call optimization is performed
2596 // * tailcallopt is enabled
2597 // * caller/callee are fastcc
2598 // On X86_64 architecture with GOT-style position independent code only local
2599 // (within module) calls are supported at the moment.
2600 // To keep the stack aligned according to platform abi the function
2601 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2602 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2603 // If a tail called function callee has more arguments than the caller the
2604 // caller needs to make sure that there is room to move the RETADDR to. This is
2605 // achieved by reserving an area the size of the argument delta right after the
2606 // original REtADDR, but before the saved framepointer or the spilled registers
2607 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2619 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2620 /// for a 16 byte align requirement.
2622 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2623 SelectionDAG& DAG) const {
2624 MachineFunction &MF = DAG.getMachineFunction();
2625 const TargetMachine &TM = MF.getTarget();
2626 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2627 unsigned StackAlignment = TFI.getStackAlignment();
2628 uint64_t AlignMask = StackAlignment - 1;
2629 int64_t Offset = StackSize;
2630 uint64_t SlotSize = TD->getPointerSize();
2631 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2632 // Number smaller than 12 so just add the difference.
2633 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2635 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2636 Offset = ((~AlignMask) & Offset) + StackAlignment +
2637 (StackAlignment-SlotSize);
2642 /// MatchingStackOffset - Return true if the given stack call argument is
2643 /// already available in the same position (relatively) of the caller's
2644 /// incoming argument stack.
2646 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2647 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2648 const X86InstrInfo *TII) {
2649 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2651 if (Arg.getOpcode() == ISD::CopyFromReg) {
2652 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2653 if (!TargetRegisterInfo::isVirtualRegister(VR))
2655 MachineInstr *Def = MRI->getVRegDef(VR);
2658 if (!Flags.isByVal()) {
2659 if (!TII->isLoadFromStackSlot(Def, FI))
2662 unsigned Opcode = Def->getOpcode();
2663 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2664 Def->getOperand(1).isFI()) {
2665 FI = Def->getOperand(1).getIndex();
2666 Bytes = Flags.getByValSize();
2670 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2671 if (Flags.isByVal())
2672 // ByVal argument is passed in as a pointer but it's now being
2673 // dereferenced. e.g.
2674 // define @foo(%struct.X* %A) {
2675 // tail call @bar(%struct.X* byval %A)
2678 SDValue Ptr = Ld->getBasePtr();
2679 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2682 FI = FINode->getIndex();
2683 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2684 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2685 FI = FINode->getIndex();
2686 Bytes = Flags.getByValSize();
2690 assert(FI != INT_MAX);
2691 if (!MFI->isFixedObjectIndex(FI))
2693 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2696 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2697 /// for tail call optimization. Targets which want to do tail call
2698 /// optimization should implement this function.
2700 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2701 CallingConv::ID CalleeCC,
2703 bool isCalleeStructRet,
2704 bool isCallerStructRet,
2705 const SmallVectorImpl<ISD::OutputArg> &Outs,
2706 const SmallVectorImpl<SDValue> &OutVals,
2707 const SmallVectorImpl<ISD::InputArg> &Ins,
2708 SelectionDAG& DAG) const {
2709 if (!IsTailCallConvention(CalleeCC) &&
2710 CalleeCC != CallingConv::C)
2713 // If -tailcallopt is specified, make fastcc functions tail-callable.
2714 const MachineFunction &MF = DAG.getMachineFunction();
2715 const Function *CallerF = DAG.getMachineFunction().getFunction();
2716 CallingConv::ID CallerCC = CallerF->getCallingConv();
2717 bool CCMatch = CallerCC == CalleeCC;
2719 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2720 if (IsTailCallConvention(CalleeCC) && CCMatch)
2725 // Look for obvious safe cases to perform tail call optimization that do not
2726 // require ABI changes. This is what gcc calls sibcall.
2728 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2729 // emit a special epilogue.
2730 if (RegInfo->needsStackRealignment(MF))
2733 // Also avoid sibcall optimization if either caller or callee uses struct
2734 // return semantics.
2735 if (isCalleeStructRet || isCallerStructRet)
2738 // An stdcall caller is expected to clean up its arguments; the callee
2739 // isn't going to do that.
2740 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2743 // Do not sibcall optimize vararg calls unless all arguments are passed via
2745 if (isVarArg && !Outs.empty()) {
2747 // Optimizing for varargs on Win64 is unlikely to be safe without
2748 // additional testing.
2749 if (Subtarget->isTargetWin64())
2752 SmallVector<CCValAssign, 16> ArgLocs;
2753 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2754 getTargetMachine(), ArgLocs, *DAG.getContext());
2756 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2757 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2758 if (!ArgLocs[i].isRegLoc())
2762 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2763 // stack. Therefore, if it's not used by the call it is not safe to optimize
2764 // this into a sibcall.
2765 bool Unused = false;
2766 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2773 SmallVector<CCValAssign, 16> RVLocs;
2774 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2775 getTargetMachine(), RVLocs, *DAG.getContext());
2776 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2777 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2778 CCValAssign &VA = RVLocs[i];
2779 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2784 // If the calling conventions do not match, then we'd better make sure the
2785 // results are returned in the same way as what the caller expects.
2787 SmallVector<CCValAssign, 16> RVLocs1;
2788 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2789 getTargetMachine(), RVLocs1, *DAG.getContext());
2790 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2792 SmallVector<CCValAssign, 16> RVLocs2;
2793 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2794 getTargetMachine(), RVLocs2, *DAG.getContext());
2795 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2797 if (RVLocs1.size() != RVLocs2.size())
2799 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2800 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2802 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2804 if (RVLocs1[i].isRegLoc()) {
2805 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2808 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2814 // If the callee takes no arguments then go on to check the results of the
2816 if (!Outs.empty()) {
2817 // Check if stack adjustment is needed. For now, do not do this if any
2818 // argument is passed on the stack.
2819 SmallVector<CCValAssign, 16> ArgLocs;
2820 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2821 getTargetMachine(), ArgLocs, *DAG.getContext());
2823 // Allocate shadow area for Win64
2824 if (Subtarget->isTargetWin64()) {
2825 CCInfo.AllocateStack(32, 8);
2828 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2829 if (CCInfo.getNextStackOffset()) {
2830 MachineFunction &MF = DAG.getMachineFunction();
2831 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2834 // Check if the arguments are already laid out in the right way as
2835 // the caller's fixed stack objects.
2836 MachineFrameInfo *MFI = MF.getFrameInfo();
2837 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2838 const X86InstrInfo *TII =
2839 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2840 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2841 CCValAssign &VA = ArgLocs[i];
2842 SDValue Arg = OutVals[i];
2843 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2844 if (VA.getLocInfo() == CCValAssign::Indirect)
2846 if (!VA.isRegLoc()) {
2847 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2854 // If the tailcall address may be in a register, then make sure it's
2855 // possible to register allocate for it. In 32-bit, the call address can
2856 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2857 // callee-saved registers are restored. These happen to be the same
2858 // registers used to pass 'inreg' arguments so watch out for those.
2859 if (!Subtarget->is64Bit() &&
2860 !isa<GlobalAddressSDNode>(Callee) &&
2861 !isa<ExternalSymbolSDNode>(Callee)) {
2862 unsigned NumInRegs = 0;
2863 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2864 CCValAssign &VA = ArgLocs[i];
2867 unsigned Reg = VA.getLocReg();
2870 case X86::EAX: case X86::EDX: case X86::ECX:
2871 if (++NumInRegs == 3)
2883 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2884 const TargetLibraryInfo *libInfo) const {
2885 return X86::createFastISel(funcInfo, libInfo);
2889 //===----------------------------------------------------------------------===//
2890 // Other Lowering Hooks
2891 //===----------------------------------------------------------------------===//
2893 static bool MayFoldLoad(SDValue Op) {
2894 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2897 static bool MayFoldIntoStore(SDValue Op) {
2898 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2901 static bool isTargetShuffle(unsigned Opcode) {
2903 default: return false;
2904 case X86ISD::PSHUFD:
2905 case X86ISD::PSHUFHW:
2906 case X86ISD::PSHUFLW:
2908 case X86ISD::PALIGN:
2909 case X86ISD::MOVLHPS:
2910 case X86ISD::MOVLHPD:
2911 case X86ISD::MOVHLPS:
2912 case X86ISD::MOVLPS:
2913 case X86ISD::MOVLPD:
2914 case X86ISD::MOVSHDUP:
2915 case X86ISD::MOVSLDUP:
2916 case X86ISD::MOVDDUP:
2919 case X86ISD::UNPCKL:
2920 case X86ISD::UNPCKH:
2921 case X86ISD::VPERMILP:
2922 case X86ISD::VPERM2X128:
2923 case X86ISD::VPERMI:
2928 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2929 SDValue V1, SelectionDAG &DAG) {
2931 default: llvm_unreachable("Unknown x86 shuffle node");
2932 case X86ISD::MOVSHDUP:
2933 case X86ISD::MOVSLDUP:
2934 case X86ISD::MOVDDUP:
2935 return DAG.getNode(Opc, dl, VT, V1);
2939 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2940 SDValue V1, unsigned TargetMask,
2941 SelectionDAG &DAG) {
2943 default: llvm_unreachable("Unknown x86 shuffle node");
2944 case X86ISD::PSHUFD:
2945 case X86ISD::PSHUFHW:
2946 case X86ISD::PSHUFLW:
2947 case X86ISD::VPERMILP:
2948 case X86ISD::VPERMI:
2949 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2953 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2954 SDValue V1, SDValue V2, unsigned TargetMask,
2955 SelectionDAG &DAG) {
2957 default: llvm_unreachable("Unknown x86 shuffle node");
2958 case X86ISD::PALIGN:
2960 case X86ISD::VPERM2X128:
2961 return DAG.getNode(Opc, dl, VT, V1, V2,
2962 DAG.getConstant(TargetMask, MVT::i8));
2966 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2967 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2969 default: llvm_unreachable("Unknown x86 shuffle node");
2970 case X86ISD::MOVLHPS:
2971 case X86ISD::MOVLHPD:
2972 case X86ISD::MOVHLPS:
2973 case X86ISD::MOVLPS:
2974 case X86ISD::MOVLPD:
2977 case X86ISD::UNPCKL:
2978 case X86ISD::UNPCKH:
2979 return DAG.getNode(Opc, dl, VT, V1, V2);
2983 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2984 MachineFunction &MF = DAG.getMachineFunction();
2985 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2986 int ReturnAddrIndex = FuncInfo->getRAIndex();
2988 if (ReturnAddrIndex == 0) {
2989 // Set up a frame object for the return address.
2990 uint64_t SlotSize = TD->getPointerSize();
2991 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2993 FuncInfo->setRAIndex(ReturnAddrIndex);
2996 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3000 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3001 bool hasSymbolicDisplacement) {
3002 // Offset should fit into 32 bit immediate field.
3003 if (!isInt<32>(Offset))
3006 // If we don't have a symbolic displacement - we don't have any extra
3008 if (!hasSymbolicDisplacement)
3011 // FIXME: Some tweaks might be needed for medium code model.
3012 if (M != CodeModel::Small && M != CodeModel::Kernel)
3015 // For small code model we assume that latest object is 16MB before end of 31
3016 // bits boundary. We may also accept pretty large negative constants knowing
3017 // that all objects are in the positive half of address space.
3018 if (M == CodeModel::Small && Offset < 16*1024*1024)
3021 // For kernel code model we know that all object resist in the negative half
3022 // of 32bits address space. We may not accept negative offsets, since they may
3023 // be just off and we may accept pretty large positive ones.
3024 if (M == CodeModel::Kernel && Offset > 0)
3030 /// isCalleePop - Determines whether the callee is required to pop its
3031 /// own arguments. Callee pop is necessary to support tail calls.
3032 bool X86::isCalleePop(CallingConv::ID CallingConv,
3033 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3037 switch (CallingConv) {
3040 case CallingConv::X86_StdCall:
3042 case CallingConv::X86_FastCall:
3044 case CallingConv::X86_ThisCall:
3046 case CallingConv::Fast:
3048 case CallingConv::GHC:
3053 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3054 /// specific condition code, returning the condition code and the LHS/RHS of the
3055 /// comparison to make.
3056 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3057 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3059 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3060 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3061 // X > -1 -> X == 0, jump !sign.
3062 RHS = DAG.getConstant(0, RHS.getValueType());
3063 return X86::COND_NS;
3065 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3066 // X < 0 -> X == 0, jump on sign.
3069 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3071 RHS = DAG.getConstant(0, RHS.getValueType());
3072 return X86::COND_LE;
3076 switch (SetCCOpcode) {
3077 default: llvm_unreachable("Invalid integer condition!");
3078 case ISD::SETEQ: return X86::COND_E;
3079 case ISD::SETGT: return X86::COND_G;
3080 case ISD::SETGE: return X86::COND_GE;
3081 case ISD::SETLT: return X86::COND_L;
3082 case ISD::SETLE: return X86::COND_LE;
3083 case ISD::SETNE: return X86::COND_NE;
3084 case ISD::SETULT: return X86::COND_B;
3085 case ISD::SETUGT: return X86::COND_A;
3086 case ISD::SETULE: return X86::COND_BE;
3087 case ISD::SETUGE: return X86::COND_AE;
3091 // First determine if it is required or is profitable to flip the operands.
3093 // If LHS is a foldable load, but RHS is not, flip the condition.
3094 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3095 !ISD::isNON_EXTLoad(RHS.getNode())) {
3096 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3097 std::swap(LHS, RHS);
3100 switch (SetCCOpcode) {
3106 std::swap(LHS, RHS);
3110 // On a floating point condition, the flags are set as follows:
3112 // 0 | 0 | 0 | X > Y
3113 // 0 | 0 | 1 | X < Y
3114 // 1 | 0 | 0 | X == Y
3115 // 1 | 1 | 1 | unordered
3116 switch (SetCCOpcode) {
3117 default: llvm_unreachable("Condcode should be pre-legalized away");
3119 case ISD::SETEQ: return X86::COND_E;
3120 case ISD::SETOLT: // flipped
3122 case ISD::SETGT: return X86::COND_A;
3123 case ISD::SETOLE: // flipped
3125 case ISD::SETGE: return X86::COND_AE;
3126 case ISD::SETUGT: // flipped
3128 case ISD::SETLT: return X86::COND_B;
3129 case ISD::SETUGE: // flipped
3131 case ISD::SETLE: return X86::COND_BE;
3133 case ISD::SETNE: return X86::COND_NE;
3134 case ISD::SETUO: return X86::COND_P;
3135 case ISD::SETO: return X86::COND_NP;
3137 case ISD::SETUNE: return X86::COND_INVALID;
3141 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3142 /// code. Current x86 isa includes the following FP cmov instructions:
3143 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3144 static bool hasFPCMov(unsigned X86CC) {
3160 /// isFPImmLegal - Returns true if the target can instruction select the
3161 /// specified FP immediate natively. If false, the legalizer will
3162 /// materialize the FP immediate as a load from a constant pool.
3163 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3164 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3165 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3171 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3172 /// the specified range (L, H].
3173 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3174 return (Val < 0) || (Val >= Low && Val < Hi);
3177 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3178 /// specified value.
3179 static bool isUndefOrEqual(int Val, int CmpVal) {
3180 if (Val < 0 || Val == CmpVal)
3185 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3186 /// from position Pos and ending in Pos+Size, falls within the specified
3187 /// sequential range (L, L+Pos]. or is undef.
3188 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3189 unsigned Pos, unsigned Size, int Low) {
3190 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3191 if (!isUndefOrEqual(Mask[i], Low))
3196 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3197 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3198 /// the second operand.
3199 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3200 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3201 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3202 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3203 return (Mask[0] < 2 && Mask[1] < 2);
3207 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3208 /// is suitable for input to PSHUFHW.
3209 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3210 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3213 // Lower quadword copied in order or undef.
3214 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3217 // Upper quadword shuffled.
3218 for (unsigned i = 4; i != 8; ++i)
3219 if (!isUndefOrInRange(Mask[i], 4, 8))
3222 if (VT == MVT::v16i16) {
3223 // Lower quadword copied in order or undef.
3224 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3227 // Upper quadword shuffled.
3228 for (unsigned i = 12; i != 16; ++i)
3229 if (!isUndefOrInRange(Mask[i], 12, 16))
3236 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3237 /// is suitable for input to PSHUFLW.
3238 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3239 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3242 // Upper quadword copied in order.
3243 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3246 // Lower quadword shuffled.
3247 for (unsigned i = 0; i != 4; ++i)
3248 if (!isUndefOrInRange(Mask[i], 0, 4))
3251 if (VT == MVT::v16i16) {
3252 // Upper quadword copied in order.
3253 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3256 // Lower quadword shuffled.
3257 for (unsigned i = 8; i != 12; ++i)
3258 if (!isUndefOrInRange(Mask[i], 8, 12))
3265 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3266 /// is suitable for input to PALIGNR.
3267 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3268 const X86Subtarget *Subtarget) {
3269 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3270 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3273 unsigned NumElts = VT.getVectorNumElements();
3274 unsigned NumLanes = VT.getSizeInBits()/128;
3275 unsigned NumLaneElts = NumElts/NumLanes;
3277 // Do not handle 64-bit element shuffles with palignr.
3278 if (NumLaneElts == 2)
3281 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3283 for (i = 0; i != NumLaneElts; ++i) {
3288 // Lane is all undef, go to next lane
3289 if (i == NumLaneElts)
3292 int Start = Mask[i+l];
3294 // Make sure its in this lane in one of the sources
3295 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3296 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3299 // If not lane 0, then we must match lane 0
3300 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3303 // Correct second source to be contiguous with first source
3304 if (Start >= (int)NumElts)
3305 Start -= NumElts - NumLaneElts;
3307 // Make sure we're shifting in the right direction.
3308 if (Start <= (int)(i+l))
3313 // Check the rest of the elements to see if they are consecutive.
3314 for (++i; i != NumLaneElts; ++i) {
3315 int Idx = Mask[i+l];
3317 // Make sure its in this lane
3318 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3319 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3322 // If not lane 0, then we must match lane 0
3323 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3326 if (Idx >= (int)NumElts)
3327 Idx -= NumElts - NumLaneElts;
3329 if (!isUndefOrEqual(Idx, Start+i))
3338 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3339 /// the two vector operands have swapped position.
3340 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3341 unsigned NumElems) {
3342 for (unsigned i = 0; i != NumElems; ++i) {
3346 else if (idx < (int)NumElems)
3347 Mask[i] = idx + NumElems;
3349 Mask[i] = idx - NumElems;
3353 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3354 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3355 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3356 /// reverse of what x86 shuffles want.
3357 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3358 bool Commuted = false) {
3359 if (!HasAVX && VT.getSizeInBits() == 256)
3362 unsigned NumElems = VT.getVectorNumElements();
3363 unsigned NumLanes = VT.getSizeInBits()/128;
3364 unsigned NumLaneElems = NumElems/NumLanes;
3366 if (NumLaneElems != 2 && NumLaneElems != 4)
3369 // VSHUFPSY divides the resulting vector into 4 chunks.
3370 // The sources are also splitted into 4 chunks, and each destination
3371 // chunk must come from a different source chunk.
3373 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3374 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3376 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3377 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3379 // VSHUFPDY divides the resulting vector into 4 chunks.
3380 // The sources are also splitted into 4 chunks, and each destination
3381 // chunk must come from a different source chunk.
3383 // SRC1 => X3 X2 X1 X0
3384 // SRC2 => Y3 Y2 Y1 Y0
3386 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3388 unsigned HalfLaneElems = NumLaneElems/2;
3389 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3390 for (unsigned i = 0; i != NumLaneElems; ++i) {
3391 int Idx = Mask[i+l];
3392 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3393 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3395 // For VSHUFPSY, the mask of the second half must be the same as the
3396 // first but with the appropriate offsets. This works in the same way as
3397 // VPERMILPS works with masks.
3398 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3400 if (!isUndefOrEqual(Idx, Mask[i]+l))
3408 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3409 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3410 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3411 if (!VT.is128BitVector())
3414 unsigned NumElems = VT.getVectorNumElements();
3419 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3420 return isUndefOrEqual(Mask[0], 6) &&
3421 isUndefOrEqual(Mask[1], 7) &&
3422 isUndefOrEqual(Mask[2], 2) &&
3423 isUndefOrEqual(Mask[3], 3);
3426 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3427 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3429 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3430 if (!VT.is128BitVector())
3433 unsigned NumElems = VT.getVectorNumElements();
3438 return isUndefOrEqual(Mask[0], 2) &&
3439 isUndefOrEqual(Mask[1], 3) &&
3440 isUndefOrEqual(Mask[2], 2) &&
3441 isUndefOrEqual(Mask[3], 3);
3444 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3445 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3446 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3447 if (!VT.is128BitVector())
3450 unsigned NumElems = VT.getVectorNumElements();
3452 if (NumElems != 2 && NumElems != 4)
3455 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3456 if (!isUndefOrEqual(Mask[i], i + NumElems))
3459 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3460 if (!isUndefOrEqual(Mask[i], i))
3466 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3467 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3468 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3469 if (!VT.is128BitVector())
3472 unsigned NumElems = VT.getVectorNumElements();
3474 if (NumElems != 2 && NumElems != 4)
3477 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3478 if (!isUndefOrEqual(Mask[i], i))
3481 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3482 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3489 // Some special combinations that can be optimized.
3492 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3493 SelectionDAG &DAG) {
3494 EVT VT = SVOp->getValueType(0);
3495 DebugLoc dl = SVOp->getDebugLoc();
3497 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3500 ArrayRef<int> Mask = SVOp->getMask();
3502 // These are the special masks that may be optimized.
3503 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3504 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3505 bool MatchEvenMask = true;
3506 bool MatchOddMask = true;
3507 for (int i=0; i<8; ++i) {
3508 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3509 MatchEvenMask = false;
3510 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3511 MatchOddMask = false;
3514 if (!MatchEvenMask && !MatchOddMask)
3517 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3519 SDValue Op0 = SVOp->getOperand(0);
3520 SDValue Op1 = SVOp->getOperand(1);
3522 if (MatchEvenMask) {
3523 // Shift the second operand right to 32 bits.
3524 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3525 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3527 // Shift the first operand left to 32 bits.
3528 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3529 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3531 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3532 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3535 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3536 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3537 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3538 bool HasAVX2, bool V2IsSplat = false) {
3539 unsigned NumElts = VT.getVectorNumElements();
3541 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3542 "Unsupported vector type for unpckh");
3544 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3545 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3548 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3549 // independently on 128-bit lanes.
3550 unsigned NumLanes = VT.getSizeInBits()/128;
3551 unsigned NumLaneElts = NumElts/NumLanes;
3553 for (unsigned l = 0; l != NumLanes; ++l) {
3554 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3555 i != (l+1)*NumLaneElts;
3558 int BitI1 = Mask[i+1];
3559 if (!isUndefOrEqual(BitI, j))
3562 if (!isUndefOrEqual(BitI1, NumElts))
3565 if (!isUndefOrEqual(BitI1, j + NumElts))
3574 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3575 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3576 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3577 bool HasAVX2, bool V2IsSplat = false) {
3578 unsigned NumElts = VT.getVectorNumElements();
3580 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3581 "Unsupported vector type for unpckh");
3583 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3584 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3587 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3588 // independently on 128-bit lanes.
3589 unsigned NumLanes = VT.getSizeInBits()/128;
3590 unsigned NumLaneElts = NumElts/NumLanes;
3592 for (unsigned l = 0; l != NumLanes; ++l) {
3593 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3594 i != (l+1)*NumLaneElts; i += 2, ++j) {
3596 int BitI1 = Mask[i+1];
3597 if (!isUndefOrEqual(BitI, j))
3600 if (isUndefOrEqual(BitI1, NumElts))
3603 if (!isUndefOrEqual(BitI1, j+NumElts))
3611 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3612 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3614 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3616 unsigned NumElts = VT.getVectorNumElements();
3618 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3619 "Unsupported vector type for unpckh");
3621 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3622 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3625 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3626 // FIXME: Need a better way to get rid of this, there's no latency difference
3627 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3628 // the former later. We should also remove the "_undef" special mask.
3629 if (NumElts == 4 && VT.getSizeInBits() == 256)
3632 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3633 // independently on 128-bit lanes.
3634 unsigned NumLanes = VT.getSizeInBits()/128;
3635 unsigned NumLaneElts = NumElts/NumLanes;
3637 for (unsigned l = 0; l != NumLanes; ++l) {
3638 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3639 i != (l+1)*NumLaneElts;
3642 int BitI1 = Mask[i+1];
3644 if (!isUndefOrEqual(BitI, j))
3646 if (!isUndefOrEqual(BitI1, j))
3654 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3655 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3657 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3658 unsigned NumElts = VT.getVectorNumElements();
3660 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3661 "Unsupported vector type for unpckh");
3663 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3664 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3667 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3668 // independently on 128-bit lanes.
3669 unsigned NumLanes = VT.getSizeInBits()/128;
3670 unsigned NumLaneElts = NumElts/NumLanes;
3672 for (unsigned l = 0; l != NumLanes; ++l) {
3673 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3674 i != (l+1)*NumLaneElts; i += 2, ++j) {
3676 int BitI1 = Mask[i+1];
3677 if (!isUndefOrEqual(BitI, j))
3679 if (!isUndefOrEqual(BitI1, j))
3686 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3687 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3688 /// MOVSD, and MOVD, i.e. setting the lowest element.
3689 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3690 if (VT.getVectorElementType().getSizeInBits() < 32)
3692 if (!VT.is128BitVector())
3695 unsigned NumElts = VT.getVectorNumElements();
3697 if (!isUndefOrEqual(Mask[0], NumElts))
3700 for (unsigned i = 1; i != NumElts; ++i)
3701 if (!isUndefOrEqual(Mask[i], i))
3707 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3708 /// as permutations between 128-bit chunks or halves. As an example: this
3710 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3711 /// The first half comes from the second half of V1 and the second half from the
3712 /// the second half of V2.
3713 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3714 if (!HasAVX || !VT.is256BitVector())
3717 // The shuffle result is divided into half A and half B. In total the two
3718 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3719 // B must come from C, D, E or F.
3720 unsigned HalfSize = VT.getVectorNumElements()/2;
3721 bool MatchA = false, MatchB = false;
3723 // Check if A comes from one of C, D, E, F.
3724 for (unsigned Half = 0; Half != 4; ++Half) {
3725 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3731 // Check if B comes from one of C, D, E, F.
3732 for (unsigned Half = 0; Half != 4; ++Half) {
3733 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3739 return MatchA && MatchB;
3742 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3743 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3744 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3745 EVT VT = SVOp->getValueType(0);
3747 unsigned HalfSize = VT.getVectorNumElements()/2;
3749 unsigned FstHalf = 0, SndHalf = 0;
3750 for (unsigned i = 0; i < HalfSize; ++i) {
3751 if (SVOp->getMaskElt(i) > 0) {
3752 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3756 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3757 if (SVOp->getMaskElt(i) > 0) {
3758 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3763 return (FstHalf | (SndHalf << 4));
3766 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3767 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3768 /// Note that VPERMIL mask matching is different depending whether theunderlying
3769 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3770 /// to the same elements of the low, but to the higher half of the source.
3771 /// In VPERMILPD the two lanes could be shuffled independently of each other
3772 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3773 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3777 unsigned NumElts = VT.getVectorNumElements();
3778 // Only match 256-bit with 32/64-bit types
3779 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3782 unsigned NumLanes = VT.getSizeInBits()/128;
3783 unsigned LaneSize = NumElts/NumLanes;
3784 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3785 for (unsigned i = 0; i != LaneSize; ++i) {
3786 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3788 if (NumElts != 8 || l == 0)
3790 // VPERMILPS handling
3793 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3801 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3802 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3803 /// element of vector 2 and the other elements to come from vector 1 in order.
3804 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3805 bool V2IsSplat = false, bool V2IsUndef = false) {
3806 if (!VT.is128BitVector())
3809 unsigned NumOps = VT.getVectorNumElements();
3810 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3813 if (!isUndefOrEqual(Mask[0], 0))
3816 for (unsigned i = 1; i != NumOps; ++i)
3817 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3818 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3819 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3825 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3826 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3827 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3828 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3829 const X86Subtarget *Subtarget) {
3830 if (!Subtarget->hasSSE3())
3833 unsigned NumElems = VT.getVectorNumElements();
3835 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3836 (VT.getSizeInBits() == 256 && NumElems != 8))
3839 // "i+1" is the value the indexed mask element must have
3840 for (unsigned i = 0; i != NumElems; i += 2)
3841 if (!isUndefOrEqual(Mask[i], i+1) ||
3842 !isUndefOrEqual(Mask[i+1], i+1))
3848 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3849 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3850 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3851 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3852 const X86Subtarget *Subtarget) {
3853 if (!Subtarget->hasSSE3())
3856 unsigned NumElems = VT.getVectorNumElements();
3858 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3859 (VT.getSizeInBits() == 256 && NumElems != 8))
3862 // "i" is the value the indexed mask element must have
3863 for (unsigned i = 0; i != NumElems; i += 2)
3864 if (!isUndefOrEqual(Mask[i], i) ||
3865 !isUndefOrEqual(Mask[i+1], i))
3871 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to 256-bit
3873 /// version of MOVDDUP.
3874 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3875 if (!HasAVX || !VT.is256BitVector())
3878 unsigned NumElts = VT.getVectorNumElements();
3882 for (unsigned i = 0; i != NumElts/2; ++i)
3883 if (!isUndefOrEqual(Mask[i], 0))
3885 for (unsigned i = NumElts/2; i != NumElts; ++i)
3886 if (!isUndefOrEqual(Mask[i], NumElts/2))
3891 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3892 /// specifies a shuffle of elements that is suitable for input to 128-bit
3893 /// version of MOVDDUP.
3894 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3895 if (!VT.is128BitVector())
3898 unsigned e = VT.getVectorNumElements() / 2;
3899 for (unsigned i = 0; i != e; ++i)
3900 if (!isUndefOrEqual(Mask[i], i))
3902 for (unsigned i = 0; i != e; ++i)
3903 if (!isUndefOrEqual(Mask[e+i], i))
3908 /// isVEXTRACTF128Index - Return true if the specified
3909 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3910 /// suitable for input to VEXTRACTF128.
3911 bool X86::isVEXTRACTF128Index(SDNode *N) {
3912 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3915 // The index should be aligned on a 128-bit boundary.
3917 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3919 unsigned VL = N->getValueType(0).getVectorNumElements();
3920 unsigned VBits = N->getValueType(0).getSizeInBits();
3921 unsigned ElSize = VBits / VL;
3922 bool Result = (Index * ElSize) % 128 == 0;
3927 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3928 /// operand specifies a subvector insert that is suitable for input to
3930 bool X86::isVINSERTF128Index(SDNode *N) {
3931 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3934 // The index should be aligned on a 128-bit boundary.
3936 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3938 unsigned VL = N->getValueType(0).getVectorNumElements();
3939 unsigned VBits = N->getValueType(0).getSizeInBits();
3940 unsigned ElSize = VBits / VL;
3941 bool Result = (Index * ElSize) % 128 == 0;
3946 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3947 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3948 /// Handles 128-bit and 256-bit.
3949 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3950 EVT VT = N->getValueType(0);
3952 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3953 "Unsupported vector type for PSHUF/SHUFP");
3955 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3956 // independently on 128-bit lanes.
3957 unsigned NumElts = VT.getVectorNumElements();
3958 unsigned NumLanes = VT.getSizeInBits()/128;
3959 unsigned NumLaneElts = NumElts/NumLanes;
3961 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3962 "Only supports 2 or 4 elements per lane");
3964 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3966 for (unsigned i = 0; i != NumElts; ++i) {
3967 int Elt = N->getMaskElt(i);
3968 if (Elt < 0) continue;
3969 Elt &= NumLaneElts - 1;
3970 unsigned ShAmt = (i << Shift) % 8;
3971 Mask |= Elt << ShAmt;
3977 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3978 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3979 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3980 EVT VT = N->getValueType(0);
3982 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3983 "Unsupported vector type for PSHUFHW");
3985 unsigned NumElts = VT.getVectorNumElements();
3988 for (unsigned l = 0; l != NumElts; l += 8) {
3989 // 8 nodes per lane, but we only care about the last 4.
3990 for (unsigned i = 0; i < 4; ++i) {
3991 int Elt = N->getMaskElt(l+i+4);
3992 if (Elt < 0) continue;
3993 Elt &= 0x3; // only 2-bits.
3994 Mask |= Elt << (i * 2);
4001 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4002 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4003 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4004 EVT VT = N->getValueType(0);
4006 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4007 "Unsupported vector type for PSHUFHW");
4009 unsigned NumElts = VT.getVectorNumElements();
4012 for (unsigned l = 0; l != NumElts; l += 8) {
4013 // 8 nodes per lane, but we only care about the first 4.
4014 for (unsigned i = 0; i < 4; ++i) {
4015 int Elt = N->getMaskElt(l+i);
4016 if (Elt < 0) continue;
4017 Elt &= 0x3; // only 2-bits
4018 Mask |= Elt << (i * 2);
4025 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4026 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4027 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4028 EVT VT = SVOp->getValueType(0);
4029 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4031 unsigned NumElts = VT.getVectorNumElements();
4032 unsigned NumLanes = VT.getSizeInBits()/128;
4033 unsigned NumLaneElts = NumElts/NumLanes;
4037 for (i = 0; i != NumElts; ++i) {
4038 Val = SVOp->getMaskElt(i);
4042 if (Val >= (int)NumElts)
4043 Val -= NumElts - NumLaneElts;
4045 assert(Val - i > 0 && "PALIGNR imm should be positive");
4046 return (Val - i) * EltSize;
4049 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4050 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4052 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4053 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4054 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4057 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4059 EVT VecVT = N->getOperand(0).getValueType();
4060 EVT ElVT = VecVT.getVectorElementType();
4062 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4063 return Index / NumElemsPerChunk;
4066 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4067 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4069 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4070 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4071 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4074 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4076 EVT VecVT = N->getValueType(0);
4077 EVT ElVT = VecVT.getVectorElementType();
4079 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4080 return Index / NumElemsPerChunk;
4083 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4084 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4085 /// Handles 256-bit.
4086 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4087 EVT VT = N->getValueType(0);
4089 unsigned NumElts = VT.getVectorNumElements();
4091 assert((VT.is256BitVector() && NumElts == 4) &&
4092 "Unsupported vector type for VPERMQ/VPERMPD");
4095 for (unsigned i = 0; i != NumElts; ++i) {
4096 int Elt = N->getMaskElt(i);
4099 Mask |= Elt << (i*2);
4104 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4106 bool X86::isZeroNode(SDValue Elt) {
4107 return ((isa<ConstantSDNode>(Elt) &&
4108 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4109 (isa<ConstantFPSDNode>(Elt) &&
4110 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4113 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4114 /// their permute mask.
4115 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4116 SelectionDAG &DAG) {
4117 EVT VT = SVOp->getValueType(0);
4118 unsigned NumElems = VT.getVectorNumElements();
4119 SmallVector<int, 8> MaskVec;
4121 for (unsigned i = 0; i != NumElems; ++i) {
4122 int Idx = SVOp->getMaskElt(i);
4124 if (Idx < (int)NumElems)
4129 MaskVec.push_back(Idx);
4131 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4132 SVOp->getOperand(0), &MaskVec[0]);
4135 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4136 /// match movhlps. The lower half elements should come from upper half of
4137 /// V1 (and in order), and the upper half elements should come from the upper
4138 /// half of V2 (and in order).
4139 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4140 if (!VT.is128BitVector())
4142 if (VT.getVectorNumElements() != 4)
4144 for (unsigned i = 0, e = 2; i != e; ++i)
4145 if (!isUndefOrEqual(Mask[i], i+2))
4147 for (unsigned i = 2; i != 4; ++i)
4148 if (!isUndefOrEqual(Mask[i], i+4))
4153 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4154 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4156 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4157 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4159 N = N->getOperand(0).getNode();
4160 if (!ISD::isNON_EXTLoad(N))
4163 *LD = cast<LoadSDNode>(N);
4167 // Test whether the given value is a vector value which will be legalized
4169 static bool WillBeConstantPoolLoad(SDNode *N) {
4170 if (N->getOpcode() != ISD::BUILD_VECTOR)
4173 // Check for any non-constant elements.
4174 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4175 switch (N->getOperand(i).getNode()->getOpcode()) {
4177 case ISD::ConstantFP:
4184 // Vectors of all-zeros and all-ones are materialized with special
4185 // instructions rather than being loaded.
4186 return !ISD::isBuildVectorAllZeros(N) &&
4187 !ISD::isBuildVectorAllOnes(N);
4190 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4191 /// match movlp{s|d}. The lower half elements should come from lower half of
4192 /// V1 (and in order), and the upper half elements should come from the upper
4193 /// half of V2 (and in order). And since V1 will become the source of the
4194 /// MOVLP, it must be either a vector load or a scalar load to vector.
4195 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4196 ArrayRef<int> Mask, EVT VT) {
4197 if (!VT.is128BitVector())
4200 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4202 // Is V2 is a vector load, don't do this transformation. We will try to use
4203 // load folding shufps op.
4204 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4207 unsigned NumElems = VT.getVectorNumElements();
4209 if (NumElems != 2 && NumElems != 4)
4211 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4212 if (!isUndefOrEqual(Mask[i], i))
4214 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4215 if (!isUndefOrEqual(Mask[i], i+NumElems))
4220 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4222 static bool isSplatVector(SDNode *N) {
4223 if (N->getOpcode() != ISD::BUILD_VECTOR)
4226 SDValue SplatValue = N->getOperand(0);
4227 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4228 if (N->getOperand(i) != SplatValue)
4233 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4234 /// to an zero vector.
4235 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4236 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4237 SDValue V1 = N->getOperand(0);
4238 SDValue V2 = N->getOperand(1);
4239 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4240 for (unsigned i = 0; i != NumElems; ++i) {
4241 int Idx = N->getMaskElt(i);
4242 if (Idx >= (int)NumElems) {
4243 unsigned Opc = V2.getOpcode();
4244 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4246 if (Opc != ISD::BUILD_VECTOR ||
4247 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4249 } else if (Idx >= 0) {
4250 unsigned Opc = V1.getOpcode();
4251 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4253 if (Opc != ISD::BUILD_VECTOR ||
4254 !X86::isZeroNode(V1.getOperand(Idx)))
4261 /// getZeroVector - Returns a vector of specified type with all zero elements.
4263 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4264 SelectionDAG &DAG, DebugLoc dl) {
4265 assert(VT.isVector() && "Expected a vector type");
4266 unsigned Size = VT.getSizeInBits();
4268 // Always build SSE zero vectors as <4 x i32> bitcasted
4269 // to their dest type. This ensures they get CSE'd.
4271 if (Size == 128) { // SSE
4272 if (Subtarget->hasSSE2()) { // SSE2
4273 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4274 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4276 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4277 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4279 } else if (Size == 256) { // AVX
4280 if (Subtarget->hasAVX2()) { // AVX2
4281 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4282 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4283 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4285 // 256-bit logic and arithmetic instructions in AVX are all
4286 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4287 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4288 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4289 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4292 llvm_unreachable("Unexpected vector type");
4294 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4297 /// getOnesVector - Returns a vector of specified type with all bits set.
4298 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4299 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4300 /// Then bitcast to their original type, ensuring they get CSE'd.
4301 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4303 assert(VT.isVector() && "Expected a vector type");
4304 unsigned Size = VT.getSizeInBits();
4306 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4309 if (HasAVX2) { // AVX2
4310 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4311 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4313 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4314 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4316 } else if (Size == 128) {
4317 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4319 llvm_unreachable("Unexpected vector type");
4321 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4324 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4325 /// that point to V2 points to its first element.
4326 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4327 for (unsigned i = 0; i != NumElems; ++i) {
4328 if (Mask[i] > (int)NumElems) {
4334 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4335 /// operation of specified width.
4336 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4338 unsigned NumElems = VT.getVectorNumElements();
4339 SmallVector<int, 8> Mask;
4340 Mask.push_back(NumElems);
4341 for (unsigned i = 1; i != NumElems; ++i)
4343 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4346 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4347 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4349 unsigned NumElems = VT.getVectorNumElements();
4350 SmallVector<int, 8> Mask;
4351 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4353 Mask.push_back(i + NumElems);
4355 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4358 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4359 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4361 unsigned NumElems = VT.getVectorNumElements();
4362 SmallVector<int, 8> Mask;
4363 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4364 Mask.push_back(i + Half);
4365 Mask.push_back(i + NumElems + Half);
4367 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4370 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4371 // a generic shuffle instruction because the target has no such instructions.
4372 // Generate shuffles which repeat i16 and i8 several times until they can be
4373 // represented by v4f32 and then be manipulated by target suported shuffles.
4374 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4375 EVT VT = V.getValueType();
4376 int NumElems = VT.getVectorNumElements();
4377 DebugLoc dl = V.getDebugLoc();
4379 while (NumElems > 4) {
4380 if (EltNo < NumElems/2) {
4381 V = getUnpackl(DAG, dl, VT, V, V);
4383 V = getUnpackh(DAG, dl, VT, V, V);
4384 EltNo -= NumElems/2;
4391 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4392 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4393 EVT VT = V.getValueType();
4394 DebugLoc dl = V.getDebugLoc();
4395 unsigned Size = VT.getSizeInBits();
4398 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4399 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4400 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4402 } else if (Size == 256) {
4403 // To use VPERMILPS to splat scalars, the second half of indicies must
4404 // refer to the higher part, which is a duplication of the lower one,
4405 // because VPERMILPS can only handle in-lane permutations.
4406 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4407 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4409 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4410 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4413 llvm_unreachable("Vector size not supported");
4415 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4418 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4419 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4420 EVT SrcVT = SV->getValueType(0);
4421 SDValue V1 = SV->getOperand(0);
4422 DebugLoc dl = SV->getDebugLoc();
4424 int EltNo = SV->getSplatIndex();
4425 int NumElems = SrcVT.getVectorNumElements();
4426 unsigned Size = SrcVT.getSizeInBits();
4428 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4429 "Unknown how to promote splat for type");
4431 // Extract the 128-bit part containing the splat element and update
4432 // the splat element index when it refers to the higher register.
4434 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4435 if (EltNo >= NumElems/2)
4436 EltNo -= NumElems/2;
4439 // All i16 and i8 vector types can't be used directly by a generic shuffle
4440 // instruction because the target has no such instruction. Generate shuffles
4441 // which repeat i16 and i8 several times until they fit in i32, and then can
4442 // be manipulated by target suported shuffles.
4443 EVT EltVT = SrcVT.getVectorElementType();
4444 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4445 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4447 // Recreate the 256-bit vector and place the same 128-bit vector
4448 // into the low and high part. This is necessary because we want
4449 // to use VPERM* to shuffle the vectors
4451 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4454 return getLegalSplat(DAG, V1, EltNo);
4457 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4458 /// vector of zero or undef vector. This produces a shuffle where the low
4459 /// element of V2 is swizzled into the zero/undef vector, landing at element
4460 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4461 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4463 const X86Subtarget *Subtarget,
4464 SelectionDAG &DAG) {
4465 EVT VT = V2.getValueType();
4467 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4468 unsigned NumElems = VT.getVectorNumElements();
4469 SmallVector<int, 16> MaskVec;
4470 for (unsigned i = 0; i != NumElems; ++i)
4471 // If this is the insertion idx, put the low elt of V2 here.
4472 MaskVec.push_back(i == Idx ? NumElems : i);
4473 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4476 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4477 /// target specific opcode. Returns true if the Mask could be calculated.
4478 /// Sets IsUnary to true if only uses one source.
4479 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4480 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4481 unsigned NumElems = VT.getVectorNumElements();
4485 switch(N->getOpcode()) {
4487 ImmN = N->getOperand(N->getNumOperands()-1);
4488 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4490 case X86ISD::UNPCKH:
4491 DecodeUNPCKHMask(VT, Mask);
4493 case X86ISD::UNPCKL:
4494 DecodeUNPCKLMask(VT, Mask);
4496 case X86ISD::MOVHLPS:
4497 DecodeMOVHLPSMask(NumElems, Mask);
4499 case X86ISD::MOVLHPS:
4500 DecodeMOVLHPSMask(NumElems, Mask);
4502 case X86ISD::PSHUFD:
4503 case X86ISD::VPERMILP:
4504 ImmN = N->getOperand(N->getNumOperands()-1);
4505 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4508 case X86ISD::PSHUFHW:
4509 ImmN = N->getOperand(N->getNumOperands()-1);
4510 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4513 case X86ISD::PSHUFLW:
4514 ImmN = N->getOperand(N->getNumOperands()-1);
4515 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4518 case X86ISD::VPERMI:
4519 ImmN = N->getOperand(N->getNumOperands()-1);
4520 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524 case X86ISD::MOVSD: {
4525 // The index 0 always comes from the first element of the second source,
4526 // this is why MOVSS and MOVSD are used in the first place. The other
4527 // elements come from the other positions of the first source vector
4528 Mask.push_back(NumElems);
4529 for (unsigned i = 1; i != NumElems; ++i) {
4534 case X86ISD::VPERM2X128:
4535 ImmN = N->getOperand(N->getNumOperands()-1);
4536 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4537 if (Mask.empty()) return false;
4539 case X86ISD::MOVDDUP:
4540 case X86ISD::MOVLHPD:
4541 case X86ISD::MOVLPD:
4542 case X86ISD::MOVLPS:
4543 case X86ISD::MOVSHDUP:
4544 case X86ISD::MOVSLDUP:
4545 case X86ISD::PALIGN:
4546 // Not yet implemented
4548 default: llvm_unreachable("unknown target shuffle node");
4554 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4555 /// element of the result of the vector shuffle.
4556 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4559 return SDValue(); // Limit search depth.
4561 SDValue V = SDValue(N, 0);
4562 EVT VT = V.getValueType();
4563 unsigned Opcode = V.getOpcode();
4565 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4566 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4567 int Elt = SV->getMaskElt(Index);
4570 return DAG.getUNDEF(VT.getVectorElementType());
4572 unsigned NumElems = VT.getVectorNumElements();
4573 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4574 : SV->getOperand(1);
4575 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4578 // Recurse into target specific vector shuffles to find scalars.
4579 if (isTargetShuffle(Opcode)) {
4580 MVT ShufVT = V.getValueType().getSimpleVT();
4581 unsigned NumElems = ShufVT.getVectorNumElements();
4582 SmallVector<int, 16> ShuffleMask;
4586 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4589 int Elt = ShuffleMask[Index];
4591 return DAG.getUNDEF(ShufVT.getVectorElementType());
4593 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4595 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4599 // Actual nodes that may contain scalar elements
4600 if (Opcode == ISD::BITCAST) {
4601 V = V.getOperand(0);
4602 EVT SrcVT = V.getValueType();
4603 unsigned NumElems = VT.getVectorNumElements();
4605 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4609 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4610 return (Index == 0) ? V.getOperand(0)
4611 : DAG.getUNDEF(VT.getVectorElementType());
4613 if (V.getOpcode() == ISD::BUILD_VECTOR)
4614 return V.getOperand(Index);
4619 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4620 /// shuffle operation which come from a consecutively from a zero. The
4621 /// search can start in two different directions, from left or right.
4623 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4624 bool ZerosFromLeft, SelectionDAG &DAG) {
4626 for (i = 0; i != NumElems; ++i) {
4627 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4628 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4629 if (!(Elt.getNode() &&
4630 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4637 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4638 /// correspond consecutively to elements from one of the vector operands,
4639 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4641 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4642 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4643 unsigned NumElems, unsigned &OpNum) {
4644 bool SeenV1 = false;
4645 bool SeenV2 = false;
4647 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4648 int Idx = SVOp->getMaskElt(i);
4649 // Ignore undef indicies
4653 if (Idx < (int)NumElems)
4658 // Only accept consecutive elements from the same vector
4659 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4663 OpNum = SeenV1 ? 0 : 1;
4667 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4668 /// logical left shift of a vector.
4669 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4670 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4671 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4672 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4673 false /* check zeros from right */, DAG);
4679 // Considering the elements in the mask that are not consecutive zeros,
4680 // check if they consecutively come from only one of the source vectors.
4682 // V1 = {X, A, B, C} 0
4684 // vector_shuffle V1, V2 <1, 2, 3, X>
4686 if (!isShuffleMaskConsecutive(SVOp,
4687 0, // Mask Start Index
4688 NumElems-NumZeros, // Mask End Index(exclusive)
4689 NumZeros, // Where to start looking in the src vector
4690 NumElems, // Number of elements in vector
4691 OpSrc)) // Which source operand ?
4696 ShVal = SVOp->getOperand(OpSrc);
4700 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4701 /// logical left shift of a vector.
4702 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4703 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4704 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4705 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4706 true /* check zeros from left */, DAG);
4712 // Considering the elements in the mask that are not consecutive zeros,
4713 // check if they consecutively come from only one of the source vectors.
4715 // 0 { A, B, X, X } = V2
4717 // vector_shuffle V1, V2 <X, X, 4, 5>
4719 if (!isShuffleMaskConsecutive(SVOp,
4720 NumZeros, // Mask Start Index
4721 NumElems, // Mask End Index(exclusive)
4722 0, // Where to start looking in the src vector
4723 NumElems, // Number of elements in vector
4724 OpSrc)) // Which source operand ?
4729 ShVal = SVOp->getOperand(OpSrc);
4733 /// isVectorShift - Returns true if the shuffle can be implemented as a
4734 /// logical left or right shift of a vector.
4735 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4736 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4737 // Although the logic below support any bitwidth size, there are no
4738 // shift instructions which handle more than 128-bit vectors.
4739 if (!SVOp->getValueType(0).is128BitVector())
4742 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4743 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4749 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4751 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4752 unsigned NumNonZero, unsigned NumZero,
4754 const X86Subtarget* Subtarget,
4755 const TargetLowering &TLI) {
4759 DebugLoc dl = Op.getDebugLoc();
4762 for (unsigned i = 0; i < 16; ++i) {
4763 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4764 if (ThisIsNonZero && First) {
4766 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4768 V = DAG.getUNDEF(MVT::v8i16);
4773 SDValue ThisElt(0, 0), LastElt(0, 0);
4774 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4775 if (LastIsNonZero) {
4776 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4777 MVT::i16, Op.getOperand(i-1));
4779 if (ThisIsNonZero) {
4780 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4781 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4782 ThisElt, DAG.getConstant(8, MVT::i8));
4784 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4788 if (ThisElt.getNode())
4789 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4790 DAG.getIntPtrConstant(i/2));
4794 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4797 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4799 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4800 unsigned NumNonZero, unsigned NumZero,
4802 const X86Subtarget* Subtarget,
4803 const TargetLowering &TLI) {
4807 DebugLoc dl = Op.getDebugLoc();
4810 for (unsigned i = 0; i < 8; ++i) {
4811 bool isNonZero = (NonZeros & (1 << i)) != 0;
4815 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4817 V = DAG.getUNDEF(MVT::v8i16);
4820 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4821 MVT::v8i16, V, Op.getOperand(i),
4822 DAG.getIntPtrConstant(i));
4829 /// getVShift - Return a vector logical shift node.
4831 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4832 unsigned NumBits, SelectionDAG &DAG,
4833 const TargetLowering &TLI, DebugLoc dl) {
4834 assert(VT.is128BitVector() && "Unknown type for VShift");
4835 EVT ShVT = MVT::v2i64;
4836 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4837 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4838 return DAG.getNode(ISD::BITCAST, dl, VT,
4839 DAG.getNode(Opc, dl, ShVT, SrcOp,
4840 DAG.getConstant(NumBits,
4841 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4845 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4846 SelectionDAG &DAG) const {
4848 // Check if the scalar load can be widened into a vector load. And if
4849 // the address is "base + cst" see if the cst can be "absorbed" into
4850 // the shuffle mask.
4851 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4852 SDValue Ptr = LD->getBasePtr();
4853 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4855 EVT PVT = LD->getValueType(0);
4856 if (PVT != MVT::i32 && PVT != MVT::f32)
4861 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4862 FI = FINode->getIndex();
4864 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4865 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4866 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4867 Offset = Ptr.getConstantOperandVal(1);
4868 Ptr = Ptr.getOperand(0);
4873 // FIXME: 256-bit vector instructions don't require a strict alignment,
4874 // improve this code to support it better.
4875 unsigned RequiredAlign = VT.getSizeInBits()/8;
4876 SDValue Chain = LD->getChain();
4877 // Make sure the stack object alignment is at least 16 or 32.
4878 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4879 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4880 if (MFI->isFixedObjectIndex(FI)) {
4881 // Can't change the alignment. FIXME: It's possible to compute
4882 // the exact stack offset and reference FI + adjust offset instead.
4883 // If someone *really* cares about this. That's the way to implement it.
4886 MFI->setObjectAlignment(FI, RequiredAlign);
4890 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4891 // Ptr + (Offset & ~15).
4894 if ((Offset % RequiredAlign) & 3)
4896 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4898 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4899 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4901 int EltNo = (Offset - StartOffset) >> 2;
4902 unsigned NumElems = VT.getVectorNumElements();
4904 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4905 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4906 LD->getPointerInfo().getWithOffset(StartOffset),
4907 false, false, false, 0);
4909 SmallVector<int, 8> Mask;
4910 for (unsigned i = 0; i != NumElems; ++i)
4911 Mask.push_back(EltNo);
4913 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4919 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4920 /// vector of type 'VT', see if the elements can be replaced by a single large
4921 /// load which has the same value as a build_vector whose operands are 'elts'.
4923 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4925 /// FIXME: we'd also like to handle the case where the last elements are zero
4926 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4927 /// There's even a handy isZeroNode for that purpose.
4928 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4929 DebugLoc &DL, SelectionDAG &DAG) {
4930 EVT EltVT = VT.getVectorElementType();
4931 unsigned NumElems = Elts.size();
4933 LoadSDNode *LDBase = NULL;
4934 unsigned LastLoadedElt = -1U;
4936 // For each element in the initializer, see if we've found a load or an undef.
4937 // If we don't find an initial load element, or later load elements are
4938 // non-consecutive, bail out.
4939 for (unsigned i = 0; i < NumElems; ++i) {
4940 SDValue Elt = Elts[i];
4942 if (!Elt.getNode() ||
4943 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4946 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4948 LDBase = cast<LoadSDNode>(Elt.getNode());
4952 if (Elt.getOpcode() == ISD::UNDEF)
4955 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4956 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4961 // If we have found an entire vector of loads and undefs, then return a large
4962 // load of the entire vector width starting at the base pointer. If we found
4963 // consecutive loads for the low half, generate a vzext_load node.
4964 if (LastLoadedElt == NumElems - 1) {
4965 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4966 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4967 LDBase->getPointerInfo(),
4968 LDBase->isVolatile(), LDBase->isNonTemporal(),
4969 LDBase->isInvariant(), 0);
4970 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4971 LDBase->getPointerInfo(),
4972 LDBase->isVolatile(), LDBase->isNonTemporal(),
4973 LDBase->isInvariant(), LDBase->getAlignment());
4975 if (NumElems == 4 && LastLoadedElt == 1 &&
4976 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4977 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4978 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4980 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4981 LDBase->getPointerInfo(),
4982 LDBase->getAlignment(),
4983 false/*isVolatile*/, true/*ReadMem*/,
4986 // Make sure the newly-created LOAD is in the same position as LDBase in
4987 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4988 // update uses of LDBase's output chain to use the TokenFactor.
4989 if (LDBase->hasAnyUseOfValue(1)) {
4990 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4991 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4992 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4993 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4994 SDValue(ResNode.getNode(), 1));
4997 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5002 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5003 /// to generate a splat value for the following cases:
5004 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5005 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5006 /// a scalar load, or a constant.
5007 /// The VBROADCAST node is returned when a pattern is found,
5008 /// or SDValue() otherwise.
5010 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5011 if (!Subtarget->hasAVX())
5014 EVT VT = Op.getValueType();
5015 DebugLoc dl = Op.getDebugLoc();
5017 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5018 "Unsupported vector type for broadcast.");
5023 switch (Op.getOpcode()) {
5025 // Unknown pattern found.
5028 case ISD::BUILD_VECTOR: {
5029 // The BUILD_VECTOR node must be a splat.
5030 if (!isSplatVector(Op.getNode()))
5033 Ld = Op.getOperand(0);
5034 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5035 Ld.getOpcode() == ISD::ConstantFP);
5037 // The suspected load node has several users. Make sure that all
5038 // of its users are from the BUILD_VECTOR node.
5039 // Constants may have multiple users.
5040 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5045 case ISD::VECTOR_SHUFFLE: {
5046 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5048 // Shuffles must have a splat mask where the first element is
5050 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5053 SDValue Sc = Op.getOperand(0);
5054 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5055 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5057 if (!Subtarget->hasAVX2())
5060 // Use the register form of the broadcast instruction available on AVX2.
5061 if (VT.is256BitVector())
5062 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5063 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5066 Ld = Sc.getOperand(0);
5067 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5068 Ld.getOpcode() == ISD::ConstantFP);
5070 // The scalar_to_vector node and the suspected
5071 // load node must have exactly one user.
5072 // Constants may have multiple users.
5073 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5079 bool Is256 = VT.is256BitVector();
5081 // Handle the broadcasting a single constant scalar from the constant pool
5082 // into a vector. On Sandybridge it is still better to load a constant vector
5083 // from the constant pool and not to broadcast it from a scalar.
5084 if (ConstSplatVal && Subtarget->hasAVX2()) {
5085 EVT CVT = Ld.getValueType();
5086 assert(!CVT.isVector() && "Must not broadcast a vector type");
5087 unsigned ScalarSize = CVT.getSizeInBits();
5089 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5090 const Constant *C = 0;
5091 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5092 C = CI->getConstantIntValue();
5093 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5094 C = CF->getConstantFPValue();
5096 assert(C && "Invalid constant type");
5098 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5099 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5100 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5101 MachinePointerInfo::getConstantPool(),
5102 false, false, false, Alignment);
5104 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5108 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5109 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5111 // Handle AVX2 in-register broadcasts.
5112 if (!IsLoad && Subtarget->hasAVX2() &&
5113 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5114 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5116 // The scalar source must be a normal load.
5120 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5121 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5123 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5124 // double since there is no vbroadcastsd xmm
5125 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5126 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5127 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5130 // Unsupported broadcast.
5134 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5135 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5136 // constraint of matching input/output vector elements.
5138 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5139 DebugLoc DL = Op.getDebugLoc();
5140 SDNode *N = Op.getNode();
5141 EVT VT = Op.getValueType();
5142 unsigned NumElts = Op.getNumOperands();
5144 // Check supported types and sub-targets.
5146 // Only v2f32 -> v2f64 needs special handling.
5147 if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5152 SmallVector<int, 8> Mask;
5153 EVT SrcVT = MVT::Other;
5155 // Check the patterns could be translated into X86vfpext.
5156 for (unsigned i = 0; i < NumElts; ++i) {
5157 SDValue In = N->getOperand(i);
5158 unsigned Opcode = In.getOpcode();
5160 // Skip if the element is undefined.
5161 if (Opcode == ISD::UNDEF) {
5166 // Quit if one of the elements is not defined from 'fpext'.
5167 if (Opcode != ISD::FP_EXTEND)
5170 // Check how the source of 'fpext' is defined.
5171 SDValue L2In = In.getOperand(0);
5172 EVT L2InVT = L2In.getValueType();
5174 // Check the original type
5175 if (SrcVT == MVT::Other)
5177 else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5180 // Check whether the value being 'fpext'ed is extracted from the same
5182 Opcode = L2In.getOpcode();
5184 // Quit if it's not extracted with a constant index.
5185 if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5186 !isa<ConstantSDNode>(L2In.getOperand(1)))
5189 SDValue ExtractedFromVec = L2In.getOperand(0);
5191 if (VecIn.getNode() == 0) {
5192 VecIn = ExtractedFromVec;
5193 VecInVT = ExtractedFromVec.getValueType();
5194 } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5197 Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5200 // Quit if all operands of BUILD_VECTOR are undefined.
5201 if (!VecIn.getNode())
5204 // Fill the remaining mask as undef.
5205 for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5208 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5209 DAG.getVectorShuffle(VecInVT, DL,
5210 VecIn, DAG.getUNDEF(VecInVT),
5215 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5216 DebugLoc dl = Op.getDebugLoc();
5218 EVT VT = Op.getValueType();
5219 EVT ExtVT = VT.getVectorElementType();
5220 unsigned NumElems = Op.getNumOperands();
5222 // Vectors containing all zeros can be matched by pxor and xorps later
5223 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5224 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5225 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5226 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5229 return getZeroVector(VT, Subtarget, DAG, dl);
5232 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5233 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5234 // vpcmpeqd on 256-bit vectors.
5235 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5236 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5239 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5242 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5243 if (Broadcast.getNode())
5246 SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5247 if (FpExt.getNode())
5250 unsigned EVTBits = ExtVT.getSizeInBits();
5252 unsigned NumZero = 0;
5253 unsigned NumNonZero = 0;
5254 unsigned NonZeros = 0;
5255 bool IsAllConstants = true;
5256 SmallSet<SDValue, 8> Values;
5257 for (unsigned i = 0; i < NumElems; ++i) {
5258 SDValue Elt = Op.getOperand(i);
5259 if (Elt.getOpcode() == ISD::UNDEF)
5262 if (Elt.getOpcode() != ISD::Constant &&
5263 Elt.getOpcode() != ISD::ConstantFP)
5264 IsAllConstants = false;
5265 if (X86::isZeroNode(Elt))
5268 NonZeros |= (1 << i);
5273 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5274 if (NumNonZero == 0)
5275 return DAG.getUNDEF(VT);
5277 // Special case for single non-zero, non-undef, element.
5278 if (NumNonZero == 1) {
5279 unsigned Idx = CountTrailingZeros_32(NonZeros);
5280 SDValue Item = Op.getOperand(Idx);
5282 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5283 // the value are obviously zero, truncate the value to i32 and do the
5284 // insertion that way. Only do this if the value is non-constant or if the
5285 // value is a constant being inserted into element 0. It is cheaper to do
5286 // a constant pool load than it is to do a movd + shuffle.
5287 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5288 (!IsAllConstants || Idx == 0)) {
5289 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5291 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5292 EVT VecVT = MVT::v4i32;
5293 unsigned VecElts = 4;
5295 // Truncate the value (which may itself be a constant) to i32, and
5296 // convert it to a vector with movd (S2V+shuffle to zero extend).
5297 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5298 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5299 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5301 // Now we have our 32-bit value zero extended in the low element of
5302 // a vector. If Idx != 0, swizzle it into place.
5304 SmallVector<int, 4> Mask;
5305 Mask.push_back(Idx);
5306 for (unsigned i = 1; i != VecElts; ++i)
5308 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5311 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5315 // If we have a constant or non-constant insertion into the low element of
5316 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5317 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5318 // depending on what the source datatype is.
5321 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5323 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5324 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5325 if (VT.is256BitVector()) {
5326 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5327 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5328 Item, DAG.getIntPtrConstant(0));
5330 assert(VT.is128BitVector() && "Expected an SSE value type!");
5331 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5332 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5333 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5336 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5337 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5338 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5339 if (VT.is256BitVector()) {
5340 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5341 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5343 assert(VT.is128BitVector() && "Expected an SSE value type!");
5344 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5346 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5350 // Is it a vector logical left shift?
5351 if (NumElems == 2 && Idx == 1 &&
5352 X86::isZeroNode(Op.getOperand(0)) &&
5353 !X86::isZeroNode(Op.getOperand(1))) {
5354 unsigned NumBits = VT.getSizeInBits();
5355 return getVShift(true, VT,
5356 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5357 VT, Op.getOperand(1)),
5358 NumBits/2, DAG, *this, dl);
5361 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5364 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5365 // is a non-constant being inserted into an element other than the low one,
5366 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5367 // movd/movss) to move this into the low element, then shuffle it into
5369 if (EVTBits == 32) {
5370 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5372 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5373 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5374 SmallVector<int, 8> MaskVec;
5375 for (unsigned i = 0; i != NumElems; ++i)
5376 MaskVec.push_back(i == Idx ? 0 : 1);
5377 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5381 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5382 if (Values.size() == 1) {
5383 if (EVTBits == 32) {
5384 // Instead of a shuffle like this:
5385 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5386 // Check if it's possible to issue this instead.
5387 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5388 unsigned Idx = CountTrailingZeros_32(NonZeros);
5389 SDValue Item = Op.getOperand(Idx);
5390 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5391 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5396 // A vector full of immediates; various special cases are already
5397 // handled, so this is best done with a single constant-pool load.
5401 // For AVX-length vectors, build the individual 128-bit pieces and use
5402 // shuffles to put them in place.
5403 if (VT.is256BitVector()) {
5404 SmallVector<SDValue, 32> V;
5405 for (unsigned i = 0; i != NumElems; ++i)
5406 V.push_back(Op.getOperand(i));
5408 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5410 // Build both the lower and upper subvector.
5411 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5412 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5415 // Recreate the wider vector with the lower and upper part.
5416 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5419 // Let legalizer expand 2-wide build_vectors.
5420 if (EVTBits == 64) {
5421 if (NumNonZero == 1) {
5422 // One half is zero or undef.
5423 unsigned Idx = CountTrailingZeros_32(NonZeros);
5424 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5425 Op.getOperand(Idx));
5426 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5431 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5432 if (EVTBits == 8 && NumElems == 16) {
5433 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5435 if (V.getNode()) return V;
5438 if (EVTBits == 16 && NumElems == 8) {
5439 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5441 if (V.getNode()) return V;
5444 // If element VT is == 32 bits, turn it into a number of shuffles.
5445 SmallVector<SDValue, 8> V(NumElems);
5446 if (NumElems == 4 && NumZero > 0) {
5447 for (unsigned i = 0; i < 4; ++i) {
5448 bool isZero = !(NonZeros & (1 << i));
5450 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5452 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5455 for (unsigned i = 0; i < 2; ++i) {
5456 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5459 V[i] = V[i*2]; // Must be a zero vector.
5462 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5465 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5468 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5473 bool Reverse1 = (NonZeros & 0x3) == 2;
5474 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5478 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5479 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5481 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5484 if (Values.size() > 1 && VT.is128BitVector()) {
5485 // Check for a build vector of consecutive loads.
5486 for (unsigned i = 0; i < NumElems; ++i)
5487 V[i] = Op.getOperand(i);
5489 // Check for elements which are consecutive loads.
5490 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5494 // For SSE 4.1, use insertps to put the high elements into the low element.
5495 if (getSubtarget()->hasSSE41()) {
5497 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5498 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5500 Result = DAG.getUNDEF(VT);
5502 for (unsigned i = 1; i < NumElems; ++i) {
5503 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5504 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5505 Op.getOperand(i), DAG.getIntPtrConstant(i));
5510 // Otherwise, expand into a number of unpckl*, start by extending each of
5511 // our (non-undef) elements to the full vector width with the element in the
5512 // bottom slot of the vector (which generates no code for SSE).
5513 for (unsigned i = 0; i < NumElems; ++i) {
5514 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5515 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5517 V[i] = DAG.getUNDEF(VT);
5520 // Next, we iteratively mix elements, e.g. for v4f32:
5521 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5522 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5523 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5524 unsigned EltStride = NumElems >> 1;
5525 while (EltStride != 0) {
5526 for (unsigned i = 0; i < EltStride; ++i) {
5527 // If V[i+EltStride] is undef and this is the first round of mixing,
5528 // then it is safe to just drop this shuffle: V[i] is already in the
5529 // right place, the one element (since it's the first round) being
5530 // inserted as undef can be dropped. This isn't safe for successive
5531 // rounds because they will permute elements within both vectors.
5532 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5533 EltStride == NumElems/2)
5536 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5545 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5546 // to create 256-bit vectors from two other 128-bit ones.
5547 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5548 DebugLoc dl = Op.getDebugLoc();
5549 EVT ResVT = Op.getValueType();
5551 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5553 SDValue V1 = Op.getOperand(0);
5554 SDValue V2 = Op.getOperand(1);
5555 unsigned NumElems = ResVT.getVectorNumElements();
5557 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5561 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5562 assert(Op.getNumOperands() == 2);
5564 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5565 // from two other 128-bit ones.
5566 return LowerAVXCONCAT_VECTORS(Op, DAG);
5569 // Try to lower a shuffle node into a simple blend instruction.
5570 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5571 const X86Subtarget *Subtarget,
5572 SelectionDAG &DAG) {
5573 SDValue V1 = SVOp->getOperand(0);
5574 SDValue V2 = SVOp->getOperand(1);
5575 DebugLoc dl = SVOp->getDebugLoc();
5576 MVT VT = SVOp->getValueType(0).getSimpleVT();
5577 unsigned NumElems = VT.getVectorNumElements();
5579 if (!Subtarget->hasSSE41())
5585 switch (VT.SimpleTy) {
5586 default: return SDValue();
5588 ISDNo = X86ISD::BLENDPW;
5593 ISDNo = X86ISD::BLENDPS;
5598 ISDNo = X86ISD::BLENDPD;
5603 if (!Subtarget->hasAVX())
5605 ISDNo = X86ISD::BLENDPS;
5610 if (!Subtarget->hasAVX())
5612 ISDNo = X86ISD::BLENDPD;
5616 assert(ISDNo && "Invalid Op Number");
5618 unsigned MaskVals = 0;
5620 for (unsigned i = 0; i != NumElems; ++i) {
5621 int EltIdx = SVOp->getMaskElt(i);
5622 if (EltIdx == (int)i || EltIdx < 0)
5624 else if (EltIdx == (int)(i + NumElems))
5625 continue; // Bit is set to zero;
5630 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5631 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5632 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5633 DAG.getConstant(MaskVals, MVT::i32));
5634 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5637 // v8i16 shuffles - Prefer shuffles in the following order:
5638 // 1. [all] pshuflw, pshufhw, optional move
5639 // 2. [ssse3] 1 x pshufb
5640 // 3. [ssse3] 2 x pshufb + 1 x por
5641 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5643 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5644 SelectionDAG &DAG) const {
5645 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5646 SDValue V1 = SVOp->getOperand(0);
5647 SDValue V2 = SVOp->getOperand(1);
5648 DebugLoc dl = SVOp->getDebugLoc();
5649 SmallVector<int, 8> MaskVals;
5651 // Determine if more than 1 of the words in each of the low and high quadwords
5652 // of the result come from the same quadword of one of the two inputs. Undef
5653 // mask values count as coming from any quadword, for better codegen.
5654 unsigned LoQuad[] = { 0, 0, 0, 0 };
5655 unsigned HiQuad[] = { 0, 0, 0, 0 };
5656 std::bitset<4> InputQuads;
5657 for (unsigned i = 0; i < 8; ++i) {
5658 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5659 int EltIdx = SVOp->getMaskElt(i);
5660 MaskVals.push_back(EltIdx);
5669 InputQuads.set(EltIdx / 4);
5672 int BestLoQuad = -1;
5673 unsigned MaxQuad = 1;
5674 for (unsigned i = 0; i < 4; ++i) {
5675 if (LoQuad[i] > MaxQuad) {
5677 MaxQuad = LoQuad[i];
5681 int BestHiQuad = -1;
5683 for (unsigned i = 0; i < 4; ++i) {
5684 if (HiQuad[i] > MaxQuad) {
5686 MaxQuad = HiQuad[i];
5690 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5691 // of the two input vectors, shuffle them into one input vector so only a
5692 // single pshufb instruction is necessary. If There are more than 2 input
5693 // quads, disable the next transformation since it does not help SSSE3.
5694 bool V1Used = InputQuads[0] || InputQuads[1];
5695 bool V2Used = InputQuads[2] || InputQuads[3];
5696 if (Subtarget->hasSSSE3()) {
5697 if (InputQuads.count() == 2 && V1Used && V2Used) {
5698 BestLoQuad = InputQuads[0] ? 0 : 1;
5699 BestHiQuad = InputQuads[2] ? 2 : 3;
5701 if (InputQuads.count() > 2) {
5707 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5708 // the shuffle mask. If a quad is scored as -1, that means that it contains
5709 // words from all 4 input quadwords.
5711 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5713 BestLoQuad < 0 ? 0 : BestLoQuad,
5714 BestHiQuad < 0 ? 1 : BestHiQuad
5716 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5717 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5718 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5719 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5721 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5722 // source words for the shuffle, to aid later transformations.
5723 bool AllWordsInNewV = true;
5724 bool InOrder[2] = { true, true };
5725 for (unsigned i = 0; i != 8; ++i) {
5726 int idx = MaskVals[i];
5728 InOrder[i/4] = false;
5729 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5731 AllWordsInNewV = false;
5735 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5736 if (AllWordsInNewV) {
5737 for (int i = 0; i != 8; ++i) {
5738 int idx = MaskVals[i];
5741 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5742 if ((idx != i) && idx < 4)
5744 if ((idx != i) && idx > 3)
5753 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5754 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5755 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5756 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5757 unsigned TargetMask = 0;
5758 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5759 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5760 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5761 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5762 getShufflePSHUFLWImmediate(SVOp);
5763 V1 = NewV.getOperand(0);
5764 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5768 // If we have SSSE3, and all words of the result are from 1 input vector,
5769 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5770 // is present, fall back to case 4.
5771 if (Subtarget->hasSSSE3()) {
5772 SmallVector<SDValue,16> pshufbMask;
5774 // If we have elements from both input vectors, set the high bit of the
5775 // shuffle mask element to zero out elements that come from V2 in the V1
5776 // mask, and elements that come from V1 in the V2 mask, so that the two
5777 // results can be OR'd together.
5778 bool TwoInputs = V1Used && V2Used;
5779 for (unsigned i = 0; i != 8; ++i) {
5780 int EltIdx = MaskVals[i] * 2;
5781 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5782 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5783 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5784 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5786 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5787 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5788 DAG.getNode(ISD::BUILD_VECTOR, dl,
5789 MVT::v16i8, &pshufbMask[0], 16));
5791 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5793 // Calculate the shuffle mask for the second input, shuffle it, and
5794 // OR it with the first shuffled input.
5796 for (unsigned i = 0; i != 8; ++i) {
5797 int EltIdx = MaskVals[i] * 2;
5798 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5799 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5800 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5801 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5803 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5804 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5805 DAG.getNode(ISD::BUILD_VECTOR, dl,
5806 MVT::v16i8, &pshufbMask[0], 16));
5807 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5808 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5811 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5812 // and update MaskVals with new element order.
5813 std::bitset<8> InOrder;
5814 if (BestLoQuad >= 0) {
5815 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5816 for (int i = 0; i != 4; ++i) {
5817 int idx = MaskVals[i];
5820 } else if ((idx / 4) == BestLoQuad) {
5825 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5828 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5829 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5830 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5832 getShufflePSHUFLWImmediate(SVOp), DAG);
5836 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5837 // and update MaskVals with the new element order.
5838 if (BestHiQuad >= 0) {
5839 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5840 for (unsigned i = 4; i != 8; ++i) {
5841 int idx = MaskVals[i];
5844 } else if ((idx / 4) == BestHiQuad) {
5845 MaskV[i] = (idx & 3) + 4;
5849 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5852 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5853 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5854 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5856 getShufflePSHUFHWImmediate(SVOp), DAG);
5860 // In case BestHi & BestLo were both -1, which means each quadword has a word
5861 // from each of the four input quadwords, calculate the InOrder bitvector now
5862 // before falling through to the insert/extract cleanup.
5863 if (BestLoQuad == -1 && BestHiQuad == -1) {
5865 for (int i = 0; i != 8; ++i)
5866 if (MaskVals[i] < 0 || MaskVals[i] == i)
5870 // The other elements are put in the right place using pextrw and pinsrw.
5871 for (unsigned i = 0; i != 8; ++i) {
5874 int EltIdx = MaskVals[i];
5877 SDValue ExtOp = (EltIdx < 8) ?
5878 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5879 DAG.getIntPtrConstant(EltIdx)) :
5880 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5881 DAG.getIntPtrConstant(EltIdx - 8));
5882 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5883 DAG.getIntPtrConstant(i));
5888 // v16i8 shuffles - Prefer shuffles in the following order:
5889 // 1. [ssse3] 1 x pshufb
5890 // 2. [ssse3] 2 x pshufb + 1 x por
5891 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5893 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5895 const X86TargetLowering &TLI) {
5896 SDValue V1 = SVOp->getOperand(0);
5897 SDValue V2 = SVOp->getOperand(1);
5898 DebugLoc dl = SVOp->getDebugLoc();
5899 ArrayRef<int> MaskVals = SVOp->getMask();
5901 // If we have SSSE3, case 1 is generated when all result bytes come from
5902 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5903 // present, fall back to case 3.
5905 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5906 if (TLI.getSubtarget()->hasSSSE3()) {
5907 SmallVector<SDValue,16> pshufbMask;
5909 // If all result elements are from one input vector, then only translate
5910 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5912 // Otherwise, we have elements from both input vectors, and must zero out
5913 // elements that come from V2 in the first mask, and V1 in the second mask
5914 // so that we can OR them together.
5915 for (unsigned i = 0; i != 16; ++i) {
5916 int EltIdx = MaskVals[i];
5917 if (EltIdx < 0 || EltIdx >= 16)
5919 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5921 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5922 DAG.getNode(ISD::BUILD_VECTOR, dl,
5923 MVT::v16i8, &pshufbMask[0], 16));
5925 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5926 // the 2nd operand if it's undefined or zero.
5927 if (V2.getOpcode() == ISD::UNDEF ||
5928 ISD::isBuildVectorAllZeros(V2.getNode()))
5931 // Calculate the shuffle mask for the second input, shuffle it, and
5932 // OR it with the first shuffled input.
5934 for (unsigned i = 0; i != 16; ++i) {
5935 int EltIdx = MaskVals[i];
5936 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5937 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5939 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5940 DAG.getNode(ISD::BUILD_VECTOR, dl,
5941 MVT::v16i8, &pshufbMask[0], 16));
5942 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5945 // No SSSE3 - Calculate in place words and then fix all out of place words
5946 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5947 // the 16 different words that comprise the two doublequadword input vectors.
5948 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5949 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5951 for (int i = 0; i != 8; ++i) {
5952 int Elt0 = MaskVals[i*2];
5953 int Elt1 = MaskVals[i*2+1];
5955 // This word of the result is all undef, skip it.
5956 if (Elt0 < 0 && Elt1 < 0)
5959 // This word of the result is already in the correct place, skip it.
5960 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5963 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5964 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5967 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5968 // using a single extract together, load it and store it.
5969 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5970 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5971 DAG.getIntPtrConstant(Elt1 / 2));
5972 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5973 DAG.getIntPtrConstant(i));
5977 // If Elt1 is defined, extract it from the appropriate source. If the
5978 // source byte is not also odd, shift the extracted word left 8 bits
5979 // otherwise clear the bottom 8 bits if we need to do an or.
5981 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5982 DAG.getIntPtrConstant(Elt1 / 2));
5983 if ((Elt1 & 1) == 0)
5984 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5986 TLI.getShiftAmountTy(InsElt.getValueType())));
5988 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5989 DAG.getConstant(0xFF00, MVT::i16));
5991 // If Elt0 is defined, extract it from the appropriate source. If the
5992 // source byte is not also even, shift the extracted word right 8 bits. If
5993 // Elt1 was also defined, OR the extracted values together before
5994 // inserting them in the result.
5996 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5997 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5998 if ((Elt0 & 1) != 0)
5999 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6001 TLI.getShiftAmountTy(InsElt0.getValueType())));
6003 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6004 DAG.getConstant(0x00FF, MVT::i16));
6005 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6008 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6009 DAG.getIntPtrConstant(i));
6011 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6014 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6015 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6016 /// done when every pair / quad of shuffle mask elements point to elements in
6017 /// the right sequence. e.g.
6018 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6020 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6021 SelectionDAG &DAG, DebugLoc dl) {
6022 MVT VT = SVOp->getValueType(0).getSimpleVT();
6023 unsigned NumElems = VT.getVectorNumElements();
6026 switch (VT.SimpleTy) {
6027 default: llvm_unreachable("Unexpected!");
6028 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6029 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6030 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6031 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6032 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6033 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6036 SmallVector<int, 8> MaskVec;
6037 for (unsigned i = 0; i != NumElems; i += Scale) {
6039 for (unsigned j = 0; j != Scale; ++j) {
6040 int EltIdx = SVOp->getMaskElt(i+j);
6044 StartIdx = (EltIdx / Scale);
6045 if (EltIdx != (int)(StartIdx*Scale + j))
6048 MaskVec.push_back(StartIdx);
6051 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6052 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6053 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6056 /// getVZextMovL - Return a zero-extending vector move low node.
6058 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6059 SDValue SrcOp, SelectionDAG &DAG,
6060 const X86Subtarget *Subtarget, DebugLoc dl) {
6061 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6062 LoadSDNode *LD = NULL;
6063 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6064 LD = dyn_cast<LoadSDNode>(SrcOp);
6066 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6068 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6069 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6070 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6071 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6072 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6074 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6075 return DAG.getNode(ISD::BITCAST, dl, VT,
6076 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6077 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6085 return DAG.getNode(ISD::BITCAST, dl, VT,
6086 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6087 DAG.getNode(ISD::BITCAST, dl,
6091 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6092 /// which could not be matched by any known target speficic shuffle
6094 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6096 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6097 if (NewOp.getNode())
6100 EVT VT = SVOp->getValueType(0);
6102 unsigned NumElems = VT.getVectorNumElements();
6103 unsigned NumLaneElems = NumElems / 2;
6105 DebugLoc dl = SVOp->getDebugLoc();
6106 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6107 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6110 SmallVector<int, 16> Mask;
6111 for (unsigned l = 0; l < 2; ++l) {
6112 // Build a shuffle mask for the output, discovering on the fly which
6113 // input vectors to use as shuffle operands (recorded in InputUsed).
6114 // If building a suitable shuffle vector proves too hard, then bail
6115 // out with UseBuildVector set.
6116 bool UseBuildVector = false;
6117 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6118 unsigned LaneStart = l * NumLaneElems;
6119 for (unsigned i = 0; i != NumLaneElems; ++i) {
6120 // The mask element. This indexes into the input.
6121 int Idx = SVOp->getMaskElt(i+LaneStart);
6123 // the mask element does not index into any input vector.
6128 // The input vector this mask element indexes into.
6129 int Input = Idx / NumLaneElems;
6131 // Turn the index into an offset from the start of the input vector.
6132 Idx -= Input * NumLaneElems;
6134 // Find or create a shuffle vector operand to hold this input.
6136 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6137 if (InputUsed[OpNo] == Input)
6138 // This input vector is already an operand.
6140 if (InputUsed[OpNo] < 0) {
6141 // Create a new operand for this input vector.
6142 InputUsed[OpNo] = Input;
6147 if (OpNo >= array_lengthof(InputUsed)) {
6148 // More than two input vectors used! Give up on trying to create a
6149 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6150 UseBuildVector = true;
6154 // Add the mask index for the new shuffle vector.
6155 Mask.push_back(Idx + OpNo * NumLaneElems);
6158 if (UseBuildVector) {
6159 SmallVector<SDValue, 16> SVOps;
6160 for (unsigned i = 0; i != NumLaneElems; ++i) {
6161 // The mask element. This indexes into the input.
6162 int Idx = SVOp->getMaskElt(i+LaneStart);
6164 SVOps.push_back(DAG.getUNDEF(EltVT));
6168 // The input vector this mask element indexes into.
6169 int Input = Idx / NumElems;
6171 // Turn the index into an offset from the start of the input vector.
6172 Idx -= Input * NumElems;
6174 // Extract the vector element by hand.
6175 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6176 SVOp->getOperand(Input),
6177 DAG.getIntPtrConstant(Idx)));
6180 // Construct the output using a BUILD_VECTOR.
6181 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6183 } else if (InputUsed[0] < 0) {
6184 // No input vectors were used! The result is undefined.
6185 Output[l] = DAG.getUNDEF(NVT);
6187 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6188 (InputUsed[0] % 2) * NumLaneElems,
6190 // If only one input was used, use an undefined vector for the other.
6191 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6192 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6193 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6194 // At least one input vector was used. Create a new shuffle vector.
6195 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6201 // Concatenate the result back
6202 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6205 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6206 /// 4 elements, and match them with several different shuffle types.
6208 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6209 SDValue V1 = SVOp->getOperand(0);
6210 SDValue V2 = SVOp->getOperand(1);
6211 DebugLoc dl = SVOp->getDebugLoc();
6212 EVT VT = SVOp->getValueType(0);
6214 assert(VT.is128BitVector() && "Unsupported vector size");
6216 std::pair<int, int> Locs[4];
6217 int Mask1[] = { -1, -1, -1, -1 };
6218 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6222 for (unsigned i = 0; i != 4; ++i) {
6223 int Idx = PermMask[i];
6225 Locs[i] = std::make_pair(-1, -1);
6227 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6229 Locs[i] = std::make_pair(0, NumLo);
6233 Locs[i] = std::make_pair(1, NumHi);
6235 Mask1[2+NumHi] = Idx;
6241 if (NumLo <= 2 && NumHi <= 2) {
6242 // If no more than two elements come from either vector. This can be
6243 // implemented with two shuffles. First shuffle gather the elements.
6244 // The second shuffle, which takes the first shuffle as both of its
6245 // vector operands, put the elements into the right order.
6246 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6248 int Mask2[] = { -1, -1, -1, -1 };
6250 for (unsigned i = 0; i != 4; ++i)
6251 if (Locs[i].first != -1) {
6252 unsigned Idx = (i < 2) ? 0 : 4;
6253 Idx += Locs[i].first * 2 + Locs[i].second;
6257 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6260 if (NumLo == 3 || NumHi == 3) {
6261 // Otherwise, we must have three elements from one vector, call it X, and
6262 // one element from the other, call it Y. First, use a shufps to build an
6263 // intermediate vector with the one element from Y and the element from X
6264 // that will be in the same half in the final destination (the indexes don't
6265 // matter). Then, use a shufps to build the final vector, taking the half
6266 // containing the element from Y from the intermediate, and the other half
6269 // Normalize it so the 3 elements come from V1.
6270 CommuteVectorShuffleMask(PermMask, 4);
6274 // Find the element from V2.
6276 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6277 int Val = PermMask[HiIndex];
6284 Mask1[0] = PermMask[HiIndex];
6286 Mask1[2] = PermMask[HiIndex^1];
6288 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6291 Mask1[0] = PermMask[0];
6292 Mask1[1] = PermMask[1];
6293 Mask1[2] = HiIndex & 1 ? 6 : 4;
6294 Mask1[3] = HiIndex & 1 ? 4 : 6;
6295 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6298 Mask1[0] = HiIndex & 1 ? 2 : 0;
6299 Mask1[1] = HiIndex & 1 ? 0 : 2;
6300 Mask1[2] = PermMask[2];
6301 Mask1[3] = PermMask[3];
6306 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6309 // Break it into (shuffle shuffle_hi, shuffle_lo).
6310 int LoMask[] = { -1, -1, -1, -1 };
6311 int HiMask[] = { -1, -1, -1, -1 };
6313 int *MaskPtr = LoMask;
6314 unsigned MaskIdx = 0;
6317 for (unsigned i = 0; i != 4; ++i) {
6324 int Idx = PermMask[i];
6326 Locs[i] = std::make_pair(-1, -1);
6327 } else if (Idx < 4) {
6328 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6329 MaskPtr[LoIdx] = Idx;
6332 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6333 MaskPtr[HiIdx] = Idx;
6338 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6339 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6340 int MaskOps[] = { -1, -1, -1, -1 };
6341 for (unsigned i = 0; i != 4; ++i)
6342 if (Locs[i].first != -1)
6343 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6344 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6347 static bool MayFoldVectorLoad(SDValue V) {
6348 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6349 V = V.getOperand(0);
6350 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6351 V = V.getOperand(0);
6352 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6353 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6354 // BUILD_VECTOR (load), undef
6355 V = V.getOperand(0);
6361 // FIXME: the version above should always be used. Since there's
6362 // a bug where several vector shuffles can't be folded because the
6363 // DAG is not updated during lowering and a node claims to have two
6364 // uses while it only has one, use this version, and let isel match
6365 // another instruction if the load really happens to have more than
6366 // one use. Remove this version after this bug get fixed.
6367 // rdar://8434668, PR8156
6368 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6369 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6370 V = V.getOperand(0);
6371 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6372 V = V.getOperand(0);
6373 if (ISD::isNormalLoad(V.getNode()))
6379 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6380 EVT VT = Op.getValueType();
6382 // Canonizalize to v2f64.
6383 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6384 return DAG.getNode(ISD::BITCAST, dl, VT,
6385 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6390 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6392 SDValue V1 = Op.getOperand(0);
6393 SDValue V2 = Op.getOperand(1);
6394 EVT VT = Op.getValueType();
6396 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6398 if (HasSSE2 && VT == MVT::v2f64)
6399 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6401 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6402 return DAG.getNode(ISD::BITCAST, dl, VT,
6403 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6404 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6405 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6409 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6410 SDValue V1 = Op.getOperand(0);
6411 SDValue V2 = Op.getOperand(1);
6412 EVT VT = Op.getValueType();
6414 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6415 "unsupported shuffle type");
6417 if (V2.getOpcode() == ISD::UNDEF)
6421 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6425 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6426 SDValue V1 = Op.getOperand(0);
6427 SDValue V2 = Op.getOperand(1);
6428 EVT VT = Op.getValueType();
6429 unsigned NumElems = VT.getVectorNumElements();
6431 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6432 // operand of these instructions is only memory, so check if there's a
6433 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6435 bool CanFoldLoad = false;
6437 // Trivial case, when V2 comes from a load.
6438 if (MayFoldVectorLoad(V2))
6441 // When V1 is a load, it can be folded later into a store in isel, example:
6442 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6444 // (MOVLPSmr addr:$src1, VR128:$src2)
6445 // So, recognize this potential and also use MOVLPS or MOVLPD
6446 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6449 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6451 if (HasSSE2 && NumElems == 2)
6452 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6455 // If we don't care about the second element, proceed to use movss.
6456 if (SVOp->getMaskElt(1) != -1)
6457 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6460 // movl and movlp will both match v2i64, but v2i64 is never matched by
6461 // movl earlier because we make it strict to avoid messing with the movlp load
6462 // folding logic (see the code above getMOVLP call). Match it here then,
6463 // this is horrible, but will stay like this until we move all shuffle
6464 // matching to x86 specific nodes. Note that for the 1st condition all
6465 // types are matched with movsd.
6467 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6468 // as to remove this logic from here, as much as possible
6469 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6470 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6471 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6474 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6476 // Invert the operand order and use SHUFPS to match it.
6477 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6478 getShuffleSHUFImmediate(SVOp), DAG);
6482 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6483 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6484 EVT VT = Op.getValueType();
6485 DebugLoc dl = Op.getDebugLoc();
6486 SDValue V1 = Op.getOperand(0);
6487 SDValue V2 = Op.getOperand(1);
6489 if (isZeroShuffle(SVOp))
6490 return getZeroVector(VT, Subtarget, DAG, dl);
6492 // Handle splat operations
6493 if (SVOp->isSplat()) {
6494 unsigned NumElem = VT.getVectorNumElements();
6495 int Size = VT.getSizeInBits();
6497 // Use vbroadcast whenever the splat comes from a foldable load
6498 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6499 if (Broadcast.getNode())
6502 // Handle splats by matching through known shuffle masks
6503 if ((Size == 128 && NumElem <= 4) ||
6504 (Size == 256 && NumElem < 8))
6507 // All remaning splats are promoted to target supported vector shuffles.
6508 return PromoteSplat(SVOp, DAG);
6511 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6513 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6514 VT == MVT::v16i16 || VT == MVT::v32i8) {
6515 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6516 if (NewOp.getNode())
6517 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6518 } else if ((VT == MVT::v4i32 ||
6519 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6520 // FIXME: Figure out a cleaner way to do this.
6521 // Try to make use of movq to zero out the top part.
6522 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6523 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6524 if (NewOp.getNode()) {
6525 EVT NewVT = NewOp.getValueType();
6526 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6527 NewVT, true, false))
6528 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6529 DAG, Subtarget, dl);
6531 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6532 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6533 if (NewOp.getNode()) {
6534 EVT NewVT = NewOp.getValueType();
6535 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6536 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6537 DAG, Subtarget, dl);
6545 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6546 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6547 SDValue V1 = Op.getOperand(0);
6548 SDValue V2 = Op.getOperand(1);
6549 EVT VT = Op.getValueType();
6550 DebugLoc dl = Op.getDebugLoc();
6551 unsigned NumElems = VT.getVectorNumElements();
6552 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6553 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6554 bool V1IsSplat = false;
6555 bool V2IsSplat = false;
6556 bool HasSSE2 = Subtarget->hasSSE2();
6557 bool HasAVX = Subtarget->hasAVX();
6558 bool HasAVX2 = Subtarget->hasAVX2();
6559 MachineFunction &MF = DAG.getMachineFunction();
6560 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6562 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6564 if (V1IsUndef && V2IsUndef)
6565 return DAG.getUNDEF(VT);
6567 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6569 // Vector shuffle lowering takes 3 steps:
6571 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6572 // narrowing and commutation of operands should be handled.
6573 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6575 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6576 // so the shuffle can be broken into other shuffles and the legalizer can
6577 // try the lowering again.
6579 // The general idea is that no vector_shuffle operation should be left to
6580 // be matched during isel, all of them must be converted to a target specific
6583 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6584 // narrowing and commutation of operands should be handled. The actual code
6585 // doesn't include all of those, work in progress...
6586 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6587 if (NewOp.getNode())
6590 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6592 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6593 // unpckh_undef). Only use pshufd if speed is more important than size.
6594 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6595 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6596 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6597 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6599 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6600 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6601 return getMOVDDup(Op, dl, V1, DAG);
6603 if (isMOVHLPS_v_undef_Mask(M, VT))
6604 return getMOVHighToLow(Op, dl, DAG);
6606 // Use to match splats
6607 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6608 (VT == MVT::v2f64 || VT == MVT::v2i64))
6609 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6611 if (isPSHUFDMask(M, VT)) {
6612 // The actual implementation will match the mask in the if above and then
6613 // during isel it can match several different instructions, not only pshufd
6614 // as its name says, sad but true, emulate the behavior for now...
6615 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6616 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6618 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6620 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6621 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6623 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6624 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6626 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6630 // Check if this can be converted into a logical shift.
6631 bool isLeft = false;
6634 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6635 if (isShift && ShVal.hasOneUse()) {
6636 // If the shifted value has multiple uses, it may be cheaper to use
6637 // v_set0 + movlhps or movhlps, etc.
6638 EVT EltVT = VT.getVectorElementType();
6639 ShAmt *= EltVT.getSizeInBits();
6640 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6643 if (isMOVLMask(M, VT)) {
6644 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6645 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6646 if (!isMOVLPMask(M, VT)) {
6647 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6648 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6650 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6651 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6655 // FIXME: fold these into legal mask.
6656 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6657 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6659 if (isMOVHLPSMask(M, VT))
6660 return getMOVHighToLow(Op, dl, DAG);
6662 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6663 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6665 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6666 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6668 if (isMOVLPMask(M, VT))
6669 return getMOVLP(Op, dl, DAG, HasSSE2);
6671 if (ShouldXformToMOVHLPS(M, VT) ||
6672 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6673 return CommuteVectorShuffle(SVOp, DAG);
6676 // No better options. Use a vshldq / vsrldq.
6677 EVT EltVT = VT.getVectorElementType();
6678 ShAmt *= EltVT.getSizeInBits();
6679 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6682 bool Commuted = false;
6683 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6684 // 1,1,1,1 -> v8i16 though.
6685 V1IsSplat = isSplatVector(V1.getNode());
6686 V2IsSplat = isSplatVector(V2.getNode());
6688 // Canonicalize the splat or undef, if present, to be on the RHS.
6689 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6690 CommuteVectorShuffleMask(M, NumElems);
6692 std::swap(V1IsSplat, V2IsSplat);
6696 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6697 // Shuffling low element of v1 into undef, just return v1.
6700 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6701 // the instruction selector will not match, so get a canonical MOVL with
6702 // swapped operands to undo the commute.
6703 return getMOVL(DAG, dl, VT, V2, V1);
6706 if (isUNPCKLMask(M, VT, HasAVX2))
6707 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6709 if (isUNPCKHMask(M, VT, HasAVX2))
6710 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6713 // Normalize mask so all entries that point to V2 points to its first
6714 // element then try to match unpck{h|l} again. If match, return a
6715 // new vector_shuffle with the corrected mask.p
6716 SmallVector<int, 8> NewMask(M.begin(), M.end());
6717 NormalizeMask(NewMask, NumElems);
6718 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6719 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6720 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6721 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6725 // Commute is back and try unpck* again.
6726 // FIXME: this seems wrong.
6727 CommuteVectorShuffleMask(M, NumElems);
6729 std::swap(V1IsSplat, V2IsSplat);
6732 if (isUNPCKLMask(M, VT, HasAVX2))
6733 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6735 if (isUNPCKHMask(M, VT, HasAVX2))
6736 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6739 // Normalize the node to match x86 shuffle ops if needed
6740 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6741 return CommuteVectorShuffle(SVOp, DAG);
6743 // The checks below are all present in isShuffleMaskLegal, but they are
6744 // inlined here right now to enable us to directly emit target specific
6745 // nodes, and remove one by one until they don't return Op anymore.
6747 if (isPALIGNRMask(M, VT, Subtarget))
6748 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6749 getShufflePALIGNRImmediate(SVOp),
6752 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6753 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6754 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6755 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6758 if (isPSHUFHWMask(M, VT, HasAVX2))
6759 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6760 getShufflePSHUFHWImmediate(SVOp),
6763 if (isPSHUFLWMask(M, VT, HasAVX2))
6764 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6765 getShufflePSHUFLWImmediate(SVOp),
6768 if (isSHUFPMask(M, VT, HasAVX))
6769 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6770 getShuffleSHUFImmediate(SVOp), DAG);
6772 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6773 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6774 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6775 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6777 //===--------------------------------------------------------------------===//
6778 // Generate target specific nodes for 128 or 256-bit shuffles only
6779 // supported in the AVX instruction set.
6782 // Handle VMOVDDUPY permutations
6783 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6784 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6786 // Handle VPERMILPS/D* permutations
6787 if (isVPERMILPMask(M, VT, HasAVX)) {
6788 if (HasAVX2 && VT == MVT::v8i32)
6789 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6790 getShuffleSHUFImmediate(SVOp), DAG);
6791 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6792 getShuffleSHUFImmediate(SVOp), DAG);
6795 // Handle VPERM2F128/VPERM2I128 permutations
6796 if (isVPERM2X128Mask(M, VT, HasAVX))
6797 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6798 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6800 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6801 if (BlendOp.getNode())
6804 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6805 SmallVector<SDValue, 8> permclMask;
6806 for (unsigned i = 0; i != 8; ++i) {
6807 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6809 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6811 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6812 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6813 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6816 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6817 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6818 getShuffleCLImmediate(SVOp), DAG);
6821 //===--------------------------------------------------------------------===//
6822 // Since no target specific shuffle was selected for this generic one,
6823 // lower it into other known shuffles. FIXME: this isn't true yet, but
6824 // this is the plan.
6827 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6828 if (VT == MVT::v8i16) {
6829 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6830 if (NewOp.getNode())
6834 if (VT == MVT::v16i8) {
6835 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6836 if (NewOp.getNode())
6840 // Handle all 128-bit wide vectors with 4 elements, and match them with
6841 // several different shuffle types.
6842 if (NumElems == 4 && VT.is128BitVector())
6843 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6845 // Handle general 256-bit shuffles
6846 if (VT.is256BitVector())
6847 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6853 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6854 SelectionDAG &DAG) const {
6855 EVT VT = Op.getValueType();
6856 DebugLoc dl = Op.getDebugLoc();
6858 if (!Op.getOperand(0).getValueType().is128BitVector())
6861 if (VT.getSizeInBits() == 8) {
6862 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6863 Op.getOperand(0), Op.getOperand(1));
6864 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6865 DAG.getValueType(VT));
6866 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6869 if (VT.getSizeInBits() == 16) {
6870 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6871 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6873 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6874 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6875 DAG.getNode(ISD::BITCAST, dl,
6879 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6880 Op.getOperand(0), Op.getOperand(1));
6881 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6882 DAG.getValueType(VT));
6883 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6886 if (VT == MVT::f32) {
6887 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6888 // the result back to FR32 register. It's only worth matching if the
6889 // result has a single use which is a store or a bitcast to i32. And in
6890 // the case of a store, it's not worth it if the index is a constant 0,
6891 // because a MOVSSmr can be used instead, which is smaller and faster.
6892 if (!Op.hasOneUse())
6894 SDNode *User = *Op.getNode()->use_begin();
6895 if ((User->getOpcode() != ISD::STORE ||
6896 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6897 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6898 (User->getOpcode() != ISD::BITCAST ||
6899 User->getValueType(0) != MVT::i32))
6901 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6902 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6905 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6908 if (VT == MVT::i32 || VT == MVT::i64) {
6909 // ExtractPS/pextrq works with constant index.
6910 if (isa<ConstantSDNode>(Op.getOperand(1)))
6918 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6919 SelectionDAG &DAG) const {
6920 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6923 SDValue Vec = Op.getOperand(0);
6924 EVT VecVT = Vec.getValueType();
6926 // If this is a 256-bit vector result, first extract the 128-bit vector and
6927 // then extract the element from the 128-bit vector.
6928 if (VecVT.is256BitVector()) {
6929 DebugLoc dl = Op.getNode()->getDebugLoc();
6930 unsigned NumElems = VecVT.getVectorNumElements();
6931 SDValue Idx = Op.getOperand(1);
6932 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6934 // Get the 128-bit vector.
6935 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6937 if (IdxVal >= NumElems/2)
6938 IdxVal -= NumElems/2;
6939 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6940 DAG.getConstant(IdxVal, MVT::i32));
6943 assert(VecVT.is128BitVector() && "Unexpected vector length");
6945 if (Subtarget->hasSSE41()) {
6946 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6951 EVT VT = Op.getValueType();
6952 DebugLoc dl = Op.getDebugLoc();
6953 // TODO: handle v16i8.
6954 if (VT.getSizeInBits() == 16) {
6955 SDValue Vec = Op.getOperand(0);
6956 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6958 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6959 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6960 DAG.getNode(ISD::BITCAST, dl,
6963 // Transform it so it match pextrw which produces a 32-bit result.
6964 EVT EltVT = MVT::i32;
6965 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6966 Op.getOperand(0), Op.getOperand(1));
6967 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6968 DAG.getValueType(VT));
6969 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6972 if (VT.getSizeInBits() == 32) {
6973 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6977 // SHUFPS the element to the lowest double word, then movss.
6978 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6979 EVT VVT = Op.getOperand(0).getValueType();
6980 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6981 DAG.getUNDEF(VVT), Mask);
6982 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6983 DAG.getIntPtrConstant(0));
6986 if (VT.getSizeInBits() == 64) {
6987 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6988 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6989 // to match extract_elt for f64.
6990 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6994 // UNPCKHPD the element to the lowest double word, then movsd.
6995 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6996 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6997 int Mask[2] = { 1, -1 };
6998 EVT VVT = Op.getOperand(0).getValueType();
6999 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7000 DAG.getUNDEF(VVT), Mask);
7001 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7002 DAG.getIntPtrConstant(0));
7009 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7010 SelectionDAG &DAG) const {
7011 EVT VT = Op.getValueType();
7012 EVT EltVT = VT.getVectorElementType();
7013 DebugLoc dl = Op.getDebugLoc();
7015 SDValue N0 = Op.getOperand(0);
7016 SDValue N1 = Op.getOperand(1);
7017 SDValue N2 = Op.getOperand(2);
7019 if (!VT.is128BitVector())
7022 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7023 isa<ConstantSDNode>(N2)) {
7025 if (VT == MVT::v8i16)
7026 Opc = X86ISD::PINSRW;
7027 else if (VT == MVT::v16i8)
7028 Opc = X86ISD::PINSRB;
7030 Opc = X86ISD::PINSRB;
7032 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7034 if (N1.getValueType() != MVT::i32)
7035 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7036 if (N2.getValueType() != MVT::i32)
7037 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7038 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7041 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7042 // Bits [7:6] of the constant are the source select. This will always be
7043 // zero here. The DAG Combiner may combine an extract_elt index into these
7044 // bits. For example (insert (extract, 3), 2) could be matched by putting
7045 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7046 // Bits [5:4] of the constant are the destination select. This is the
7047 // value of the incoming immediate.
7048 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7049 // combine either bitwise AND or insert of float 0.0 to set these bits.
7050 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7051 // Create this as a scalar to vector..
7052 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7053 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7056 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7057 // PINSR* works with constant index.
7064 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7065 EVT VT = Op.getValueType();
7066 EVT EltVT = VT.getVectorElementType();
7068 DebugLoc dl = Op.getDebugLoc();
7069 SDValue N0 = Op.getOperand(0);
7070 SDValue N1 = Op.getOperand(1);
7071 SDValue N2 = Op.getOperand(2);
7073 // If this is a 256-bit vector result, first extract the 128-bit vector,
7074 // insert the element into the extracted half and then place it back.
7075 if (VT.is256BitVector()) {
7076 if (!isa<ConstantSDNode>(N2))
7079 // Get the desired 128-bit vector half.
7080 unsigned NumElems = VT.getVectorNumElements();
7081 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7082 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7084 // Insert the element into the desired half.
7085 bool Upper = IdxVal >= NumElems/2;
7086 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7087 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7089 // Insert the changed part back to the 256-bit vector
7090 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7093 if (Subtarget->hasSSE41())
7094 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7096 if (EltVT == MVT::i8)
7099 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7100 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7101 // as its second argument.
7102 if (N1.getValueType() != MVT::i32)
7103 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7104 if (N2.getValueType() != MVT::i32)
7105 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7106 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7112 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7113 LLVMContext *Context = DAG.getContext();
7114 DebugLoc dl = Op.getDebugLoc();
7115 EVT OpVT = Op.getValueType();
7117 // If this is a 256-bit vector result, first insert into a 128-bit
7118 // vector and then insert into the 256-bit vector.
7119 if (!OpVT.is128BitVector()) {
7120 // Insert into a 128-bit vector.
7121 EVT VT128 = EVT::getVectorVT(*Context,
7122 OpVT.getVectorElementType(),
7123 OpVT.getVectorNumElements() / 2);
7125 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7127 // Insert the 128-bit vector.
7128 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7131 if (OpVT == MVT::v1i64 &&
7132 Op.getOperand(0).getValueType() == MVT::i64)
7133 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7135 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7136 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7137 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7138 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7141 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7142 // a simple subregister reference or explicit instructions to grab
7143 // upper bits of a vector.
7145 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7146 if (Subtarget->hasAVX()) {
7147 DebugLoc dl = Op.getNode()->getDebugLoc();
7148 SDValue Vec = Op.getNode()->getOperand(0);
7149 SDValue Idx = Op.getNode()->getOperand(1);
7151 if (Op.getNode()->getValueType(0).is128BitVector() &&
7152 Vec.getNode()->getValueType(0).is256BitVector() &&
7153 isa<ConstantSDNode>(Idx)) {
7154 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7155 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7161 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7162 // simple superregister reference or explicit instructions to insert
7163 // the upper bits of a vector.
7165 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7166 if (Subtarget->hasAVX()) {
7167 DebugLoc dl = Op.getNode()->getDebugLoc();
7168 SDValue Vec = Op.getNode()->getOperand(0);
7169 SDValue SubVec = Op.getNode()->getOperand(1);
7170 SDValue Idx = Op.getNode()->getOperand(2);
7172 if (Op.getNode()->getValueType(0).is256BitVector() &&
7173 SubVec.getNode()->getValueType(0).is128BitVector() &&
7174 isa<ConstantSDNode>(Idx)) {
7175 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7176 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7182 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7183 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7184 // one of the above mentioned nodes. It has to be wrapped because otherwise
7185 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7186 // be used to form addressing mode. These wrapped nodes will be selected
7189 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7190 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7192 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7194 unsigned char OpFlag = 0;
7195 unsigned WrapperKind = X86ISD::Wrapper;
7196 CodeModel::Model M = getTargetMachine().getCodeModel();
7198 if (Subtarget->isPICStyleRIPRel() &&
7199 (M == CodeModel::Small || M == CodeModel::Kernel))
7200 WrapperKind = X86ISD::WrapperRIP;
7201 else if (Subtarget->isPICStyleGOT())
7202 OpFlag = X86II::MO_GOTOFF;
7203 else if (Subtarget->isPICStyleStubPIC())
7204 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7206 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7208 CP->getOffset(), OpFlag);
7209 DebugLoc DL = CP->getDebugLoc();
7210 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7211 // With PIC, the address is actually $g + Offset.
7213 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7214 DAG.getNode(X86ISD::GlobalBaseReg,
7215 DebugLoc(), getPointerTy()),
7222 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7223 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7225 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7227 unsigned char OpFlag = 0;
7228 unsigned WrapperKind = X86ISD::Wrapper;
7229 CodeModel::Model M = getTargetMachine().getCodeModel();
7231 if (Subtarget->isPICStyleRIPRel() &&
7232 (M == CodeModel::Small || M == CodeModel::Kernel))
7233 WrapperKind = X86ISD::WrapperRIP;
7234 else if (Subtarget->isPICStyleGOT())
7235 OpFlag = X86II::MO_GOTOFF;
7236 else if (Subtarget->isPICStyleStubPIC())
7237 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7239 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7241 DebugLoc DL = JT->getDebugLoc();
7242 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7244 // With PIC, the address is actually $g + Offset.
7246 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7247 DAG.getNode(X86ISD::GlobalBaseReg,
7248 DebugLoc(), getPointerTy()),
7255 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7256 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7258 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7260 unsigned char OpFlag = 0;
7261 unsigned WrapperKind = X86ISD::Wrapper;
7262 CodeModel::Model M = getTargetMachine().getCodeModel();
7264 if (Subtarget->isPICStyleRIPRel() &&
7265 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7266 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7267 OpFlag = X86II::MO_GOTPCREL;
7268 WrapperKind = X86ISD::WrapperRIP;
7269 } else if (Subtarget->isPICStyleGOT()) {
7270 OpFlag = X86II::MO_GOT;
7271 } else if (Subtarget->isPICStyleStubPIC()) {
7272 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7273 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7274 OpFlag = X86II::MO_DARWIN_NONLAZY;
7277 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7279 DebugLoc DL = Op.getDebugLoc();
7280 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7283 // With PIC, the address is actually $g + Offset.
7284 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7285 !Subtarget->is64Bit()) {
7286 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7287 DAG.getNode(X86ISD::GlobalBaseReg,
7288 DebugLoc(), getPointerTy()),
7292 // For symbols that require a load from a stub to get the address, emit the
7294 if (isGlobalStubReference(OpFlag))
7295 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7296 MachinePointerInfo::getGOT(), false, false, false, 0);
7302 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7303 // Create the TargetBlockAddressAddress node.
7304 unsigned char OpFlags =
7305 Subtarget->ClassifyBlockAddressReference();
7306 CodeModel::Model M = getTargetMachine().getCodeModel();
7307 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7308 DebugLoc dl = Op.getDebugLoc();
7309 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7310 /*isTarget=*/true, OpFlags);
7312 if (Subtarget->isPICStyleRIPRel() &&
7313 (M == CodeModel::Small || M == CodeModel::Kernel))
7314 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7316 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7318 // With PIC, the address is actually $g + Offset.
7319 if (isGlobalRelativeToPICBase(OpFlags)) {
7320 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7321 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7329 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7331 SelectionDAG &DAG) const {
7332 // Create the TargetGlobalAddress node, folding in the constant
7333 // offset if it is legal.
7334 unsigned char OpFlags =
7335 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7336 CodeModel::Model M = getTargetMachine().getCodeModel();
7338 if (OpFlags == X86II::MO_NO_FLAG &&
7339 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7340 // A direct static reference to a global.
7341 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7344 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7347 if (Subtarget->isPICStyleRIPRel() &&
7348 (M == CodeModel::Small || M == CodeModel::Kernel))
7349 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7351 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7353 // With PIC, the address is actually $g + Offset.
7354 if (isGlobalRelativeToPICBase(OpFlags)) {
7355 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7356 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7360 // For globals that require a load from a stub to get the address, emit the
7362 if (isGlobalStubReference(OpFlags))
7363 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7364 MachinePointerInfo::getGOT(), false, false, false, 0);
7366 // If there was a non-zero offset that we didn't fold, create an explicit
7369 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7370 DAG.getConstant(Offset, getPointerTy()));
7376 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7377 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7378 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7379 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7383 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7384 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7385 unsigned char OperandFlags, bool LocalDynamic = false) {
7386 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7387 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7388 DebugLoc dl = GA->getDebugLoc();
7389 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7390 GA->getValueType(0),
7394 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7398 SDValue Ops[] = { Chain, TGA, *InFlag };
7399 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7401 SDValue Ops[] = { Chain, TGA };
7402 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7405 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7406 MFI->setAdjustsStack(true);
7408 SDValue Flag = Chain.getValue(1);
7409 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7412 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7414 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7417 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7418 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7419 DAG.getNode(X86ISD::GlobalBaseReg,
7420 DebugLoc(), PtrVT), InFlag);
7421 InFlag = Chain.getValue(1);
7423 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7426 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7428 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7430 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7431 X86::RAX, X86II::MO_TLSGD);
7434 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7438 DebugLoc dl = GA->getDebugLoc();
7440 // Get the start address of the TLS block for this module.
7441 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7442 .getInfo<X86MachineFunctionInfo>();
7443 MFI->incNumLocalDynamicTLSAccesses();
7447 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7448 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7451 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7452 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7453 InFlag = Chain.getValue(1);
7454 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7455 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7458 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7462 unsigned char OperandFlags = X86II::MO_DTPOFF;
7463 unsigned WrapperKind = X86ISD::Wrapper;
7464 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7465 GA->getValueType(0),
7466 GA->getOffset(), OperandFlags);
7467 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7469 // Add x@dtpoff with the base.
7470 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7473 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7474 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7475 const EVT PtrVT, TLSModel::Model model,
7476 bool is64Bit, bool isPIC) {
7477 DebugLoc dl = GA->getDebugLoc();
7479 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7480 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7481 is64Bit ? 257 : 256));
7483 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7484 DAG.getIntPtrConstant(0),
7485 MachinePointerInfo(Ptr),
7486 false, false, false, 0);
7488 unsigned char OperandFlags = 0;
7489 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7491 unsigned WrapperKind = X86ISD::Wrapper;
7492 if (model == TLSModel::LocalExec) {
7493 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7494 } else if (model == TLSModel::InitialExec) {
7496 OperandFlags = X86II::MO_GOTTPOFF;
7497 WrapperKind = X86ISD::WrapperRIP;
7499 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7502 llvm_unreachable("Unexpected model");
7505 // emit "addl x@ntpoff,%eax" (local exec)
7506 // or "addl x@indntpoff,%eax" (initial exec)
7507 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7508 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7509 GA->getValueType(0),
7510 GA->getOffset(), OperandFlags);
7511 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7513 if (model == TLSModel::InitialExec) {
7514 if (isPIC && !is64Bit) {
7515 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7516 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7520 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7521 MachinePointerInfo::getGOT(), false, false, false,
7525 // The address of the thread local variable is the add of the thread
7526 // pointer with the offset of the variable.
7527 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7531 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7533 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7534 const GlobalValue *GV = GA->getGlobal();
7536 if (Subtarget->isTargetELF()) {
7537 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7540 case TLSModel::GeneralDynamic:
7541 if (Subtarget->is64Bit())
7542 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7543 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7544 case TLSModel::LocalDynamic:
7545 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7546 Subtarget->is64Bit());
7547 case TLSModel::InitialExec:
7548 case TLSModel::LocalExec:
7549 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7550 Subtarget->is64Bit(),
7551 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7553 llvm_unreachable("Unknown TLS model.");
7556 if (Subtarget->isTargetDarwin()) {
7557 // Darwin only has one model of TLS. Lower to that.
7558 unsigned char OpFlag = 0;
7559 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7560 X86ISD::WrapperRIP : X86ISD::Wrapper;
7562 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7564 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7565 !Subtarget->is64Bit();
7567 OpFlag = X86II::MO_TLVP_PIC_BASE;
7569 OpFlag = X86II::MO_TLVP;
7570 DebugLoc DL = Op.getDebugLoc();
7571 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7572 GA->getValueType(0),
7573 GA->getOffset(), OpFlag);
7574 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7576 // With PIC32, the address is actually $g + Offset.
7578 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7579 DAG.getNode(X86ISD::GlobalBaseReg,
7580 DebugLoc(), getPointerTy()),
7583 // Lowering the machine isd will make sure everything is in the right
7585 SDValue Chain = DAG.getEntryNode();
7586 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7587 SDValue Args[] = { Chain, Offset };
7588 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7590 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7591 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7592 MFI->setAdjustsStack(true);
7594 // And our return value (tls address) is in the standard call return value
7596 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7597 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7601 if (Subtarget->isTargetWindows()) {
7602 // Just use the implicit TLS architecture
7603 // Need to generate someting similar to:
7604 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7606 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7607 // mov rcx, qword [rdx+rcx*8]
7608 // mov eax, .tls$:tlsvar
7609 // [rax+rcx] contains the address
7610 // Windows 64bit: gs:0x58
7611 // Windows 32bit: fs:__tls_array
7613 // If GV is an alias then use the aliasee for determining
7614 // thread-localness.
7615 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7616 GV = GA->resolveAliasedGlobal(false);
7617 DebugLoc dl = GA->getDebugLoc();
7618 SDValue Chain = DAG.getEntryNode();
7620 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7621 // %gs:0x58 (64-bit).
7622 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7623 ? Type::getInt8PtrTy(*DAG.getContext(),
7625 : Type::getInt32PtrTy(*DAG.getContext(),
7628 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7629 Subtarget->is64Bit()
7630 ? DAG.getIntPtrConstant(0x58)
7631 : DAG.getExternalSymbol("_tls_array",
7633 MachinePointerInfo(Ptr),
7634 false, false, false, 0);
7636 // Load the _tls_index variable
7637 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7638 if (Subtarget->is64Bit())
7639 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7640 IDX, MachinePointerInfo(), MVT::i32,
7643 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7644 false, false, false, 0);
7646 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7648 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7650 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7651 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7652 false, false, false, 0);
7654 // Get the offset of start of .tls section
7655 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7656 GA->getValueType(0),
7657 GA->getOffset(), X86II::MO_SECREL);
7658 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7660 // The address of the thread local variable is the add of the thread
7661 // pointer with the offset of the variable.
7662 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7665 llvm_unreachable("TLS not implemented for this target.");
7669 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7670 /// and take a 2 x i32 value to shift plus a shift amount.
7671 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7672 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7673 EVT VT = Op.getValueType();
7674 unsigned VTBits = VT.getSizeInBits();
7675 DebugLoc dl = Op.getDebugLoc();
7676 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7677 SDValue ShOpLo = Op.getOperand(0);
7678 SDValue ShOpHi = Op.getOperand(1);
7679 SDValue ShAmt = Op.getOperand(2);
7680 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7681 DAG.getConstant(VTBits - 1, MVT::i8))
7682 : DAG.getConstant(0, VT);
7685 if (Op.getOpcode() == ISD::SHL_PARTS) {
7686 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7687 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7689 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7690 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7693 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7694 DAG.getConstant(VTBits, MVT::i8));
7695 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7696 AndNode, DAG.getConstant(0, MVT::i8));
7699 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7700 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7701 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7703 if (Op.getOpcode() == ISD::SHL_PARTS) {
7704 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7705 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7707 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7708 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7711 SDValue Ops[2] = { Lo, Hi };
7712 return DAG.getMergeValues(Ops, 2, dl);
7715 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7716 SelectionDAG &DAG) const {
7717 EVT SrcVT = Op.getOperand(0).getValueType();
7719 if (SrcVT.isVector())
7722 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7723 "Unknown SINT_TO_FP to lower!");
7725 // These are really Legal; return the operand so the caller accepts it as
7727 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7729 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7730 Subtarget->is64Bit()) {
7734 DebugLoc dl = Op.getDebugLoc();
7735 unsigned Size = SrcVT.getSizeInBits()/8;
7736 MachineFunction &MF = DAG.getMachineFunction();
7737 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7738 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7739 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7741 MachinePointerInfo::getFixedStack(SSFI),
7743 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7746 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7748 SelectionDAG &DAG) const {
7750 DebugLoc DL = Op.getDebugLoc();
7752 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7754 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7756 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7758 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7760 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7761 MachineMemOperand *MMO;
7763 int SSFI = FI->getIndex();
7765 DAG.getMachineFunction()
7766 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7767 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7769 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7770 StackSlot = StackSlot.getOperand(1);
7772 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7773 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7775 Tys, Ops, array_lengthof(Ops),
7779 Chain = Result.getValue(1);
7780 SDValue InFlag = Result.getValue(2);
7782 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7783 // shouldn't be necessary except that RFP cannot be live across
7784 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7785 MachineFunction &MF = DAG.getMachineFunction();
7786 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7787 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7788 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7789 Tys = DAG.getVTList(MVT::Other);
7791 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7793 MachineMemOperand *MMO =
7794 DAG.getMachineFunction()
7795 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7796 MachineMemOperand::MOStore, SSFISize, SSFISize);
7798 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7799 Ops, array_lengthof(Ops),
7800 Op.getValueType(), MMO);
7801 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7802 MachinePointerInfo::getFixedStack(SSFI),
7803 false, false, false, 0);
7809 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7810 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7811 SelectionDAG &DAG) const {
7812 // This algorithm is not obvious. Here it is what we're trying to output:
7815 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7816 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7820 pshufd $0x4e, %xmm0, %xmm1
7825 DebugLoc dl = Op.getDebugLoc();
7826 LLVMContext *Context = DAG.getContext();
7828 // Build some magic constants.
7829 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7830 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7831 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7833 SmallVector<Constant*,2> CV1;
7835 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7837 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7838 Constant *C1 = ConstantVector::get(CV1);
7839 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7841 // Load the 64-bit value into an XMM register.
7842 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7844 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7845 MachinePointerInfo::getConstantPool(),
7846 false, false, false, 16);
7847 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7848 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7851 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7852 MachinePointerInfo::getConstantPool(),
7853 false, false, false, 16);
7854 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7855 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7858 if (Subtarget->hasSSE3()) {
7859 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7860 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7862 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7863 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7865 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7866 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7870 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7871 DAG.getIntPtrConstant(0));
7874 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7875 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7876 SelectionDAG &DAG) const {
7877 DebugLoc dl = Op.getDebugLoc();
7878 // FP constant to bias correct the final result.
7879 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7882 // Load the 32-bit value into an XMM register.
7883 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7886 // Zero out the upper parts of the register.
7887 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7889 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7890 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7891 DAG.getIntPtrConstant(0));
7893 // Or the load with the bias.
7894 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7895 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7896 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7898 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7899 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7900 MVT::v2f64, Bias)));
7901 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7902 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7903 DAG.getIntPtrConstant(0));
7905 // Subtract the bias.
7906 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7908 // Handle final rounding.
7909 EVT DestVT = Op.getValueType();
7911 if (DestVT.bitsLT(MVT::f64))
7912 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7913 DAG.getIntPtrConstant(0));
7914 if (DestVT.bitsGT(MVT::f64))
7915 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7917 // Handle final rounding.
7921 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7922 SelectionDAG &DAG) const {
7923 SDValue N0 = Op.getOperand(0);
7924 DebugLoc dl = Op.getDebugLoc();
7926 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7927 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7928 // the optimization here.
7929 if (DAG.SignBitIsZero(N0))
7930 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7932 EVT SrcVT = N0.getValueType();
7933 EVT DstVT = Op.getValueType();
7934 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7935 return LowerUINT_TO_FP_i64(Op, DAG);
7936 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7937 return LowerUINT_TO_FP_i32(Op, DAG);
7938 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7941 // Make a 64-bit buffer, and use it to build an FILD.
7942 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7943 if (SrcVT == MVT::i32) {
7944 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7945 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7946 getPointerTy(), StackSlot, WordOff);
7947 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7948 StackSlot, MachinePointerInfo(),
7950 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7951 OffsetSlot, MachinePointerInfo(),
7953 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7957 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7958 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7959 StackSlot, MachinePointerInfo(),
7961 // For i64 source, we need to add the appropriate power of 2 if the input
7962 // was negative. This is the same as the optimization in
7963 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7964 // we must be careful to do the computation in x87 extended precision, not
7965 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7966 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7967 MachineMemOperand *MMO =
7968 DAG.getMachineFunction()
7969 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7970 MachineMemOperand::MOLoad, 8, 8);
7972 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7973 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7974 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7977 APInt FF(32, 0x5F800000ULL);
7979 // Check whether the sign bit is set.
7980 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7981 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7984 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7985 SDValue FudgePtr = DAG.getConstantPool(
7986 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7989 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7990 SDValue Zero = DAG.getIntPtrConstant(0);
7991 SDValue Four = DAG.getIntPtrConstant(4);
7992 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7994 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7996 // Load the value out, extending it from f32 to f80.
7997 // FIXME: Avoid the extend by constructing the right constant pool?
7998 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7999 FudgePtr, MachinePointerInfo::getConstantPool(),
8000 MVT::f32, false, false, 4);
8001 // Extend everything to 80 bits to force it to be done on x87.
8002 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8003 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8006 std::pair<SDValue,SDValue> X86TargetLowering::
8007 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8008 DebugLoc DL = Op.getDebugLoc();
8010 EVT DstTy = Op.getValueType();
8012 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8013 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8017 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8018 DstTy.getSimpleVT() >= MVT::i16 &&
8019 "Unknown FP_TO_INT to lower!");
8021 // These are really Legal.
8022 if (DstTy == MVT::i32 &&
8023 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8024 return std::make_pair(SDValue(), SDValue());
8025 if (Subtarget->is64Bit() &&
8026 DstTy == MVT::i64 &&
8027 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8028 return std::make_pair(SDValue(), SDValue());
8030 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8031 // stack slot, or into the FTOL runtime function.
8032 MachineFunction &MF = DAG.getMachineFunction();
8033 unsigned MemSize = DstTy.getSizeInBits()/8;
8034 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8035 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8038 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8039 Opc = X86ISD::WIN_FTOL;
8041 switch (DstTy.getSimpleVT().SimpleTy) {
8042 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8043 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8044 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8045 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8048 SDValue Chain = DAG.getEntryNode();
8049 SDValue Value = Op.getOperand(0);
8050 EVT TheVT = Op.getOperand(0).getValueType();
8051 // FIXME This causes a redundant load/store if the SSE-class value is already
8052 // in memory, such as if it is on the callstack.
8053 if (isScalarFPTypeInSSEReg(TheVT)) {
8054 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8055 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8056 MachinePointerInfo::getFixedStack(SSFI),
8058 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8060 Chain, StackSlot, DAG.getValueType(TheVT)
8063 MachineMemOperand *MMO =
8064 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8065 MachineMemOperand::MOLoad, MemSize, MemSize);
8066 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8068 Chain = Value.getValue(1);
8069 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8070 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8073 MachineMemOperand *MMO =
8074 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8075 MachineMemOperand::MOStore, MemSize, MemSize);
8077 if (Opc != X86ISD::WIN_FTOL) {
8078 // Build the FP_TO_INT*_IN_MEM
8079 SDValue Ops[] = { Chain, Value, StackSlot };
8080 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8081 Ops, 3, DstTy, MMO);
8082 return std::make_pair(FIST, StackSlot);
8084 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8085 DAG.getVTList(MVT::Other, MVT::Glue),
8087 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8088 MVT::i32, ftol.getValue(1));
8089 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8090 MVT::i32, eax.getValue(2));
8091 SDValue Ops[] = { eax, edx };
8092 SDValue pair = IsReplace
8093 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8094 : DAG.getMergeValues(Ops, 2, DL);
8095 return std::make_pair(pair, SDValue());
8099 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8100 SelectionDAG &DAG) const {
8101 if (Op.getValueType().isVector())
8104 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8105 /*IsSigned=*/ true, /*IsReplace=*/ false);
8106 SDValue FIST = Vals.first, StackSlot = Vals.second;
8107 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8108 if (FIST.getNode() == 0) return Op;
8110 if (StackSlot.getNode())
8112 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8113 FIST, StackSlot, MachinePointerInfo(),
8114 false, false, false, 0);
8116 // The node is the result.
8120 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8121 SelectionDAG &DAG) const {
8122 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8123 /*IsSigned=*/ false, /*IsReplace=*/ false);
8124 SDValue FIST = Vals.first, StackSlot = Vals.second;
8125 assert(FIST.getNode() && "Unexpected failure");
8127 if (StackSlot.getNode())
8129 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8130 FIST, StackSlot, MachinePointerInfo(),
8131 false, false, false, 0);
8133 // The node is the result.
8137 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8138 SelectionDAG &DAG) const {
8139 LLVMContext *Context = DAG.getContext();
8140 DebugLoc dl = Op.getDebugLoc();
8141 EVT VT = Op.getValueType();
8144 EltVT = VT.getVectorElementType();
8146 if (EltVT == MVT::f64) {
8147 C = ConstantVector::getSplat(2,
8148 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8150 C = ConstantVector::getSplat(4,
8151 ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8153 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8154 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8155 MachinePointerInfo::getConstantPool(),
8156 false, false, false, 16);
8157 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8160 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8161 LLVMContext *Context = DAG.getContext();
8162 DebugLoc dl = Op.getDebugLoc();
8163 EVT VT = Op.getValueType();
8165 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8166 if (VT.isVector()) {
8167 EltVT = VT.getVectorElementType();
8168 NumElts = VT.getVectorNumElements();
8171 if (EltVT == MVT::f64)
8172 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8174 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8175 C = ConstantVector::getSplat(NumElts, C);
8176 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8177 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8178 MachinePointerInfo::getConstantPool(),
8179 false, false, false, 16);
8180 if (VT.isVector()) {
8181 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8182 return DAG.getNode(ISD::BITCAST, dl, VT,
8183 DAG.getNode(ISD::XOR, dl, XORVT,
8184 DAG.getNode(ISD::BITCAST, dl, XORVT,
8186 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8189 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8192 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8193 LLVMContext *Context = DAG.getContext();
8194 SDValue Op0 = Op.getOperand(0);
8195 SDValue Op1 = Op.getOperand(1);
8196 DebugLoc dl = Op.getDebugLoc();
8197 EVT VT = Op.getValueType();
8198 EVT SrcVT = Op1.getValueType();
8200 // If second operand is smaller, extend it first.
8201 if (SrcVT.bitsLT(VT)) {
8202 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8205 // And if it is bigger, shrink it first.
8206 if (SrcVT.bitsGT(VT)) {
8207 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8211 // At this point the operands and the result should have the same
8212 // type, and that won't be f80 since that is not custom lowered.
8214 // First get the sign bit of second operand.
8215 SmallVector<Constant*,4> CV;
8216 if (SrcVT == MVT::f64) {
8217 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8218 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8220 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8221 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8222 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8223 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8225 Constant *C = ConstantVector::get(CV);
8226 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8227 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8228 MachinePointerInfo::getConstantPool(),
8229 false, false, false, 16);
8230 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8232 // Shift sign bit right or left if the two operands have different types.
8233 if (SrcVT.bitsGT(VT)) {
8234 // Op0 is MVT::f32, Op1 is MVT::f64.
8235 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8236 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8237 DAG.getConstant(32, MVT::i32));
8238 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8239 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8240 DAG.getIntPtrConstant(0));
8243 // Clear first operand sign bit.
8245 if (VT == MVT::f64) {
8246 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8247 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8249 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8250 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8251 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8252 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8254 C = ConstantVector::get(CV);
8255 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8256 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8257 MachinePointerInfo::getConstantPool(),
8258 false, false, false, 16);
8259 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8261 // Or the value with the sign bit.
8262 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8265 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8266 SDValue N0 = Op.getOperand(0);
8267 DebugLoc dl = Op.getDebugLoc();
8268 EVT VT = Op.getValueType();
8270 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8271 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8272 DAG.getConstant(1, VT));
8273 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8276 /// Emit nodes that will be selected as "test Op0,Op0", or something
8278 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8279 SelectionDAG &DAG) const {
8280 DebugLoc dl = Op.getDebugLoc();
8282 // CF and OF aren't always set the way we want. Determine which
8283 // of these we need.
8284 bool NeedCF = false;
8285 bool NeedOF = false;
8288 case X86::COND_A: case X86::COND_AE:
8289 case X86::COND_B: case X86::COND_BE:
8292 case X86::COND_G: case X86::COND_GE:
8293 case X86::COND_L: case X86::COND_LE:
8294 case X86::COND_O: case X86::COND_NO:
8299 // See if we can use the EFLAGS value from the operand instead of
8300 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8301 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8302 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8303 // Emit a CMP with 0, which is the TEST pattern.
8304 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8305 DAG.getConstant(0, Op.getValueType()));
8307 unsigned Opcode = 0;
8308 unsigned NumOperands = 0;
8310 // Truncate operations may prevent the merge of the SETCC instruction
8311 // and the arithmetic intruction before it. Attempt to truncate the operands
8312 // of the arithmetic instruction and use a reduced bit-width instruction.
8313 bool NeedTruncation = false;
8314 SDValue ArithOp = Op;
8315 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8316 SDValue Arith = Op->getOperand(0);
8317 // Both the trunc and the arithmetic op need to have one user each.
8318 if (Arith->hasOneUse())
8319 switch (Arith.getOpcode()) {
8326 NeedTruncation = true;
8332 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8333 // which may be the result of a CAST. We use the variable 'Op', which is the
8334 // non-casted variable when we check for possible users.
8335 switch (ArithOp.getOpcode()) {
8337 // Due to an isel shortcoming, be conservative if this add is likely to be
8338 // selected as part of a load-modify-store instruction. When the root node
8339 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8340 // uses of other nodes in the match, such as the ADD in this case. This
8341 // leads to the ADD being left around and reselected, with the result being
8342 // two adds in the output. Alas, even if none our users are stores, that
8343 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8344 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8345 // climbing the DAG back to the root, and it doesn't seem to be worth the
8347 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8348 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8349 if (UI->getOpcode() != ISD::CopyToReg &&
8350 UI->getOpcode() != ISD::SETCC &&
8351 UI->getOpcode() != ISD::STORE)
8354 if (ConstantSDNode *C =
8355 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8356 // An add of one will be selected as an INC.
8357 if (C->getAPIntValue() == 1) {
8358 Opcode = X86ISD::INC;
8363 // An add of negative one (subtract of one) will be selected as a DEC.
8364 if (C->getAPIntValue().isAllOnesValue()) {
8365 Opcode = X86ISD::DEC;
8371 // Otherwise use a regular EFLAGS-setting add.
8372 Opcode = X86ISD::ADD;
8376 // If the primary and result isn't used, don't bother using X86ISD::AND,
8377 // because a TEST instruction will be better.
8378 bool NonFlagUse = false;
8379 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8380 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8382 unsigned UOpNo = UI.getOperandNo();
8383 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8384 // Look pass truncate.
8385 UOpNo = User->use_begin().getOperandNo();
8386 User = *User->use_begin();
8389 if (User->getOpcode() != ISD::BRCOND &&
8390 User->getOpcode() != ISD::SETCC &&
8391 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8404 // Due to the ISEL shortcoming noted above, be conservative if this op is
8405 // likely to be selected as part of a load-modify-store instruction.
8406 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8407 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8408 if (UI->getOpcode() == ISD::STORE)
8411 // Otherwise use a regular EFLAGS-setting instruction.
8412 switch (ArithOp.getOpcode()) {
8413 default: llvm_unreachable("unexpected operator!");
8414 case ISD::SUB: Opcode = X86ISD::SUB; break;
8415 case ISD::OR: Opcode = X86ISD::OR; break;
8416 case ISD::XOR: Opcode = X86ISD::XOR; break;
8417 case ISD::AND: Opcode = X86ISD::AND; break;
8429 return SDValue(Op.getNode(), 1);
8435 // If we found that truncation is beneficial, perform the truncation and
8437 if (NeedTruncation) {
8438 EVT VT = Op.getValueType();
8439 SDValue WideVal = Op->getOperand(0);
8440 EVT WideVT = WideVal.getValueType();
8441 unsigned ConvertedOp = 0;
8442 // Use a target machine opcode to prevent further DAGCombine
8443 // optimizations that may separate the arithmetic operations
8444 // from the setcc node.
8445 switch (WideVal.getOpcode()) {
8447 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8448 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8449 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8450 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8451 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8455 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8456 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8457 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8458 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8459 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8465 // Emit a CMP with 0, which is the TEST pattern.
8466 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8467 DAG.getConstant(0, Op.getValueType()));
8469 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8470 SmallVector<SDValue, 4> Ops;
8471 for (unsigned i = 0; i != NumOperands; ++i)
8472 Ops.push_back(Op.getOperand(i));
8474 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8475 DAG.ReplaceAllUsesWith(Op, New);
8476 return SDValue(New.getNode(), 1);
8479 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8481 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8482 SelectionDAG &DAG) const {
8483 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8484 if (C->getAPIntValue() == 0)
8485 return EmitTest(Op0, X86CC, DAG);
8487 DebugLoc dl = Op0.getDebugLoc();
8488 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8489 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8490 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8491 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8492 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8494 return SDValue(Sub.getNode(), 1);
8496 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8499 /// Convert a comparison if required by the subtarget.
8500 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8501 SelectionDAG &DAG) const {
8502 // If the subtarget does not support the FUCOMI instruction, floating-point
8503 // comparisons have to be converted.
8504 if (Subtarget->hasCMov() ||
8505 Cmp.getOpcode() != X86ISD::CMP ||
8506 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8507 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8510 // The instruction selector will select an FUCOM instruction instead of
8511 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8512 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8513 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8514 DebugLoc dl = Cmp.getDebugLoc();
8515 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8516 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8517 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8518 DAG.getConstant(8, MVT::i8));
8519 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8520 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8523 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8524 /// if it's possible.
8525 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8526 DebugLoc dl, SelectionDAG &DAG) const {
8527 SDValue Op0 = And.getOperand(0);
8528 SDValue Op1 = And.getOperand(1);
8529 if (Op0.getOpcode() == ISD::TRUNCATE)
8530 Op0 = Op0.getOperand(0);
8531 if (Op1.getOpcode() == ISD::TRUNCATE)
8532 Op1 = Op1.getOperand(0);
8535 if (Op1.getOpcode() == ISD::SHL)
8536 std::swap(Op0, Op1);
8537 if (Op0.getOpcode() == ISD::SHL) {
8538 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8539 if (And00C->getZExtValue() == 1) {
8540 // If we looked past a truncate, check that it's only truncating away
8542 unsigned BitWidth = Op0.getValueSizeInBits();
8543 unsigned AndBitWidth = And.getValueSizeInBits();
8544 if (BitWidth > AndBitWidth) {
8546 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8547 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8551 RHS = Op0.getOperand(1);
8553 } else if (Op1.getOpcode() == ISD::Constant) {
8554 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8555 uint64_t AndRHSVal = AndRHS->getZExtValue();
8556 SDValue AndLHS = Op0;
8558 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8559 LHS = AndLHS.getOperand(0);
8560 RHS = AndLHS.getOperand(1);
8563 // Use BT if the immediate can't be encoded in a TEST instruction.
8564 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8566 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8570 if (LHS.getNode()) {
8571 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8572 // instruction. Since the shift amount is in-range-or-undefined, we know
8573 // that doing a bittest on the i32 value is ok. We extend to i32 because
8574 // the encoding for the i16 version is larger than the i32 version.
8575 // Also promote i16 to i32 for performance / code size reason.
8576 if (LHS.getValueType() == MVT::i8 ||
8577 LHS.getValueType() == MVT::i16)
8578 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8580 // If the operand types disagree, extend the shift amount to match. Since
8581 // BT ignores high bits (like shifts) we can use anyextend.
8582 if (LHS.getValueType() != RHS.getValueType())
8583 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8585 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8586 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8587 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8588 DAG.getConstant(Cond, MVT::i8), BT);
8594 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8596 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8598 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8599 SDValue Op0 = Op.getOperand(0);
8600 SDValue Op1 = Op.getOperand(1);
8601 DebugLoc dl = Op.getDebugLoc();
8602 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8604 // Optimize to BT if possible.
8605 // Lower (X & (1 << N)) == 0 to BT(X, N).
8606 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8607 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8608 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8609 Op1.getOpcode() == ISD::Constant &&
8610 cast<ConstantSDNode>(Op1)->isNullValue() &&
8611 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8612 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8613 if (NewSetCC.getNode())
8617 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8619 if (Op1.getOpcode() == ISD::Constant &&
8620 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8621 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8622 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8624 // If the input is a setcc, then reuse the input setcc or use a new one with
8625 // the inverted condition.
8626 if (Op0.getOpcode() == X86ISD::SETCC) {
8627 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8628 bool Invert = (CC == ISD::SETNE) ^
8629 cast<ConstantSDNode>(Op1)->isNullValue();
8630 if (!Invert) return Op0;
8632 CCode = X86::GetOppositeBranchCondition(CCode);
8633 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8634 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8638 bool isFP = Op1.getValueType().isFloatingPoint();
8639 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8640 if (X86CC == X86::COND_INVALID)
8643 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8644 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8645 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8646 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8649 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8650 // ones, and then concatenate the result back.
8651 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8652 EVT VT = Op.getValueType();
8654 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8655 "Unsupported value type for operation");
8657 unsigned NumElems = VT.getVectorNumElements();
8658 DebugLoc dl = Op.getDebugLoc();
8659 SDValue CC = Op.getOperand(2);
8661 // Extract the LHS vectors
8662 SDValue LHS = Op.getOperand(0);
8663 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8664 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8666 // Extract the RHS vectors
8667 SDValue RHS = Op.getOperand(1);
8668 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8669 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8671 // Issue the operation on the smaller types and concatenate the result back
8672 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8673 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8674 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8675 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8676 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8680 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8682 SDValue Op0 = Op.getOperand(0);
8683 SDValue Op1 = Op.getOperand(1);
8684 SDValue CC = Op.getOperand(2);
8685 EVT VT = Op.getValueType();
8686 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8687 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8688 DebugLoc dl = Op.getDebugLoc();
8692 EVT EltVT = Op0.getValueType().getVectorElementType();
8693 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8699 // SSE Condition code mapping:
8708 switch (SetCCOpcode) {
8709 default: llvm_unreachable("Unexpected SETCC condition");
8711 case ISD::SETEQ: SSECC = 0; break;
8713 case ISD::SETGT: Swap = true; // Fallthrough
8715 case ISD::SETOLT: SSECC = 1; break;
8717 case ISD::SETGE: Swap = true; // Fallthrough
8719 case ISD::SETOLE: SSECC = 2; break;
8720 case ISD::SETUO: SSECC = 3; break;
8722 case ISD::SETNE: SSECC = 4; break;
8723 case ISD::SETULE: Swap = true; // Fallthrough
8724 case ISD::SETUGE: SSECC = 5; break;
8725 case ISD::SETULT: Swap = true; // Fallthrough
8726 case ISD::SETUGT: SSECC = 6; break;
8727 case ISD::SETO: SSECC = 7; break;
8729 case ISD::SETONE: SSECC = 8; break;
8732 std::swap(Op0, Op1);
8734 // In the two special cases we can't handle, emit two comparisons.
8737 unsigned CombineOpc;
8738 if (SetCCOpcode == ISD::SETUEQ) {
8739 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8741 assert(SetCCOpcode == ISD::SETONE);
8742 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8745 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8746 DAG.getConstant(CC0, MVT::i8));
8747 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8748 DAG.getConstant(CC1, MVT::i8));
8749 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8751 // Handle all other FP comparisons here.
8752 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8753 DAG.getConstant(SSECC, MVT::i8));
8756 // Break 256-bit integer vector compare into smaller ones.
8757 if (VT.is256BitVector() && !Subtarget->hasAVX2())
8758 return Lower256IntVSETCC(Op, DAG);
8760 // We are handling one of the integer comparisons here. Since SSE only has
8761 // GT and EQ comparisons for integer, swapping operands and multiple
8762 // operations may be required for some comparisons.
8764 bool Swap = false, Invert = false, FlipSigns = false;
8766 switch (SetCCOpcode) {
8767 default: llvm_unreachable("Unexpected SETCC condition");
8768 case ISD::SETNE: Invert = true;
8769 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8770 case ISD::SETLT: Swap = true;
8771 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8772 case ISD::SETGE: Swap = true;
8773 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8774 case ISD::SETULT: Swap = true;
8775 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8776 case ISD::SETUGE: Swap = true;
8777 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8780 std::swap(Op0, Op1);
8782 // Check that the operation in question is available (most are plain SSE2,
8783 // but PCMPGTQ and PCMPEQQ have different requirements).
8784 if (VT == MVT::v2i64) {
8785 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8787 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8791 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8792 // bits of the inputs before performing those operations.
8794 EVT EltVT = VT.getVectorElementType();
8795 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8797 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8798 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8800 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8801 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8804 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8806 // If the logical-not of the result is required, perform that now.
8808 Result = DAG.getNOT(dl, Result, VT);
8813 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8814 static bool isX86LogicalCmp(SDValue Op) {
8815 unsigned Opc = Op.getNode()->getOpcode();
8816 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8817 Opc == X86ISD::SAHF)
8819 if (Op.getResNo() == 1 &&
8820 (Opc == X86ISD::ADD ||
8821 Opc == X86ISD::SUB ||
8822 Opc == X86ISD::ADC ||
8823 Opc == X86ISD::SBB ||
8824 Opc == X86ISD::SMUL ||
8825 Opc == X86ISD::UMUL ||
8826 Opc == X86ISD::INC ||
8827 Opc == X86ISD::DEC ||
8828 Opc == X86ISD::OR ||
8829 Opc == X86ISD::XOR ||
8830 Opc == X86ISD::AND))
8833 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8839 static bool isZero(SDValue V) {
8840 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8841 return C && C->isNullValue();
8844 static bool isAllOnes(SDValue V) {
8845 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8846 return C && C->isAllOnesValue();
8849 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8850 if (V.getOpcode() != ISD::TRUNCATE)
8853 SDValue VOp0 = V.getOperand(0);
8854 unsigned InBits = VOp0.getValueSizeInBits();
8855 unsigned Bits = V.getValueSizeInBits();
8856 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8859 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8860 bool addTest = true;
8861 SDValue Cond = Op.getOperand(0);
8862 SDValue Op1 = Op.getOperand(1);
8863 SDValue Op2 = Op.getOperand(2);
8864 DebugLoc DL = Op.getDebugLoc();
8867 if (Cond.getOpcode() == ISD::SETCC) {
8868 SDValue NewCond = LowerSETCC(Cond, DAG);
8869 if (NewCond.getNode())
8873 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8874 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8875 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8876 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8877 if (Cond.getOpcode() == X86ISD::SETCC &&
8878 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8879 isZero(Cond.getOperand(1).getOperand(1))) {
8880 SDValue Cmp = Cond.getOperand(1);
8882 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8884 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8885 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8886 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8888 SDValue CmpOp0 = Cmp.getOperand(0);
8889 // Apply further optimizations for special cases
8890 // (select (x != 0), -1, 0) -> neg & sbb
8891 // (select (x == 0), 0, -1) -> neg & sbb
8892 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8893 if (YC->isNullValue() &&
8894 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8895 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8896 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8897 DAG.getConstant(0, CmpOp0.getValueType()),
8899 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8900 DAG.getConstant(X86::COND_B, MVT::i8),
8901 SDValue(Neg.getNode(), 1));
8905 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8906 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8907 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8909 SDValue Res = // Res = 0 or -1.
8910 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8911 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8913 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8914 Res = DAG.getNOT(DL, Res, Res.getValueType());
8916 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8917 if (N2C == 0 || !N2C->isNullValue())
8918 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8923 // Look past (and (setcc_carry (cmp ...)), 1).
8924 if (Cond.getOpcode() == ISD::AND &&
8925 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8926 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8927 if (C && C->getAPIntValue() == 1)
8928 Cond = Cond.getOperand(0);
8931 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8932 // setting operand in place of the X86ISD::SETCC.
8933 unsigned CondOpcode = Cond.getOpcode();
8934 if (CondOpcode == X86ISD::SETCC ||
8935 CondOpcode == X86ISD::SETCC_CARRY) {
8936 CC = Cond.getOperand(0);
8938 SDValue Cmp = Cond.getOperand(1);
8939 unsigned Opc = Cmp.getOpcode();
8940 EVT VT = Op.getValueType();
8942 bool IllegalFPCMov = false;
8943 if (VT.isFloatingPoint() && !VT.isVector() &&
8944 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8945 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8947 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8948 Opc == X86ISD::BT) { // FIXME
8952 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8953 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8954 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8955 Cond.getOperand(0).getValueType() != MVT::i8)) {
8956 SDValue LHS = Cond.getOperand(0);
8957 SDValue RHS = Cond.getOperand(1);
8961 switch (CondOpcode) {
8962 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8963 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8964 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8965 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8966 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8967 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8968 default: llvm_unreachable("unexpected overflowing operator");
8970 if (CondOpcode == ISD::UMULO)
8971 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8974 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8976 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8978 if (CondOpcode == ISD::UMULO)
8979 Cond = X86Op.getValue(2);
8981 Cond = X86Op.getValue(1);
8983 CC = DAG.getConstant(X86Cond, MVT::i8);
8988 // Look pass the truncate if the high bits are known zero.
8989 if (isTruncWithZeroHighBitsInput(Cond, DAG))
8990 Cond = Cond.getOperand(0);
8992 // We know the result of AND is compared against zero. Try to match
8994 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8995 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8996 if (NewSetCC.getNode()) {
8997 CC = NewSetCC.getOperand(0);
8998 Cond = NewSetCC.getOperand(1);
9005 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9006 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9009 // a < b ? -1 : 0 -> RES = ~setcc_carry
9010 // a < b ? 0 : -1 -> RES = setcc_carry
9011 // a >= b ? -1 : 0 -> RES = setcc_carry
9012 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9013 if (Cond.getOpcode() == X86ISD::SUB) {
9014 Cond = ConvertCmpIfNecessary(Cond, DAG);
9015 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9017 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9018 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9019 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9020 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9021 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9022 return DAG.getNOT(DL, Res, Res.getValueType());
9027 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9028 // condition is true.
9029 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9030 SDValue Ops[] = { Op2, Op1, CC, Cond };
9031 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9034 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9035 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9036 // from the AND / OR.
9037 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9038 Opc = Op.getOpcode();
9039 if (Opc != ISD::OR && Opc != ISD::AND)
9041 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9042 Op.getOperand(0).hasOneUse() &&
9043 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9044 Op.getOperand(1).hasOneUse());
9047 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9048 // 1 and that the SETCC node has a single use.
9049 static bool isXor1OfSetCC(SDValue Op) {
9050 if (Op.getOpcode() != ISD::XOR)
9052 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9053 if (N1C && N1C->getAPIntValue() == 1) {
9054 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9055 Op.getOperand(0).hasOneUse();
9060 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9061 bool addTest = true;
9062 SDValue Chain = Op.getOperand(0);
9063 SDValue Cond = Op.getOperand(1);
9064 SDValue Dest = Op.getOperand(2);
9065 DebugLoc dl = Op.getDebugLoc();
9067 bool Inverted = false;
9069 if (Cond.getOpcode() == ISD::SETCC) {
9070 // Check for setcc([su]{add,sub,mul}o == 0).
9071 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9072 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9073 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9074 Cond.getOperand(0).getResNo() == 1 &&
9075 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9076 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9077 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9078 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9079 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9080 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9082 Cond = Cond.getOperand(0);
9084 SDValue NewCond = LowerSETCC(Cond, DAG);
9085 if (NewCond.getNode())
9090 // FIXME: LowerXALUO doesn't handle these!!
9091 else if (Cond.getOpcode() == X86ISD::ADD ||
9092 Cond.getOpcode() == X86ISD::SUB ||
9093 Cond.getOpcode() == X86ISD::SMUL ||
9094 Cond.getOpcode() == X86ISD::UMUL)
9095 Cond = LowerXALUO(Cond, DAG);
9098 // Look pass (and (setcc_carry (cmp ...)), 1).
9099 if (Cond.getOpcode() == ISD::AND &&
9100 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9101 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9102 if (C && C->getAPIntValue() == 1)
9103 Cond = Cond.getOperand(0);
9106 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9107 // setting operand in place of the X86ISD::SETCC.
9108 unsigned CondOpcode = Cond.getOpcode();
9109 if (CondOpcode == X86ISD::SETCC ||
9110 CondOpcode == X86ISD::SETCC_CARRY) {
9111 CC = Cond.getOperand(0);
9113 SDValue Cmp = Cond.getOperand(1);
9114 unsigned Opc = Cmp.getOpcode();
9115 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9116 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9120 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9124 // These can only come from an arithmetic instruction with overflow,
9125 // e.g. SADDO, UADDO.
9126 Cond = Cond.getNode()->getOperand(1);
9132 CondOpcode = Cond.getOpcode();
9133 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9134 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9135 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9136 Cond.getOperand(0).getValueType() != MVT::i8)) {
9137 SDValue LHS = Cond.getOperand(0);
9138 SDValue RHS = Cond.getOperand(1);
9142 switch (CondOpcode) {
9143 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9144 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9145 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9146 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9147 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9148 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9149 default: llvm_unreachable("unexpected overflowing operator");
9152 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9153 if (CondOpcode == ISD::UMULO)
9154 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9157 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9159 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9161 if (CondOpcode == ISD::UMULO)
9162 Cond = X86Op.getValue(2);
9164 Cond = X86Op.getValue(1);
9166 CC = DAG.getConstant(X86Cond, MVT::i8);
9170 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9171 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9172 if (CondOpc == ISD::OR) {
9173 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9174 // two branches instead of an explicit OR instruction with a
9176 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9177 isX86LogicalCmp(Cmp)) {
9178 CC = Cond.getOperand(0).getOperand(0);
9179 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9180 Chain, Dest, CC, Cmp);
9181 CC = Cond.getOperand(1).getOperand(0);
9185 } else { // ISD::AND
9186 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9187 // two branches instead of an explicit AND instruction with a
9188 // separate test. However, we only do this if this block doesn't
9189 // have a fall-through edge, because this requires an explicit
9190 // jmp when the condition is false.
9191 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9192 isX86LogicalCmp(Cmp) &&
9193 Op.getNode()->hasOneUse()) {
9194 X86::CondCode CCode =
9195 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9196 CCode = X86::GetOppositeBranchCondition(CCode);
9197 CC = DAG.getConstant(CCode, MVT::i8);
9198 SDNode *User = *Op.getNode()->use_begin();
9199 // Look for an unconditional branch following this conditional branch.
9200 // We need this because we need to reverse the successors in order
9201 // to implement FCMP_OEQ.
9202 if (User->getOpcode() == ISD::BR) {
9203 SDValue FalseBB = User->getOperand(1);
9205 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9206 assert(NewBR == User);
9210 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9211 Chain, Dest, CC, Cmp);
9212 X86::CondCode CCode =
9213 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9214 CCode = X86::GetOppositeBranchCondition(CCode);
9215 CC = DAG.getConstant(CCode, MVT::i8);
9221 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9222 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9223 // It should be transformed during dag combiner except when the condition
9224 // is set by a arithmetics with overflow node.
9225 X86::CondCode CCode =
9226 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9227 CCode = X86::GetOppositeBranchCondition(CCode);
9228 CC = DAG.getConstant(CCode, MVT::i8);
9229 Cond = Cond.getOperand(0).getOperand(1);
9231 } else if (Cond.getOpcode() == ISD::SETCC &&
9232 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9233 // For FCMP_OEQ, we can emit
9234 // two branches instead of an explicit AND instruction with a
9235 // separate test. However, we only do this if this block doesn't
9236 // have a fall-through edge, because this requires an explicit
9237 // jmp when the condition is false.
9238 if (Op.getNode()->hasOneUse()) {
9239 SDNode *User = *Op.getNode()->use_begin();
9240 // Look for an unconditional branch following this conditional branch.
9241 // We need this because we need to reverse the successors in order
9242 // to implement FCMP_OEQ.
9243 if (User->getOpcode() == ISD::BR) {
9244 SDValue FalseBB = User->getOperand(1);
9246 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9247 assert(NewBR == User);
9251 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9252 Cond.getOperand(0), Cond.getOperand(1));
9253 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9254 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9255 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9256 Chain, Dest, CC, Cmp);
9257 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9262 } else if (Cond.getOpcode() == ISD::SETCC &&
9263 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9264 // For FCMP_UNE, we can emit
9265 // two branches instead of an explicit AND instruction with a
9266 // separate test. However, we only do this if this block doesn't
9267 // have a fall-through edge, because this requires an explicit
9268 // jmp when the condition is false.
9269 if (Op.getNode()->hasOneUse()) {
9270 SDNode *User = *Op.getNode()->use_begin();
9271 // Look for an unconditional branch following this conditional branch.
9272 // We need this because we need to reverse the successors in order
9273 // to implement FCMP_UNE.
9274 if (User->getOpcode() == ISD::BR) {
9275 SDValue FalseBB = User->getOperand(1);
9277 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9278 assert(NewBR == User);
9281 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9282 Cond.getOperand(0), Cond.getOperand(1));
9283 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9284 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9285 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9286 Chain, Dest, CC, Cmp);
9287 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9297 // Look pass the truncate if the high bits are known zero.
9298 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9299 Cond = Cond.getOperand(0);
9301 // We know the result of AND is compared against zero. Try to match
9303 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9304 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9305 if (NewSetCC.getNode()) {
9306 CC = NewSetCC.getOperand(0);
9307 Cond = NewSetCC.getOperand(1);
9314 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9315 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9317 Cond = ConvertCmpIfNecessary(Cond, DAG);
9318 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9319 Chain, Dest, CC, Cond);
9323 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9324 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9325 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9326 // that the guard pages used by the OS virtual memory manager are allocated in
9327 // correct sequence.
9329 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9330 SelectionDAG &DAG) const {
9331 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9332 getTargetMachine().Options.EnableSegmentedStacks) &&
9333 "This should be used only on Windows targets or when segmented stacks "
9335 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9336 DebugLoc dl = Op.getDebugLoc();
9339 SDValue Chain = Op.getOperand(0);
9340 SDValue Size = Op.getOperand(1);
9341 // FIXME: Ensure alignment here
9343 bool Is64Bit = Subtarget->is64Bit();
9344 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9346 if (getTargetMachine().Options.EnableSegmentedStacks) {
9347 MachineFunction &MF = DAG.getMachineFunction();
9348 MachineRegisterInfo &MRI = MF.getRegInfo();
9351 // The 64 bit implementation of segmented stacks needs to clobber both r10
9352 // r11. This makes it impossible to use it along with nested parameters.
9353 const Function *F = MF.getFunction();
9355 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9357 if (I->hasNestAttr())
9358 report_fatal_error("Cannot use segmented stacks with functions that "
9359 "have nested arguments.");
9362 const TargetRegisterClass *AddrRegClass =
9363 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9364 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9365 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9366 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9367 DAG.getRegister(Vreg, SPTy));
9368 SDValue Ops1[2] = { Value, Chain };
9369 return DAG.getMergeValues(Ops1, 2, dl);
9372 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9374 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9375 Flag = Chain.getValue(1);
9376 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9378 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9379 Flag = Chain.getValue(1);
9381 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9383 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9384 return DAG.getMergeValues(Ops1, 2, dl);
9388 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9389 MachineFunction &MF = DAG.getMachineFunction();
9390 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9392 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9393 DebugLoc DL = Op.getDebugLoc();
9395 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9396 // vastart just stores the address of the VarArgsFrameIndex slot into the
9397 // memory location argument.
9398 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9400 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9401 MachinePointerInfo(SV), false, false, 0);
9405 // gp_offset (0 - 6 * 8)
9406 // fp_offset (48 - 48 + 8 * 16)
9407 // overflow_arg_area (point to parameters coming in memory).
9409 SmallVector<SDValue, 8> MemOps;
9410 SDValue FIN = Op.getOperand(1);
9412 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9413 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9415 FIN, MachinePointerInfo(SV), false, false, 0);
9416 MemOps.push_back(Store);
9419 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9420 FIN, DAG.getIntPtrConstant(4));
9421 Store = DAG.getStore(Op.getOperand(0), DL,
9422 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9424 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9425 MemOps.push_back(Store);
9427 // Store ptr to overflow_arg_area
9428 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9429 FIN, DAG.getIntPtrConstant(4));
9430 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9432 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9433 MachinePointerInfo(SV, 8),
9435 MemOps.push_back(Store);
9437 // Store ptr to reg_save_area.
9438 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9439 FIN, DAG.getIntPtrConstant(8));
9440 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9442 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9443 MachinePointerInfo(SV, 16), false, false, 0);
9444 MemOps.push_back(Store);
9445 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9446 &MemOps[0], MemOps.size());
9449 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9450 assert(Subtarget->is64Bit() &&
9451 "LowerVAARG only handles 64-bit va_arg!");
9452 assert((Subtarget->isTargetLinux() ||
9453 Subtarget->isTargetDarwin()) &&
9454 "Unhandled target in LowerVAARG");
9455 assert(Op.getNode()->getNumOperands() == 4);
9456 SDValue Chain = Op.getOperand(0);
9457 SDValue SrcPtr = Op.getOperand(1);
9458 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9459 unsigned Align = Op.getConstantOperandVal(3);
9460 DebugLoc dl = Op.getDebugLoc();
9462 EVT ArgVT = Op.getNode()->getValueType(0);
9463 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9464 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9467 // Decide which area this value should be read from.
9468 // TODO: Implement the AMD64 ABI in its entirety. This simple
9469 // selection mechanism works only for the basic types.
9470 if (ArgVT == MVT::f80) {
9471 llvm_unreachable("va_arg for f80 not yet implemented");
9472 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9473 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9474 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9475 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9477 llvm_unreachable("Unhandled argument type in LowerVAARG");
9481 // Sanity Check: Make sure using fp_offset makes sense.
9482 assert(!getTargetMachine().Options.UseSoftFloat &&
9483 !(DAG.getMachineFunction()
9484 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9485 Subtarget->hasSSE1());
9488 // Insert VAARG_64 node into the DAG
9489 // VAARG_64 returns two values: Variable Argument Address, Chain
9490 SmallVector<SDValue, 11> InstOps;
9491 InstOps.push_back(Chain);
9492 InstOps.push_back(SrcPtr);
9493 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9494 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9495 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9496 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9497 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9498 VTs, &InstOps[0], InstOps.size(),
9500 MachinePointerInfo(SV),
9505 Chain = VAARG.getValue(1);
9507 // Load the next argument and return it
9508 return DAG.getLoad(ArgVT, dl,
9511 MachinePointerInfo(),
9512 false, false, false, 0);
9515 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9516 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9517 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9518 SDValue Chain = Op.getOperand(0);
9519 SDValue DstPtr = Op.getOperand(1);
9520 SDValue SrcPtr = Op.getOperand(2);
9521 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9522 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9523 DebugLoc DL = Op.getDebugLoc();
9525 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9526 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9528 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9531 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9532 // may or may not be a constant. Takes immediate version of shift as input.
9533 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9534 SDValue SrcOp, SDValue ShAmt,
9535 SelectionDAG &DAG) {
9536 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9538 if (isa<ConstantSDNode>(ShAmt)) {
9539 // Constant may be a TargetConstant. Use a regular constant.
9540 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9542 default: llvm_unreachable("Unknown target vector shift node");
9546 return DAG.getNode(Opc, dl, VT, SrcOp,
9547 DAG.getConstant(ShiftAmt, MVT::i32));
9551 // Change opcode to non-immediate version
9553 default: llvm_unreachable("Unknown target vector shift node");
9554 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9555 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9556 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9559 // Need to build a vector containing shift amount
9560 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9563 ShOps[1] = DAG.getConstant(0, MVT::i32);
9564 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9565 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9567 // The return type has to be a 128-bit type with the same element
9568 // type as the input type.
9569 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9570 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9572 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9573 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9577 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9578 DebugLoc dl = Op.getDebugLoc();
9579 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9581 default: return SDValue(); // Don't custom lower most intrinsics.
9582 // Comparison intrinsics.
9583 case Intrinsic::x86_sse_comieq_ss:
9584 case Intrinsic::x86_sse_comilt_ss:
9585 case Intrinsic::x86_sse_comile_ss:
9586 case Intrinsic::x86_sse_comigt_ss:
9587 case Intrinsic::x86_sse_comige_ss:
9588 case Intrinsic::x86_sse_comineq_ss:
9589 case Intrinsic::x86_sse_ucomieq_ss:
9590 case Intrinsic::x86_sse_ucomilt_ss:
9591 case Intrinsic::x86_sse_ucomile_ss:
9592 case Intrinsic::x86_sse_ucomigt_ss:
9593 case Intrinsic::x86_sse_ucomige_ss:
9594 case Intrinsic::x86_sse_ucomineq_ss:
9595 case Intrinsic::x86_sse2_comieq_sd:
9596 case Intrinsic::x86_sse2_comilt_sd:
9597 case Intrinsic::x86_sse2_comile_sd:
9598 case Intrinsic::x86_sse2_comigt_sd:
9599 case Intrinsic::x86_sse2_comige_sd:
9600 case Intrinsic::x86_sse2_comineq_sd:
9601 case Intrinsic::x86_sse2_ucomieq_sd:
9602 case Intrinsic::x86_sse2_ucomilt_sd:
9603 case Intrinsic::x86_sse2_ucomile_sd:
9604 case Intrinsic::x86_sse2_ucomigt_sd:
9605 case Intrinsic::x86_sse2_ucomige_sd:
9606 case Intrinsic::x86_sse2_ucomineq_sd: {
9610 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9611 case Intrinsic::x86_sse_comieq_ss:
9612 case Intrinsic::x86_sse2_comieq_sd:
9616 case Intrinsic::x86_sse_comilt_ss:
9617 case Intrinsic::x86_sse2_comilt_sd:
9621 case Intrinsic::x86_sse_comile_ss:
9622 case Intrinsic::x86_sse2_comile_sd:
9626 case Intrinsic::x86_sse_comigt_ss:
9627 case Intrinsic::x86_sse2_comigt_sd:
9631 case Intrinsic::x86_sse_comige_ss:
9632 case Intrinsic::x86_sse2_comige_sd:
9636 case Intrinsic::x86_sse_comineq_ss:
9637 case Intrinsic::x86_sse2_comineq_sd:
9641 case Intrinsic::x86_sse_ucomieq_ss:
9642 case Intrinsic::x86_sse2_ucomieq_sd:
9643 Opc = X86ISD::UCOMI;
9646 case Intrinsic::x86_sse_ucomilt_ss:
9647 case Intrinsic::x86_sse2_ucomilt_sd:
9648 Opc = X86ISD::UCOMI;
9651 case Intrinsic::x86_sse_ucomile_ss:
9652 case Intrinsic::x86_sse2_ucomile_sd:
9653 Opc = X86ISD::UCOMI;
9656 case Intrinsic::x86_sse_ucomigt_ss:
9657 case Intrinsic::x86_sse2_ucomigt_sd:
9658 Opc = X86ISD::UCOMI;
9661 case Intrinsic::x86_sse_ucomige_ss:
9662 case Intrinsic::x86_sse2_ucomige_sd:
9663 Opc = X86ISD::UCOMI;
9666 case Intrinsic::x86_sse_ucomineq_ss:
9667 case Intrinsic::x86_sse2_ucomineq_sd:
9668 Opc = X86ISD::UCOMI;
9673 SDValue LHS = Op.getOperand(1);
9674 SDValue RHS = Op.getOperand(2);
9675 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9676 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9677 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9678 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9679 DAG.getConstant(X86CC, MVT::i8), Cond);
9680 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9683 // Arithmetic intrinsics.
9684 case Intrinsic::x86_sse2_pmulu_dq:
9685 case Intrinsic::x86_avx2_pmulu_dq:
9686 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9687 Op.getOperand(1), Op.getOperand(2));
9689 // SSE3/AVX horizontal add/sub intrinsics
9690 case Intrinsic::x86_sse3_hadd_ps:
9691 case Intrinsic::x86_sse3_hadd_pd:
9692 case Intrinsic::x86_avx_hadd_ps_256:
9693 case Intrinsic::x86_avx_hadd_pd_256:
9694 case Intrinsic::x86_sse3_hsub_ps:
9695 case Intrinsic::x86_sse3_hsub_pd:
9696 case Intrinsic::x86_avx_hsub_ps_256:
9697 case Intrinsic::x86_avx_hsub_pd_256:
9698 case Intrinsic::x86_ssse3_phadd_w_128:
9699 case Intrinsic::x86_ssse3_phadd_d_128:
9700 case Intrinsic::x86_avx2_phadd_w:
9701 case Intrinsic::x86_avx2_phadd_d:
9702 case Intrinsic::x86_ssse3_phsub_w_128:
9703 case Intrinsic::x86_ssse3_phsub_d_128:
9704 case Intrinsic::x86_avx2_phsub_w:
9705 case Intrinsic::x86_avx2_phsub_d: {
9708 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9709 case Intrinsic::x86_sse3_hadd_ps:
9710 case Intrinsic::x86_sse3_hadd_pd:
9711 case Intrinsic::x86_avx_hadd_ps_256:
9712 case Intrinsic::x86_avx_hadd_pd_256:
9713 Opcode = X86ISD::FHADD;
9715 case Intrinsic::x86_sse3_hsub_ps:
9716 case Intrinsic::x86_sse3_hsub_pd:
9717 case Intrinsic::x86_avx_hsub_ps_256:
9718 case Intrinsic::x86_avx_hsub_pd_256:
9719 Opcode = X86ISD::FHSUB;
9721 case Intrinsic::x86_ssse3_phadd_w_128:
9722 case Intrinsic::x86_ssse3_phadd_d_128:
9723 case Intrinsic::x86_avx2_phadd_w:
9724 case Intrinsic::x86_avx2_phadd_d:
9725 Opcode = X86ISD::HADD;
9727 case Intrinsic::x86_ssse3_phsub_w_128:
9728 case Intrinsic::x86_ssse3_phsub_d_128:
9729 case Intrinsic::x86_avx2_phsub_w:
9730 case Intrinsic::x86_avx2_phsub_d:
9731 Opcode = X86ISD::HSUB;
9734 return DAG.getNode(Opcode, dl, Op.getValueType(),
9735 Op.getOperand(1), Op.getOperand(2));
9738 // AVX2 variable shift intrinsics
9739 case Intrinsic::x86_avx2_psllv_d:
9740 case Intrinsic::x86_avx2_psllv_q:
9741 case Intrinsic::x86_avx2_psllv_d_256:
9742 case Intrinsic::x86_avx2_psllv_q_256:
9743 case Intrinsic::x86_avx2_psrlv_d:
9744 case Intrinsic::x86_avx2_psrlv_q:
9745 case Intrinsic::x86_avx2_psrlv_d_256:
9746 case Intrinsic::x86_avx2_psrlv_q_256:
9747 case Intrinsic::x86_avx2_psrav_d:
9748 case Intrinsic::x86_avx2_psrav_d_256: {
9751 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9752 case Intrinsic::x86_avx2_psllv_d:
9753 case Intrinsic::x86_avx2_psllv_q:
9754 case Intrinsic::x86_avx2_psllv_d_256:
9755 case Intrinsic::x86_avx2_psllv_q_256:
9758 case Intrinsic::x86_avx2_psrlv_d:
9759 case Intrinsic::x86_avx2_psrlv_q:
9760 case Intrinsic::x86_avx2_psrlv_d_256:
9761 case Intrinsic::x86_avx2_psrlv_q_256:
9764 case Intrinsic::x86_avx2_psrav_d:
9765 case Intrinsic::x86_avx2_psrav_d_256:
9769 return DAG.getNode(Opcode, dl, Op.getValueType(),
9770 Op.getOperand(1), Op.getOperand(2));
9773 case Intrinsic::x86_ssse3_pshuf_b_128:
9774 case Intrinsic::x86_avx2_pshuf_b:
9775 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9776 Op.getOperand(1), Op.getOperand(2));
9778 case Intrinsic::x86_ssse3_psign_b_128:
9779 case Intrinsic::x86_ssse3_psign_w_128:
9780 case Intrinsic::x86_ssse3_psign_d_128:
9781 case Intrinsic::x86_avx2_psign_b:
9782 case Intrinsic::x86_avx2_psign_w:
9783 case Intrinsic::x86_avx2_psign_d:
9784 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9785 Op.getOperand(1), Op.getOperand(2));
9787 case Intrinsic::x86_sse41_insertps:
9788 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9789 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9791 case Intrinsic::x86_avx_vperm2f128_ps_256:
9792 case Intrinsic::x86_avx_vperm2f128_pd_256:
9793 case Intrinsic::x86_avx_vperm2f128_si_256:
9794 case Intrinsic::x86_avx2_vperm2i128:
9795 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9796 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9798 case Intrinsic::x86_avx2_permd:
9799 case Intrinsic::x86_avx2_permps:
9800 // Operands intentionally swapped. Mask is last operand to intrinsic,
9801 // but second operand for node/intruction.
9802 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9803 Op.getOperand(2), Op.getOperand(1));
9805 // ptest and testp intrinsics. The intrinsic these come from are designed to
9806 // return an integer value, not just an instruction so lower it to the ptest
9807 // or testp pattern and a setcc for the result.
9808 case Intrinsic::x86_sse41_ptestz:
9809 case Intrinsic::x86_sse41_ptestc:
9810 case Intrinsic::x86_sse41_ptestnzc:
9811 case Intrinsic::x86_avx_ptestz_256:
9812 case Intrinsic::x86_avx_ptestc_256:
9813 case Intrinsic::x86_avx_ptestnzc_256:
9814 case Intrinsic::x86_avx_vtestz_ps:
9815 case Intrinsic::x86_avx_vtestc_ps:
9816 case Intrinsic::x86_avx_vtestnzc_ps:
9817 case Intrinsic::x86_avx_vtestz_pd:
9818 case Intrinsic::x86_avx_vtestc_pd:
9819 case Intrinsic::x86_avx_vtestnzc_pd:
9820 case Intrinsic::x86_avx_vtestz_ps_256:
9821 case Intrinsic::x86_avx_vtestc_ps_256:
9822 case Intrinsic::x86_avx_vtestnzc_ps_256:
9823 case Intrinsic::x86_avx_vtestz_pd_256:
9824 case Intrinsic::x86_avx_vtestc_pd_256:
9825 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9826 bool IsTestPacked = false;
9829 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9830 case Intrinsic::x86_avx_vtestz_ps:
9831 case Intrinsic::x86_avx_vtestz_pd:
9832 case Intrinsic::x86_avx_vtestz_ps_256:
9833 case Intrinsic::x86_avx_vtestz_pd_256:
9834 IsTestPacked = true; // Fallthrough
9835 case Intrinsic::x86_sse41_ptestz:
9836 case Intrinsic::x86_avx_ptestz_256:
9838 X86CC = X86::COND_E;
9840 case Intrinsic::x86_avx_vtestc_ps:
9841 case Intrinsic::x86_avx_vtestc_pd:
9842 case Intrinsic::x86_avx_vtestc_ps_256:
9843 case Intrinsic::x86_avx_vtestc_pd_256:
9844 IsTestPacked = true; // Fallthrough
9845 case Intrinsic::x86_sse41_ptestc:
9846 case Intrinsic::x86_avx_ptestc_256:
9848 X86CC = X86::COND_B;
9850 case Intrinsic::x86_avx_vtestnzc_ps:
9851 case Intrinsic::x86_avx_vtestnzc_pd:
9852 case Intrinsic::x86_avx_vtestnzc_ps_256:
9853 case Intrinsic::x86_avx_vtestnzc_pd_256:
9854 IsTestPacked = true; // Fallthrough
9855 case Intrinsic::x86_sse41_ptestnzc:
9856 case Intrinsic::x86_avx_ptestnzc_256:
9858 X86CC = X86::COND_A;
9862 SDValue LHS = Op.getOperand(1);
9863 SDValue RHS = Op.getOperand(2);
9864 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9865 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9866 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9867 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9868 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9871 // SSE/AVX shift intrinsics
9872 case Intrinsic::x86_sse2_psll_w:
9873 case Intrinsic::x86_sse2_psll_d:
9874 case Intrinsic::x86_sse2_psll_q:
9875 case Intrinsic::x86_avx2_psll_w:
9876 case Intrinsic::x86_avx2_psll_d:
9877 case Intrinsic::x86_avx2_psll_q:
9878 case Intrinsic::x86_sse2_psrl_w:
9879 case Intrinsic::x86_sse2_psrl_d:
9880 case Intrinsic::x86_sse2_psrl_q:
9881 case Intrinsic::x86_avx2_psrl_w:
9882 case Intrinsic::x86_avx2_psrl_d:
9883 case Intrinsic::x86_avx2_psrl_q:
9884 case Intrinsic::x86_sse2_psra_w:
9885 case Intrinsic::x86_sse2_psra_d:
9886 case Intrinsic::x86_avx2_psra_w:
9887 case Intrinsic::x86_avx2_psra_d: {
9890 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9891 case Intrinsic::x86_sse2_psll_w:
9892 case Intrinsic::x86_sse2_psll_d:
9893 case Intrinsic::x86_sse2_psll_q:
9894 case Intrinsic::x86_avx2_psll_w:
9895 case Intrinsic::x86_avx2_psll_d:
9896 case Intrinsic::x86_avx2_psll_q:
9897 Opcode = X86ISD::VSHL;
9899 case Intrinsic::x86_sse2_psrl_w:
9900 case Intrinsic::x86_sse2_psrl_d:
9901 case Intrinsic::x86_sse2_psrl_q:
9902 case Intrinsic::x86_avx2_psrl_w:
9903 case Intrinsic::x86_avx2_psrl_d:
9904 case Intrinsic::x86_avx2_psrl_q:
9905 Opcode = X86ISD::VSRL;
9907 case Intrinsic::x86_sse2_psra_w:
9908 case Intrinsic::x86_sse2_psra_d:
9909 case Intrinsic::x86_avx2_psra_w:
9910 case Intrinsic::x86_avx2_psra_d:
9911 Opcode = X86ISD::VSRA;
9914 return DAG.getNode(Opcode, dl, Op.getValueType(),
9915 Op.getOperand(1), Op.getOperand(2));
9918 // SSE/AVX immediate shift intrinsics
9919 case Intrinsic::x86_sse2_pslli_w:
9920 case Intrinsic::x86_sse2_pslli_d:
9921 case Intrinsic::x86_sse2_pslli_q:
9922 case Intrinsic::x86_avx2_pslli_w:
9923 case Intrinsic::x86_avx2_pslli_d:
9924 case Intrinsic::x86_avx2_pslli_q:
9925 case Intrinsic::x86_sse2_psrli_w:
9926 case Intrinsic::x86_sse2_psrli_d:
9927 case Intrinsic::x86_sse2_psrli_q:
9928 case Intrinsic::x86_avx2_psrli_w:
9929 case Intrinsic::x86_avx2_psrli_d:
9930 case Intrinsic::x86_avx2_psrli_q:
9931 case Intrinsic::x86_sse2_psrai_w:
9932 case Intrinsic::x86_sse2_psrai_d:
9933 case Intrinsic::x86_avx2_psrai_w:
9934 case Intrinsic::x86_avx2_psrai_d: {
9937 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9938 case Intrinsic::x86_sse2_pslli_w:
9939 case Intrinsic::x86_sse2_pslli_d:
9940 case Intrinsic::x86_sse2_pslli_q:
9941 case Intrinsic::x86_avx2_pslli_w:
9942 case Intrinsic::x86_avx2_pslli_d:
9943 case Intrinsic::x86_avx2_pslli_q:
9944 Opcode = X86ISD::VSHLI;
9946 case Intrinsic::x86_sse2_psrli_w:
9947 case Intrinsic::x86_sse2_psrli_d:
9948 case Intrinsic::x86_sse2_psrli_q:
9949 case Intrinsic::x86_avx2_psrli_w:
9950 case Intrinsic::x86_avx2_psrli_d:
9951 case Intrinsic::x86_avx2_psrli_q:
9952 Opcode = X86ISD::VSRLI;
9954 case Intrinsic::x86_sse2_psrai_w:
9955 case Intrinsic::x86_sse2_psrai_d:
9956 case Intrinsic::x86_avx2_psrai_w:
9957 case Intrinsic::x86_avx2_psrai_d:
9958 Opcode = X86ISD::VSRAI;
9961 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
9962 Op.getOperand(1), Op.getOperand(2), DAG);
9965 case Intrinsic::x86_sse42_pcmpistria128:
9966 case Intrinsic::x86_sse42_pcmpestria128:
9967 case Intrinsic::x86_sse42_pcmpistric128:
9968 case Intrinsic::x86_sse42_pcmpestric128:
9969 case Intrinsic::x86_sse42_pcmpistrio128:
9970 case Intrinsic::x86_sse42_pcmpestrio128:
9971 case Intrinsic::x86_sse42_pcmpistris128:
9972 case Intrinsic::x86_sse42_pcmpestris128:
9973 case Intrinsic::x86_sse42_pcmpistriz128:
9974 case Intrinsic::x86_sse42_pcmpestriz128: {
9978 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9979 case Intrinsic::x86_sse42_pcmpistria128:
9980 Opcode = X86ISD::PCMPISTRI;
9981 X86CC = X86::COND_A;
9983 case Intrinsic::x86_sse42_pcmpestria128:
9984 Opcode = X86ISD::PCMPESTRI;
9985 X86CC = X86::COND_A;
9987 case Intrinsic::x86_sse42_pcmpistric128:
9988 Opcode = X86ISD::PCMPISTRI;
9989 X86CC = X86::COND_B;
9991 case Intrinsic::x86_sse42_pcmpestric128:
9992 Opcode = X86ISD::PCMPESTRI;
9993 X86CC = X86::COND_B;
9995 case Intrinsic::x86_sse42_pcmpistrio128:
9996 Opcode = X86ISD::PCMPISTRI;
9997 X86CC = X86::COND_O;
9999 case Intrinsic::x86_sse42_pcmpestrio128:
10000 Opcode = X86ISD::PCMPESTRI;
10001 X86CC = X86::COND_O;
10003 case Intrinsic::x86_sse42_pcmpistris128:
10004 Opcode = X86ISD::PCMPISTRI;
10005 X86CC = X86::COND_S;
10007 case Intrinsic::x86_sse42_pcmpestris128:
10008 Opcode = X86ISD::PCMPESTRI;
10009 X86CC = X86::COND_S;
10011 case Intrinsic::x86_sse42_pcmpistriz128:
10012 Opcode = X86ISD::PCMPISTRI;
10013 X86CC = X86::COND_E;
10015 case Intrinsic::x86_sse42_pcmpestriz128:
10016 Opcode = X86ISD::PCMPESTRI;
10017 X86CC = X86::COND_E;
10020 SmallVector<SDValue, 5> NewOps;
10021 NewOps.append(Op->op_begin()+1, Op->op_end());
10022 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10023 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10024 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10025 DAG.getConstant(X86CC, MVT::i8),
10026 SDValue(PCMP.getNode(), 1));
10027 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10030 case Intrinsic::x86_sse42_pcmpistri128:
10031 case Intrinsic::x86_sse42_pcmpestri128: {
10033 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10034 Opcode = X86ISD::PCMPISTRI;
10036 Opcode = X86ISD::PCMPESTRI;
10038 SmallVector<SDValue, 5> NewOps;
10039 NewOps.append(Op->op_begin()+1, Op->op_end());
10040 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10041 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10043 case Intrinsic::x86_fma_vfmadd_ps:
10044 case Intrinsic::x86_fma_vfmadd_pd:
10045 case Intrinsic::x86_fma_vfmsub_ps:
10046 case Intrinsic::x86_fma_vfmsub_pd:
10047 case Intrinsic::x86_fma_vfnmadd_ps:
10048 case Intrinsic::x86_fma_vfnmadd_pd:
10049 case Intrinsic::x86_fma_vfnmsub_ps:
10050 case Intrinsic::x86_fma_vfnmsub_pd:
10051 case Intrinsic::x86_fma_vfmaddsub_ps:
10052 case Intrinsic::x86_fma_vfmaddsub_pd:
10053 case Intrinsic::x86_fma_vfmsubadd_ps:
10054 case Intrinsic::x86_fma_vfmsubadd_pd:
10055 case Intrinsic::x86_fma_vfmadd_ps_256:
10056 case Intrinsic::x86_fma_vfmadd_pd_256:
10057 case Intrinsic::x86_fma_vfmsub_ps_256:
10058 case Intrinsic::x86_fma_vfmsub_pd_256:
10059 case Intrinsic::x86_fma_vfnmadd_ps_256:
10060 case Intrinsic::x86_fma_vfnmadd_pd_256:
10061 case Intrinsic::x86_fma_vfnmsub_ps_256:
10062 case Intrinsic::x86_fma_vfnmsub_pd_256:
10063 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10064 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10065 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10066 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10069 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10070 case Intrinsic::x86_fma_vfmadd_ps:
10071 case Intrinsic::x86_fma_vfmadd_pd:
10072 case Intrinsic::x86_fma_vfmadd_ps_256:
10073 case Intrinsic::x86_fma_vfmadd_pd_256:
10074 Opc = X86ISD::FMADD;
10076 case Intrinsic::x86_fma_vfmsub_ps:
10077 case Intrinsic::x86_fma_vfmsub_pd:
10078 case Intrinsic::x86_fma_vfmsub_ps_256:
10079 case Intrinsic::x86_fma_vfmsub_pd_256:
10080 Opc = X86ISD::FMSUB;
10082 case Intrinsic::x86_fma_vfnmadd_ps:
10083 case Intrinsic::x86_fma_vfnmadd_pd:
10084 case Intrinsic::x86_fma_vfnmadd_ps_256:
10085 case Intrinsic::x86_fma_vfnmadd_pd_256:
10086 Opc = X86ISD::FNMADD;
10088 case Intrinsic::x86_fma_vfnmsub_ps:
10089 case Intrinsic::x86_fma_vfnmsub_pd:
10090 case Intrinsic::x86_fma_vfnmsub_ps_256:
10091 case Intrinsic::x86_fma_vfnmsub_pd_256:
10092 Opc = X86ISD::FNMSUB;
10094 case Intrinsic::x86_fma_vfmaddsub_ps:
10095 case Intrinsic::x86_fma_vfmaddsub_pd:
10096 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10097 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10098 Opc = X86ISD::FMADDSUB;
10100 case Intrinsic::x86_fma_vfmsubadd_ps:
10101 case Intrinsic::x86_fma_vfmsubadd_pd:
10102 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10103 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10104 Opc = X86ISD::FMSUBADD;
10108 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10109 Op.getOperand(2), Op.getOperand(3));
10115 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10116 DebugLoc dl = Op.getDebugLoc();
10117 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10119 default: return SDValue(); // Don't custom lower most intrinsics.
10121 // RDRAND intrinsics.
10122 case Intrinsic::x86_rdrand_16:
10123 case Intrinsic::x86_rdrand_32:
10124 case Intrinsic::x86_rdrand_64: {
10125 // Emit the node with the right value type.
10126 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10127 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10129 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10130 // return the value from Rand, which is always 0, casted to i32.
10131 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10132 DAG.getConstant(1, Op->getValueType(1)),
10133 DAG.getConstant(X86::COND_B, MVT::i32),
10134 SDValue(Result.getNode(), 1) };
10135 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10136 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10139 // Return { result, isValid, chain }.
10140 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10141 SDValue(Result.getNode(), 2));
10146 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10147 SelectionDAG &DAG) const {
10148 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10149 MFI->setReturnAddressIsTaken(true);
10151 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10152 DebugLoc dl = Op.getDebugLoc();
10155 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10157 DAG.getConstant(TD->getPointerSize(),
10158 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10159 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10160 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10161 FrameAddr, Offset),
10162 MachinePointerInfo(), false, false, false, 0);
10165 // Just load the return address.
10166 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10167 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10168 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10171 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10172 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10173 MFI->setFrameAddressIsTaken(true);
10175 EVT VT = Op.getValueType();
10176 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10177 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10178 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10179 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10181 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10182 MachinePointerInfo(),
10183 false, false, false, 0);
10187 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10188 SelectionDAG &DAG) const {
10189 return DAG.getIntPtrConstant(2*TD->getPointerSize());
10192 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10193 SDValue Chain = Op.getOperand(0);
10194 SDValue Offset = Op.getOperand(1);
10195 SDValue Handler = Op.getOperand(2);
10196 DebugLoc dl = Op.getDebugLoc();
10198 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10199 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10201 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10203 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10204 DAG.getIntPtrConstant(TD->getPointerSize()));
10205 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10206 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10208 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10210 return DAG.getNode(X86ISD::EH_RETURN, dl,
10212 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10215 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10216 SelectionDAG &DAG) const {
10217 return Op.getOperand(0);
10220 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10221 SelectionDAG &DAG) const {
10222 SDValue Root = Op.getOperand(0);
10223 SDValue Trmp = Op.getOperand(1); // trampoline
10224 SDValue FPtr = Op.getOperand(2); // nested function
10225 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10226 DebugLoc dl = Op.getDebugLoc();
10228 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10230 if (Subtarget->is64Bit()) {
10231 SDValue OutChains[6];
10233 // Large code-model.
10234 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10235 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10237 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10238 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10240 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10242 // Load the pointer to the nested function into R11.
10243 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10244 SDValue Addr = Trmp;
10245 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10246 Addr, MachinePointerInfo(TrmpAddr),
10249 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10250 DAG.getConstant(2, MVT::i64));
10251 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10252 MachinePointerInfo(TrmpAddr, 2),
10255 // Load the 'nest' parameter value into R10.
10256 // R10 is specified in X86CallingConv.td
10257 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10258 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10259 DAG.getConstant(10, MVT::i64));
10260 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10261 Addr, MachinePointerInfo(TrmpAddr, 10),
10264 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10265 DAG.getConstant(12, MVT::i64));
10266 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10267 MachinePointerInfo(TrmpAddr, 12),
10270 // Jump to the nested function.
10271 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10272 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10273 DAG.getConstant(20, MVT::i64));
10274 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10275 Addr, MachinePointerInfo(TrmpAddr, 20),
10278 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10279 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10280 DAG.getConstant(22, MVT::i64));
10281 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10282 MachinePointerInfo(TrmpAddr, 22),
10285 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10287 const Function *Func =
10288 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10289 CallingConv::ID CC = Func->getCallingConv();
10294 llvm_unreachable("Unsupported calling convention");
10295 case CallingConv::C:
10296 case CallingConv::X86_StdCall: {
10297 // Pass 'nest' parameter in ECX.
10298 // Must be kept in sync with X86CallingConv.td
10299 NestReg = X86::ECX;
10301 // Check that ECX wasn't needed by an 'inreg' parameter.
10302 FunctionType *FTy = Func->getFunctionType();
10303 const AttrListPtr &Attrs = Func->getAttributes();
10305 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10306 unsigned InRegCount = 0;
10309 for (FunctionType::param_iterator I = FTy->param_begin(),
10310 E = FTy->param_end(); I != E; ++I, ++Idx)
10311 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10312 // FIXME: should only count parameters that are lowered to integers.
10313 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10315 if (InRegCount > 2) {
10316 report_fatal_error("Nest register in use - reduce number of inreg"
10322 case CallingConv::X86_FastCall:
10323 case CallingConv::X86_ThisCall:
10324 case CallingConv::Fast:
10325 // Pass 'nest' parameter in EAX.
10326 // Must be kept in sync with X86CallingConv.td
10327 NestReg = X86::EAX;
10331 SDValue OutChains[4];
10332 SDValue Addr, Disp;
10334 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10335 DAG.getConstant(10, MVT::i32));
10336 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10338 // This is storing the opcode for MOV32ri.
10339 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10340 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10341 OutChains[0] = DAG.getStore(Root, dl,
10342 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10343 Trmp, MachinePointerInfo(TrmpAddr),
10346 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10347 DAG.getConstant(1, MVT::i32));
10348 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10349 MachinePointerInfo(TrmpAddr, 1),
10352 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10353 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10354 DAG.getConstant(5, MVT::i32));
10355 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10356 MachinePointerInfo(TrmpAddr, 5),
10359 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10360 DAG.getConstant(6, MVT::i32));
10361 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10362 MachinePointerInfo(TrmpAddr, 6),
10365 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10369 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10370 SelectionDAG &DAG) const {
10372 The rounding mode is in bits 11:10 of FPSR, and has the following
10374 00 Round to nearest
10379 FLT_ROUNDS, on the other hand, expects the following:
10386 To perform the conversion, we do:
10387 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10390 MachineFunction &MF = DAG.getMachineFunction();
10391 const TargetMachine &TM = MF.getTarget();
10392 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10393 unsigned StackAlignment = TFI.getStackAlignment();
10394 EVT VT = Op.getValueType();
10395 DebugLoc DL = Op.getDebugLoc();
10397 // Save FP Control Word to stack slot
10398 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10399 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10402 MachineMemOperand *MMO =
10403 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10404 MachineMemOperand::MOStore, 2, 2);
10406 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10407 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10408 DAG.getVTList(MVT::Other),
10409 Ops, 2, MVT::i16, MMO);
10411 // Load FP Control Word from stack slot
10412 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10413 MachinePointerInfo(), false, false, false, 0);
10415 // Transform as necessary
10417 DAG.getNode(ISD::SRL, DL, MVT::i16,
10418 DAG.getNode(ISD::AND, DL, MVT::i16,
10419 CWD, DAG.getConstant(0x800, MVT::i16)),
10420 DAG.getConstant(11, MVT::i8));
10422 DAG.getNode(ISD::SRL, DL, MVT::i16,
10423 DAG.getNode(ISD::AND, DL, MVT::i16,
10424 CWD, DAG.getConstant(0x400, MVT::i16)),
10425 DAG.getConstant(9, MVT::i8));
10428 DAG.getNode(ISD::AND, DL, MVT::i16,
10429 DAG.getNode(ISD::ADD, DL, MVT::i16,
10430 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10431 DAG.getConstant(1, MVT::i16)),
10432 DAG.getConstant(3, MVT::i16));
10435 return DAG.getNode((VT.getSizeInBits() < 16 ?
10436 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10439 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10440 EVT VT = Op.getValueType();
10442 unsigned NumBits = VT.getSizeInBits();
10443 DebugLoc dl = Op.getDebugLoc();
10445 Op = Op.getOperand(0);
10446 if (VT == MVT::i8) {
10447 // Zero extend to i32 since there is not an i8 bsr.
10449 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10452 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10453 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10454 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10456 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10459 DAG.getConstant(NumBits+NumBits-1, OpVT),
10460 DAG.getConstant(X86::COND_E, MVT::i8),
10463 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10465 // Finally xor with NumBits-1.
10466 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10469 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10473 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10474 SelectionDAG &DAG) const {
10475 EVT VT = Op.getValueType();
10477 unsigned NumBits = VT.getSizeInBits();
10478 DebugLoc dl = Op.getDebugLoc();
10480 Op = Op.getOperand(0);
10481 if (VT == MVT::i8) {
10482 // Zero extend to i32 since there is not an i8 bsr.
10484 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10487 // Issue a bsr (scan bits in reverse).
10488 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10489 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10491 // And xor with NumBits-1.
10492 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10495 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10499 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10500 EVT VT = Op.getValueType();
10501 unsigned NumBits = VT.getSizeInBits();
10502 DebugLoc dl = Op.getDebugLoc();
10503 Op = Op.getOperand(0);
10505 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10506 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10507 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10509 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10512 DAG.getConstant(NumBits, VT),
10513 DAG.getConstant(X86::COND_E, MVT::i8),
10516 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10519 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10520 // ones, and then concatenate the result back.
10521 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10522 EVT VT = Op.getValueType();
10524 assert(VT.is256BitVector() && VT.isInteger() &&
10525 "Unsupported value type for operation");
10527 unsigned NumElems = VT.getVectorNumElements();
10528 DebugLoc dl = Op.getDebugLoc();
10530 // Extract the LHS vectors
10531 SDValue LHS = Op.getOperand(0);
10532 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10533 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10535 // Extract the RHS vectors
10536 SDValue RHS = Op.getOperand(1);
10537 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10538 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10540 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10541 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10543 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10544 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10545 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10548 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10549 assert(Op.getValueType().is256BitVector() &&
10550 Op.getValueType().isInteger() &&
10551 "Only handle AVX 256-bit vector integer operation");
10552 return Lower256IntArith(Op, DAG);
10555 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10556 assert(Op.getValueType().is256BitVector() &&
10557 Op.getValueType().isInteger() &&
10558 "Only handle AVX 256-bit vector integer operation");
10559 return Lower256IntArith(Op, DAG);
10562 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10563 EVT VT = Op.getValueType();
10565 // Decompose 256-bit ops into smaller 128-bit ops.
10566 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10567 return Lower256IntArith(Op, DAG);
10569 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10570 "Only know how to lower V2I64/V4I64 multiply");
10572 DebugLoc dl = Op.getDebugLoc();
10574 // Ahi = psrlqi(a, 32);
10575 // Bhi = psrlqi(b, 32);
10577 // AloBlo = pmuludq(a, b);
10578 // AloBhi = pmuludq(a, Bhi);
10579 // AhiBlo = pmuludq(Ahi, b);
10581 // AloBhi = psllqi(AloBhi, 32);
10582 // AhiBlo = psllqi(AhiBlo, 32);
10583 // return AloBlo + AloBhi + AhiBlo;
10585 SDValue A = Op.getOperand(0);
10586 SDValue B = Op.getOperand(1);
10588 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10590 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10591 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10593 // Bit cast to 32-bit vectors for MULUDQ
10594 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10595 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10596 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10597 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10598 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10600 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10601 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10602 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10604 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10605 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10607 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10608 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10611 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10613 EVT VT = Op.getValueType();
10614 DebugLoc dl = Op.getDebugLoc();
10615 SDValue R = Op.getOperand(0);
10616 SDValue Amt = Op.getOperand(1);
10617 LLVMContext *Context = DAG.getContext();
10619 if (!Subtarget->hasSSE2())
10622 // Optimize shl/srl/sra with constant shift amount.
10623 if (isSplatVector(Amt.getNode())) {
10624 SDValue SclrAmt = Amt->getOperand(0);
10625 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10626 uint64_t ShiftAmt = C->getZExtValue();
10628 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10629 (Subtarget->hasAVX2() &&
10630 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10631 if (Op.getOpcode() == ISD::SHL)
10632 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10633 DAG.getConstant(ShiftAmt, MVT::i32));
10634 if (Op.getOpcode() == ISD::SRL)
10635 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10636 DAG.getConstant(ShiftAmt, MVT::i32));
10637 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10638 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10639 DAG.getConstant(ShiftAmt, MVT::i32));
10642 if (VT == MVT::v16i8) {
10643 if (Op.getOpcode() == ISD::SHL) {
10644 // Make a large shift.
10645 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10646 DAG.getConstant(ShiftAmt, MVT::i32));
10647 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10648 // Zero out the rightmost bits.
10649 SmallVector<SDValue, 16> V(16,
10650 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10652 return DAG.getNode(ISD::AND, dl, VT, SHL,
10653 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10655 if (Op.getOpcode() == ISD::SRL) {
10656 // Make a large shift.
10657 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10658 DAG.getConstant(ShiftAmt, MVT::i32));
10659 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10660 // Zero out the leftmost bits.
10661 SmallVector<SDValue, 16> V(16,
10662 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10664 return DAG.getNode(ISD::AND, dl, VT, SRL,
10665 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10667 if (Op.getOpcode() == ISD::SRA) {
10668 if (ShiftAmt == 7) {
10669 // R s>> 7 === R s< 0
10670 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10671 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10674 // R s>> a === ((R u>> a) ^ m) - m
10675 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10676 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10678 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10679 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10680 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10683 llvm_unreachable("Unknown shift opcode.");
10686 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10687 if (Op.getOpcode() == ISD::SHL) {
10688 // Make a large shift.
10689 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10690 DAG.getConstant(ShiftAmt, MVT::i32));
10691 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10692 // Zero out the rightmost bits.
10693 SmallVector<SDValue, 32> V(32,
10694 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10696 return DAG.getNode(ISD::AND, dl, VT, SHL,
10697 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10699 if (Op.getOpcode() == ISD::SRL) {
10700 // Make a large shift.
10701 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10702 DAG.getConstant(ShiftAmt, MVT::i32));
10703 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10704 // Zero out the leftmost bits.
10705 SmallVector<SDValue, 32> V(32,
10706 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10708 return DAG.getNode(ISD::AND, dl, VT, SRL,
10709 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10711 if (Op.getOpcode() == ISD::SRA) {
10712 if (ShiftAmt == 7) {
10713 // R s>> 7 === R s< 0
10714 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10715 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10718 // R s>> a === ((R u>> a) ^ m) - m
10719 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10720 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10722 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10723 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10724 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10727 llvm_unreachable("Unknown shift opcode.");
10732 // Lower SHL with variable shift amount.
10733 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10734 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10735 DAG.getConstant(23, MVT::i32));
10737 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10738 Constant *C = ConstantDataVector::get(*Context, CV);
10739 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10740 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10741 MachinePointerInfo::getConstantPool(),
10742 false, false, false, 16);
10744 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10745 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10746 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10747 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10749 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10750 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10753 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10754 DAG.getConstant(5, MVT::i32));
10755 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10757 // Turn 'a' into a mask suitable for VSELECT
10758 SDValue VSelM = DAG.getConstant(0x80, VT);
10759 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10760 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10762 SDValue CM1 = DAG.getConstant(0x0f, VT);
10763 SDValue CM2 = DAG.getConstant(0x3f, VT);
10765 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10766 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10767 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10768 DAG.getConstant(4, MVT::i32), DAG);
10769 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10770 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10773 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10774 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10775 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10777 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10778 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10779 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10780 DAG.getConstant(2, MVT::i32), DAG);
10781 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10782 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10785 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10786 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10787 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10789 // return VSELECT(r, r+r, a);
10790 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10791 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10795 // Decompose 256-bit shifts into smaller 128-bit shifts.
10796 if (VT.is256BitVector()) {
10797 unsigned NumElems = VT.getVectorNumElements();
10798 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10799 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10801 // Extract the two vectors
10802 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10803 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10805 // Recreate the shift amount vectors
10806 SDValue Amt1, Amt2;
10807 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10808 // Constant shift amount
10809 SmallVector<SDValue, 4> Amt1Csts;
10810 SmallVector<SDValue, 4> Amt2Csts;
10811 for (unsigned i = 0; i != NumElems/2; ++i)
10812 Amt1Csts.push_back(Amt->getOperand(i));
10813 for (unsigned i = NumElems/2; i != NumElems; ++i)
10814 Amt2Csts.push_back(Amt->getOperand(i));
10816 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10817 &Amt1Csts[0], NumElems/2);
10818 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10819 &Amt2Csts[0], NumElems/2);
10821 // Variable shift amount
10822 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10823 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10826 // Issue new vector shifts for the smaller types
10827 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10828 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10830 // Concatenate the result back
10831 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10837 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10838 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10839 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10840 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10841 // has only one use.
10842 SDNode *N = Op.getNode();
10843 SDValue LHS = N->getOperand(0);
10844 SDValue RHS = N->getOperand(1);
10845 unsigned BaseOp = 0;
10847 DebugLoc DL = Op.getDebugLoc();
10848 switch (Op.getOpcode()) {
10849 default: llvm_unreachable("Unknown ovf instruction!");
10851 // A subtract of one will be selected as a INC. Note that INC doesn't
10852 // set CF, so we can't do this for UADDO.
10853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10855 BaseOp = X86ISD::INC;
10856 Cond = X86::COND_O;
10859 BaseOp = X86ISD::ADD;
10860 Cond = X86::COND_O;
10863 BaseOp = X86ISD::ADD;
10864 Cond = X86::COND_B;
10867 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10868 // set CF, so we can't do this for USUBO.
10869 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10871 BaseOp = X86ISD::DEC;
10872 Cond = X86::COND_O;
10875 BaseOp = X86ISD::SUB;
10876 Cond = X86::COND_O;
10879 BaseOp = X86ISD::SUB;
10880 Cond = X86::COND_B;
10883 BaseOp = X86ISD::SMUL;
10884 Cond = X86::COND_O;
10886 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10887 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10889 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10892 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10893 DAG.getConstant(X86::COND_O, MVT::i32),
10894 SDValue(Sum.getNode(), 2));
10896 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10900 // Also sets EFLAGS.
10901 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10902 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10905 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10906 DAG.getConstant(Cond, MVT::i32),
10907 SDValue(Sum.getNode(), 1));
10909 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10912 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10913 SelectionDAG &DAG) const {
10914 DebugLoc dl = Op.getDebugLoc();
10915 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10916 EVT VT = Op.getValueType();
10918 if (!Subtarget->hasSSE2() || !VT.isVector())
10921 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10922 ExtraVT.getScalarType().getSizeInBits();
10923 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10925 switch (VT.getSimpleVT().SimpleTy) {
10926 default: return SDValue();
10929 if (!Subtarget->hasAVX())
10931 if (!Subtarget->hasAVX2()) {
10932 // needs to be split
10933 unsigned NumElems = VT.getVectorNumElements();
10935 // Extract the LHS vectors
10936 SDValue LHS = Op.getOperand(0);
10937 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10938 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10940 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10941 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10943 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10944 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10945 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10947 SDValue Extra = DAG.getValueType(ExtraVT);
10949 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10950 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10952 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10957 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10958 Op.getOperand(0), ShAmt, DAG);
10959 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10965 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10966 DebugLoc dl = Op.getDebugLoc();
10968 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10969 // There isn't any reason to disable it if the target processor supports it.
10970 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10971 SDValue Chain = Op.getOperand(0);
10972 SDValue Zero = DAG.getConstant(0, MVT::i32);
10974 DAG.getRegister(X86::ESP, MVT::i32), // Base
10975 DAG.getTargetConstant(1, MVT::i8), // Scale
10976 DAG.getRegister(0, MVT::i32), // Index
10977 DAG.getTargetConstant(0, MVT::i32), // Disp
10978 DAG.getRegister(0, MVT::i32), // Segment.
10983 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10984 array_lengthof(Ops));
10985 return SDValue(Res, 0);
10988 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10990 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10992 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10993 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10994 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10995 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10997 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10998 if (!Op1 && !Op2 && !Op3 && Op4)
10999 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11001 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11002 if (Op1 && !Op2 && !Op3 && !Op4)
11003 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11005 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11007 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11010 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11011 SelectionDAG &DAG) const {
11012 DebugLoc dl = Op.getDebugLoc();
11013 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11014 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11015 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11016 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11018 // The only fence that needs an instruction is a sequentially-consistent
11019 // cross-thread fence.
11020 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11021 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11022 // no-sse2). There isn't any reason to disable it if the target processor
11024 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11025 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11027 SDValue Chain = Op.getOperand(0);
11028 SDValue Zero = DAG.getConstant(0, MVT::i32);
11030 DAG.getRegister(X86::ESP, MVT::i32), // Base
11031 DAG.getTargetConstant(1, MVT::i8), // Scale
11032 DAG.getRegister(0, MVT::i32), // Index
11033 DAG.getTargetConstant(0, MVT::i32), // Disp
11034 DAG.getRegister(0, MVT::i32), // Segment.
11039 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11040 array_lengthof(Ops));
11041 return SDValue(Res, 0);
11044 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11045 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11049 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11050 EVT T = Op.getValueType();
11051 DebugLoc DL = Op.getDebugLoc();
11054 switch(T.getSimpleVT().SimpleTy) {
11055 default: llvm_unreachable("Invalid value type!");
11056 case MVT::i8: Reg = X86::AL; size = 1; break;
11057 case MVT::i16: Reg = X86::AX; size = 2; break;
11058 case MVT::i32: Reg = X86::EAX; size = 4; break;
11060 assert(Subtarget->is64Bit() && "Node not type legal!");
11061 Reg = X86::RAX; size = 8;
11064 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11065 Op.getOperand(2), SDValue());
11066 SDValue Ops[] = { cpIn.getValue(0),
11069 DAG.getTargetConstant(size, MVT::i8),
11070 cpIn.getValue(1) };
11071 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11072 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11073 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11076 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11080 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11081 SelectionDAG &DAG) const {
11082 assert(Subtarget->is64Bit() && "Result not type legalized?");
11083 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11084 SDValue TheChain = Op.getOperand(0);
11085 DebugLoc dl = Op.getDebugLoc();
11086 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11087 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11088 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11090 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11091 DAG.getConstant(32, MVT::i8));
11093 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11096 return DAG.getMergeValues(Ops, 2, dl);
11099 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11100 SelectionDAG &DAG) const {
11101 EVT SrcVT = Op.getOperand(0).getValueType();
11102 EVT DstVT = Op.getValueType();
11103 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11104 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11105 assert((DstVT == MVT::i64 ||
11106 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11107 "Unexpected custom BITCAST");
11108 // i64 <=> MMX conversions are Legal.
11109 if (SrcVT==MVT::i64 && DstVT.isVector())
11111 if (DstVT==MVT::i64 && SrcVT.isVector())
11113 // MMX <=> MMX conversions are Legal.
11114 if (SrcVT.isVector() && DstVT.isVector())
11116 // All other conversions need to be expanded.
11120 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11121 SDNode *Node = Op.getNode();
11122 DebugLoc dl = Node->getDebugLoc();
11123 EVT T = Node->getValueType(0);
11124 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11125 DAG.getConstant(0, T), Node->getOperand(2));
11126 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11127 cast<AtomicSDNode>(Node)->getMemoryVT(),
11128 Node->getOperand(0),
11129 Node->getOperand(1), negOp,
11130 cast<AtomicSDNode>(Node)->getSrcValue(),
11131 cast<AtomicSDNode>(Node)->getAlignment(),
11132 cast<AtomicSDNode>(Node)->getOrdering(),
11133 cast<AtomicSDNode>(Node)->getSynchScope());
11136 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11137 SDNode *Node = Op.getNode();
11138 DebugLoc dl = Node->getDebugLoc();
11139 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11141 // Convert seq_cst store -> xchg
11142 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11143 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11144 // (The only way to get a 16-byte store is cmpxchg16b)
11145 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11146 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11147 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11148 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11149 cast<AtomicSDNode>(Node)->getMemoryVT(),
11150 Node->getOperand(0),
11151 Node->getOperand(1), Node->getOperand(2),
11152 cast<AtomicSDNode>(Node)->getMemOperand(),
11153 cast<AtomicSDNode>(Node)->getOrdering(),
11154 cast<AtomicSDNode>(Node)->getSynchScope());
11155 return Swap.getValue(1);
11157 // Other atomic stores have a simple pattern.
11161 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11162 EVT VT = Op.getNode()->getValueType(0);
11164 // Let legalize expand this if it isn't a legal type yet.
11165 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11168 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11171 bool ExtraOp = false;
11172 switch (Op.getOpcode()) {
11173 default: llvm_unreachable("Invalid code");
11174 case ISD::ADDC: Opc = X86ISD::ADD; break;
11175 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11176 case ISD::SUBC: Opc = X86ISD::SUB; break;
11177 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11181 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11183 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11184 Op.getOperand(1), Op.getOperand(2));
11187 /// LowerOperation - Provide custom lowering hooks for some operations.
11189 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11190 switch (Op.getOpcode()) {
11191 default: llvm_unreachable("Should not custom lower this!");
11192 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11193 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
11194 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
11195 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
11196 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11197 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11198 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11199 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11200 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11201 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11202 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11203 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
11204 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
11205 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11206 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11207 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11208 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11209 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11210 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11211 case ISD::SHL_PARTS:
11212 case ISD::SRA_PARTS:
11213 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11214 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11215 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11216 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11217 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11218 case ISD::FABS: return LowerFABS(Op, DAG);
11219 case ISD::FNEG: return LowerFNEG(Op, DAG);
11220 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11221 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11222 case ISD::SETCC: return LowerSETCC(Op, DAG);
11223 case ISD::SELECT: return LowerSELECT(Op, DAG);
11224 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11225 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11226 case ISD::VASTART: return LowerVASTART(Op, DAG);
11227 case ISD::VAARG: return LowerVAARG(Op, DAG);
11228 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
11229 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11230 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11231 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11232 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11233 case ISD::FRAME_TO_ARGS_OFFSET:
11234 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11235 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11236 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11237 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11238 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11239 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11240 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11241 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11242 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11243 case ISD::MUL: return LowerMUL(Op, DAG);
11246 case ISD::SHL: return LowerShift(Op, DAG);
11252 case ISD::UMULO: return LowerXALUO(Op, DAG);
11253 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
11254 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11258 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11259 case ISD::ADD: return LowerADD(Op, DAG);
11260 case ISD::SUB: return LowerSUB(Op, DAG);
11264 static void ReplaceATOMIC_LOAD(SDNode *Node,
11265 SmallVectorImpl<SDValue> &Results,
11266 SelectionDAG &DAG) {
11267 DebugLoc dl = Node->getDebugLoc();
11268 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11270 // Convert wide load -> cmpxchg8b/cmpxchg16b
11271 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11272 // (The only way to get a 16-byte load is cmpxchg16b)
11273 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11274 SDValue Zero = DAG.getConstant(0, VT);
11275 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11276 Node->getOperand(0),
11277 Node->getOperand(1), Zero, Zero,
11278 cast<AtomicSDNode>(Node)->getMemOperand(),
11279 cast<AtomicSDNode>(Node)->getOrdering(),
11280 cast<AtomicSDNode>(Node)->getSynchScope());
11281 Results.push_back(Swap.getValue(0));
11282 Results.push_back(Swap.getValue(1));
11286 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11287 SelectionDAG &DAG, unsigned NewOp) {
11288 DebugLoc dl = Node->getDebugLoc();
11289 assert (Node->getValueType(0) == MVT::i64 &&
11290 "Only know how to expand i64 atomics");
11292 SDValue Chain = Node->getOperand(0);
11293 SDValue In1 = Node->getOperand(1);
11294 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11295 Node->getOperand(2), DAG.getIntPtrConstant(0));
11296 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11297 Node->getOperand(2), DAG.getIntPtrConstant(1));
11298 SDValue Ops[] = { Chain, In1, In2L, In2H };
11299 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11301 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11302 cast<MemSDNode>(Node)->getMemOperand());
11303 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11304 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11305 Results.push_back(Result.getValue(2));
11308 /// ReplaceNodeResults - Replace a node with an illegal result type
11309 /// with a new node built out of custom code.
11310 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11311 SmallVectorImpl<SDValue>&Results,
11312 SelectionDAG &DAG) const {
11313 DebugLoc dl = N->getDebugLoc();
11314 switch (N->getOpcode()) {
11316 llvm_unreachable("Do not know how to custom type legalize this operation!");
11317 case ISD::SIGN_EXTEND_INREG:
11322 // We don't want to expand or promote these.
11324 case ISD::FP_TO_SINT:
11325 case ISD::FP_TO_UINT: {
11326 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11328 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11331 std::pair<SDValue,SDValue> Vals =
11332 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11333 SDValue FIST = Vals.first, StackSlot = Vals.second;
11334 if (FIST.getNode() != 0) {
11335 EVT VT = N->getValueType(0);
11336 // Return a load from the stack slot.
11337 if (StackSlot.getNode() != 0)
11338 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11339 MachinePointerInfo(),
11340 false, false, false, 0));
11342 Results.push_back(FIST);
11346 case ISD::READCYCLECOUNTER: {
11347 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11348 SDValue TheChain = N->getOperand(0);
11349 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11350 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11352 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11354 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11355 SDValue Ops[] = { eax, edx };
11356 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11357 Results.push_back(edx.getValue(1));
11360 case ISD::ATOMIC_CMP_SWAP: {
11361 EVT T = N->getValueType(0);
11362 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11363 bool Regs64bit = T == MVT::i128;
11364 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11365 SDValue cpInL, cpInH;
11366 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11367 DAG.getConstant(0, HalfT));
11368 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11369 DAG.getConstant(1, HalfT));
11370 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11371 Regs64bit ? X86::RAX : X86::EAX,
11373 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11374 Regs64bit ? X86::RDX : X86::EDX,
11375 cpInH, cpInL.getValue(1));
11376 SDValue swapInL, swapInH;
11377 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11378 DAG.getConstant(0, HalfT));
11379 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11380 DAG.getConstant(1, HalfT));
11381 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11382 Regs64bit ? X86::RBX : X86::EBX,
11383 swapInL, cpInH.getValue(1));
11384 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11385 Regs64bit ? X86::RCX : X86::ECX,
11386 swapInH, swapInL.getValue(1));
11387 SDValue Ops[] = { swapInH.getValue(0),
11389 swapInH.getValue(1) };
11390 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11391 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11392 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11393 X86ISD::LCMPXCHG8_DAG;
11394 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11396 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11397 Regs64bit ? X86::RAX : X86::EAX,
11398 HalfT, Result.getValue(1));
11399 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11400 Regs64bit ? X86::RDX : X86::EDX,
11401 HalfT, cpOutL.getValue(2));
11402 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11403 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11404 Results.push_back(cpOutH.getValue(1));
11407 case ISD::ATOMIC_LOAD_ADD:
11408 case ISD::ATOMIC_LOAD_AND:
11409 case ISD::ATOMIC_LOAD_NAND:
11410 case ISD::ATOMIC_LOAD_OR:
11411 case ISD::ATOMIC_LOAD_SUB:
11412 case ISD::ATOMIC_LOAD_XOR:
11413 case ISD::ATOMIC_SWAP: {
11415 switch (N->getOpcode()) {
11416 default: llvm_unreachable("Unexpected opcode");
11417 case ISD::ATOMIC_LOAD_ADD:
11418 Opc = X86ISD::ATOMADD64_DAG;
11420 case ISD::ATOMIC_LOAD_AND:
11421 Opc = X86ISD::ATOMAND64_DAG;
11423 case ISD::ATOMIC_LOAD_NAND:
11424 Opc = X86ISD::ATOMNAND64_DAG;
11426 case ISD::ATOMIC_LOAD_OR:
11427 Opc = X86ISD::ATOMOR64_DAG;
11429 case ISD::ATOMIC_LOAD_SUB:
11430 Opc = X86ISD::ATOMSUB64_DAG;
11432 case ISD::ATOMIC_LOAD_XOR:
11433 Opc = X86ISD::ATOMXOR64_DAG;
11435 case ISD::ATOMIC_SWAP:
11436 Opc = X86ISD::ATOMSWAP64_DAG;
11439 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11442 case ISD::ATOMIC_LOAD:
11443 ReplaceATOMIC_LOAD(N, Results, DAG);
11447 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11449 default: return NULL;
11450 case X86ISD::BSF: return "X86ISD::BSF";
11451 case X86ISD::BSR: return "X86ISD::BSR";
11452 case X86ISD::SHLD: return "X86ISD::SHLD";
11453 case X86ISD::SHRD: return "X86ISD::SHRD";
11454 case X86ISD::FAND: return "X86ISD::FAND";
11455 case X86ISD::FOR: return "X86ISD::FOR";
11456 case X86ISD::FXOR: return "X86ISD::FXOR";
11457 case X86ISD::FSRL: return "X86ISD::FSRL";
11458 case X86ISD::FILD: return "X86ISD::FILD";
11459 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11460 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11461 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11462 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11463 case X86ISD::FLD: return "X86ISD::FLD";
11464 case X86ISD::FST: return "X86ISD::FST";
11465 case X86ISD::CALL: return "X86ISD::CALL";
11466 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11467 case X86ISD::BT: return "X86ISD::BT";
11468 case X86ISD::CMP: return "X86ISD::CMP";
11469 case X86ISD::COMI: return "X86ISD::COMI";
11470 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11471 case X86ISD::SETCC: return "X86ISD::SETCC";
11472 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11473 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11474 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11475 case X86ISD::CMOV: return "X86ISD::CMOV";
11476 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11477 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11478 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11479 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11480 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11481 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11482 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11483 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11484 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11485 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11486 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11487 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11488 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11489 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11490 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11491 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11492 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11493 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11494 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11495 case X86ISD::HADD: return "X86ISD::HADD";
11496 case X86ISD::HSUB: return "X86ISD::HSUB";
11497 case X86ISD::FHADD: return "X86ISD::FHADD";
11498 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11499 case X86ISD::FMAX: return "X86ISD::FMAX";
11500 case X86ISD::FMIN: return "X86ISD::FMIN";
11501 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11502 case X86ISD::FMINC: return "X86ISD::FMINC";
11503 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11504 case X86ISD::FRCP: return "X86ISD::FRCP";
11505 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11506 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11507 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11508 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11509 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11510 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11511 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11512 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11513 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11514 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11515 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11516 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11517 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11518 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11519 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11520 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11521 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11522 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11523 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11524 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11525 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11526 case X86ISD::VSHL: return "X86ISD::VSHL";
11527 case X86ISD::VSRL: return "X86ISD::VSRL";
11528 case X86ISD::VSRA: return "X86ISD::VSRA";
11529 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11530 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11531 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11532 case X86ISD::CMPP: return "X86ISD::CMPP";
11533 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11534 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11535 case X86ISD::ADD: return "X86ISD::ADD";
11536 case X86ISD::SUB: return "X86ISD::SUB";
11537 case X86ISD::ADC: return "X86ISD::ADC";
11538 case X86ISD::SBB: return "X86ISD::SBB";
11539 case X86ISD::SMUL: return "X86ISD::SMUL";
11540 case X86ISD::UMUL: return "X86ISD::UMUL";
11541 case X86ISD::INC: return "X86ISD::INC";
11542 case X86ISD::DEC: return "X86ISD::DEC";
11543 case X86ISD::OR: return "X86ISD::OR";
11544 case X86ISD::XOR: return "X86ISD::XOR";
11545 case X86ISD::AND: return "X86ISD::AND";
11546 case X86ISD::ANDN: return "X86ISD::ANDN";
11547 case X86ISD::BLSI: return "X86ISD::BLSI";
11548 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11549 case X86ISD::BLSR: return "X86ISD::BLSR";
11550 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11551 case X86ISD::PTEST: return "X86ISD::PTEST";
11552 case X86ISD::TESTP: return "X86ISD::TESTP";
11553 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11554 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11555 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11556 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11557 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11558 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11559 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11560 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11561 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11562 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11563 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11564 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11565 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11566 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11567 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11568 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11569 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11570 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11571 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11572 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11573 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11574 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11575 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11576 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11577 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11578 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11579 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11580 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11581 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11582 case X86ISD::SAHF: return "X86ISD::SAHF";
11583 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11584 case X86ISD::FMADD: return "X86ISD::FMADD";
11585 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11586 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11587 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11588 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11589 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11593 // isLegalAddressingMode - Return true if the addressing mode represented
11594 // by AM is legal for this target, for a load/store of the specified type.
11595 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11597 // X86 supports extremely general addressing modes.
11598 CodeModel::Model M = getTargetMachine().getCodeModel();
11599 Reloc::Model R = getTargetMachine().getRelocationModel();
11601 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11602 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11607 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11609 // If a reference to this global requires an extra load, we can't fold it.
11610 if (isGlobalStubReference(GVFlags))
11613 // If BaseGV requires a register for the PIC base, we cannot also have a
11614 // BaseReg specified.
11615 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11618 // If lower 4G is not available, then we must use rip-relative addressing.
11619 if ((M != CodeModel::Small || R != Reloc::Static) &&
11620 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11624 switch (AM.Scale) {
11630 // These scales always work.
11635 // These scales are formed with basereg+scalereg. Only accept if there is
11640 default: // Other stuff never works.
11648 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11649 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11651 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11652 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11653 if (NumBits1 <= NumBits2)
11658 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11659 return Imm == (int32_t)Imm;
11662 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11663 // Can also use sub to handle negated immediates.
11664 return Imm == (int32_t)Imm;
11667 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11668 if (!VT1.isInteger() || !VT2.isInteger())
11670 unsigned NumBits1 = VT1.getSizeInBits();
11671 unsigned NumBits2 = VT2.getSizeInBits();
11672 if (NumBits1 <= NumBits2)
11677 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11678 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11679 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11682 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11683 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11684 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11687 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11688 // i16 instructions are longer (0x66 prefix) and potentially slower.
11689 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11692 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11693 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11694 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11695 /// are assumed to be legal.
11697 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11699 // Very little shuffling can be done for 64-bit vectors right now.
11700 if (VT.getSizeInBits() == 64)
11703 // FIXME: pshufb, blends, shifts.
11704 return (VT.getVectorNumElements() == 2 ||
11705 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11706 isMOVLMask(M, VT) ||
11707 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11708 isPSHUFDMask(M, VT) ||
11709 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11710 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11711 isPALIGNRMask(M, VT, Subtarget) ||
11712 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11713 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11714 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11715 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11719 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11721 unsigned NumElts = VT.getVectorNumElements();
11722 // FIXME: This collection of masks seems suspect.
11725 if (NumElts == 4 && VT.is128BitVector()) {
11726 return (isMOVLMask(Mask, VT) ||
11727 isCommutedMOVLMask(Mask, VT, true) ||
11728 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11729 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11734 //===----------------------------------------------------------------------===//
11735 // X86 Scheduler Hooks
11736 //===----------------------------------------------------------------------===//
11738 // private utility function
11739 MachineBasicBlock *
11740 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11741 MachineBasicBlock *MBB,
11748 const TargetRegisterClass *RC,
11749 bool Invert) const {
11750 // For the atomic bitwise operator, we generate
11753 // ld t1 = [bitinstr.addr]
11754 // op t2 = t1, [bitinstr.val]
11755 // not t3 = t2 (if Invert)
11757 // lcs dest = [bitinstr.addr], t3 [EAX is implicit]
11759 // fallthrough -->nextMBB
11760 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11761 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11762 MachineFunction::iterator MBBIter = MBB;
11765 /// First build the CFG
11766 MachineFunction *F = MBB->getParent();
11767 MachineBasicBlock *thisMBB = MBB;
11768 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11769 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11770 F->insert(MBBIter, newMBB);
11771 F->insert(MBBIter, nextMBB);
11773 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11774 nextMBB->splice(nextMBB->begin(), thisMBB,
11775 llvm::next(MachineBasicBlock::iterator(bInstr)),
11777 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11779 // Update thisMBB to fall through to newMBB
11780 thisMBB->addSuccessor(newMBB);
11782 // newMBB jumps to itself and fall through to nextMBB
11783 newMBB->addSuccessor(nextMBB);
11784 newMBB->addSuccessor(newMBB);
11786 // Insert instructions into newMBB based on incoming instruction
11787 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11788 "unexpected number of operands");
11789 DebugLoc dl = bInstr->getDebugLoc();
11790 MachineOperand& destOper = bInstr->getOperand(0);
11791 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11792 int numArgs = bInstr->getNumOperands() - 1;
11793 for (int i=0; i < numArgs; ++i)
11794 argOpers[i] = &bInstr->getOperand(i+1);
11796 // x86 address has 4 operands: base, index, scale, and displacement
11797 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11798 int valArgIndx = lastAddrIndx + 1;
11800 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11801 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11802 for (int i=0; i <= lastAddrIndx; ++i)
11803 (*MIB).addOperand(*argOpers[i]);
11805 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11806 assert((argOpers[valArgIndx]->isReg() ||
11807 argOpers[valArgIndx]->isImm()) &&
11808 "invalid operand");
11809 if (argOpers[valArgIndx]->isReg())
11810 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11812 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11814 (*MIB).addOperand(*argOpers[valArgIndx]);
11816 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11818 MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11823 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11826 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11827 for (int i=0; i <= lastAddrIndx; ++i)
11828 (*MIB).addOperand(*argOpers[i]);
11830 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11831 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11832 bInstr->memoperands_end());
11834 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11835 MIB.addReg(EAXreg);
11838 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11840 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11844 // private utility function: 64 bit atomics on 32 bit host.
11845 MachineBasicBlock *
11846 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11847 MachineBasicBlock *MBB,
11852 bool Invert) const {
11853 // For the atomic bitwise operator, we generate
11854 // thisMBB (instructions are in pairs, except cmpxchg8b)
11855 // ld t1,t2 = [bitinstr.addr]
11857 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11858 // op t5, t6 <- out1, out2, [bitinstr.val]
11859 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11860 // neg t7, t8 < t5, t6 (if Invert)
11861 // mov ECX, EBX <- t5, t6
11862 // mov EAX, EDX <- t1, t2
11863 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11864 // mov t3, t4 <- EAX, EDX
11866 // result in out1, out2
11867 // fallthrough -->nextMBB
11869 const TargetRegisterClass *RC = &X86::GR32RegClass;
11870 const unsigned LoadOpc = X86::MOV32rm;
11871 const unsigned NotOpc = X86::NOT32r;
11872 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11873 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11874 MachineFunction::iterator MBBIter = MBB;
11877 /// First build the CFG
11878 MachineFunction *F = MBB->getParent();
11879 MachineBasicBlock *thisMBB = MBB;
11880 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11881 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11882 F->insert(MBBIter, newMBB);
11883 F->insert(MBBIter, nextMBB);
11885 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11886 nextMBB->splice(nextMBB->begin(), thisMBB,
11887 llvm::next(MachineBasicBlock::iterator(bInstr)),
11889 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11891 // Update thisMBB to fall through to newMBB
11892 thisMBB->addSuccessor(newMBB);
11894 // newMBB jumps to itself and fall through to nextMBB
11895 newMBB->addSuccessor(nextMBB);
11896 newMBB->addSuccessor(newMBB);
11898 DebugLoc dl = bInstr->getDebugLoc();
11899 // Insert instructions into newMBB based on incoming instruction
11900 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11901 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11902 "unexpected number of operands");
11903 MachineOperand& dest1Oper = bInstr->getOperand(0);
11904 MachineOperand& dest2Oper = bInstr->getOperand(1);
11905 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11906 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11907 argOpers[i] = &bInstr->getOperand(i+2);
11909 // We use some of the operands multiple times, so conservatively just
11910 // clear any kill flags that might be present.
11911 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11912 argOpers[i]->setIsKill(false);
11915 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11916 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11918 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11919 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11920 for (int i=0; i <= lastAddrIndx; ++i)
11921 (*MIB).addOperand(*argOpers[i]);
11922 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11923 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11924 // add 4 to displacement.
11925 for (int i=0; i <= lastAddrIndx-2; ++i)
11926 (*MIB).addOperand(*argOpers[i]);
11927 MachineOperand newOp3 = *(argOpers[3]);
11928 if (newOp3.isImm())
11929 newOp3.setImm(newOp3.getImm()+4);
11931 newOp3.setOffset(newOp3.getOffset()+4);
11932 (*MIB).addOperand(newOp3);
11933 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11935 // t3/4 are defined later, at the bottom of the loop
11936 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11937 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11938 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11939 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11940 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11941 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11943 // The subsequent operations should be using the destination registers of
11944 // the PHI instructions.
11945 t1 = dest1Oper.getReg();
11946 t2 = dest2Oper.getReg();
11948 int valArgIndx = lastAddrIndx + 1;
11949 assert((argOpers[valArgIndx]->isReg() ||
11950 argOpers[valArgIndx]->isImm()) &&
11951 "invalid operand");
11952 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11953 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11954 if (argOpers[valArgIndx]->isReg())
11955 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11957 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11958 if (regOpcL != X86::MOV32rr)
11960 (*MIB).addOperand(*argOpers[valArgIndx]);
11961 assert(argOpers[valArgIndx + 1]->isReg() ==
11962 argOpers[valArgIndx]->isReg());
11963 assert(argOpers[valArgIndx + 1]->isImm() ==
11964 argOpers[valArgIndx]->isImm());
11965 if (argOpers[valArgIndx + 1]->isReg())
11966 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11968 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11969 if (regOpcH != X86::MOV32rr)
11971 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11975 t7 = F->getRegInfo().createVirtualRegister(RC);
11976 t8 = F->getRegInfo().createVirtualRegister(RC);
11977 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11978 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11984 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11986 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11989 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11991 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11994 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11995 for (int i=0; i <= lastAddrIndx; ++i)
11996 (*MIB).addOperand(*argOpers[i]);
11998 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11999 (*MIB).setMemRefs(bInstr->memoperands_begin(),
12000 bInstr->memoperands_end());
12002 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12003 MIB.addReg(X86::EAX);
12004 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12005 MIB.addReg(X86::EDX);
12008 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12010 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
12014 // private utility function
12015 MachineBasicBlock *
12016 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12017 MachineBasicBlock *MBB,
12018 unsigned cmovOpc) const {
12019 // For the atomic min/max operator, we generate
12022 // ld t1 = [min/max.addr]
12023 // mov t2 = [min/max.val]
12025 // cmov[cond] t2 = t1
12027 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
12029 // fallthrough -->nextMBB
12031 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12032 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12033 MachineFunction::iterator MBBIter = MBB;
12036 /// First build the CFG
12037 MachineFunction *F = MBB->getParent();
12038 MachineBasicBlock *thisMBB = MBB;
12039 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12040 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12041 F->insert(MBBIter, newMBB);
12042 F->insert(MBBIter, nextMBB);
12044 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12045 nextMBB->splice(nextMBB->begin(), thisMBB,
12046 llvm::next(MachineBasicBlock::iterator(mInstr)),
12048 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12050 // Update thisMBB to fall through to newMBB
12051 thisMBB->addSuccessor(newMBB);
12053 // newMBB jumps to newMBB and fall through to nextMBB
12054 newMBB->addSuccessor(nextMBB);
12055 newMBB->addSuccessor(newMBB);
12057 DebugLoc dl = mInstr->getDebugLoc();
12058 // Insert instructions into newMBB based on incoming instruction
12059 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12060 "unexpected number of operands");
12061 MachineOperand& destOper = mInstr->getOperand(0);
12062 MachineOperand* argOpers[2 + X86::AddrNumOperands];
12063 int numArgs = mInstr->getNumOperands() - 1;
12064 for (int i=0; i < numArgs; ++i)
12065 argOpers[i] = &mInstr->getOperand(i+1);
12067 // x86 address has 4 operands: base, index, scale, and displacement
12068 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12069 int valArgIndx = lastAddrIndx + 1;
12071 unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12072 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12073 for (int i=0; i <= lastAddrIndx; ++i)
12074 (*MIB).addOperand(*argOpers[i]);
12076 // We only support register and immediate values
12077 assert((argOpers[valArgIndx]->isReg() ||
12078 argOpers[valArgIndx]->isImm()) &&
12079 "invalid operand");
12081 unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12082 if (argOpers[valArgIndx]->isReg())
12083 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12085 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12086 (*MIB).addOperand(*argOpers[valArgIndx]);
12088 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12091 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12096 unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12097 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12101 // Cmp and exchange if none has modified the memory location
12102 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12103 for (int i=0; i <= lastAddrIndx; ++i)
12104 (*MIB).addOperand(*argOpers[i]);
12106 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12107 (*MIB).setMemRefs(mInstr->memoperands_begin(),
12108 mInstr->memoperands_end());
12110 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12111 MIB.addReg(X86::EAX);
12114 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12116 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
12120 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12121 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12122 // in the .td file.
12123 MachineBasicBlock *
12124 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12125 unsigned numArgs, bool memArg) const {
12126 assert(Subtarget->hasSSE42() &&
12127 "Target must have SSE4.2 or AVX features enabled");
12129 DebugLoc dl = MI->getDebugLoc();
12130 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12132 if (!Subtarget->hasAVX()) {
12134 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12136 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12139 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12141 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12144 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12145 for (unsigned i = 0; i < numArgs; ++i) {
12146 MachineOperand &Op = MI->getOperand(i+1);
12147 if (!(Op.isReg() && Op.isImplicit()))
12148 MIB.addOperand(Op);
12150 BuildMI(*BB, MI, dl,
12151 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12152 .addReg(X86::XMM0);
12154 MI->eraseFromParent();
12158 MachineBasicBlock *
12159 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12160 DebugLoc dl = MI->getDebugLoc();
12161 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12163 // Address into RAX/EAX, other two args into ECX, EDX.
12164 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12165 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12166 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12167 for (int i = 0; i < X86::AddrNumOperands; ++i)
12168 MIB.addOperand(MI->getOperand(i));
12170 unsigned ValOps = X86::AddrNumOperands;
12171 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12172 .addReg(MI->getOperand(ValOps).getReg());
12173 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12174 .addReg(MI->getOperand(ValOps+1).getReg());
12176 // The instruction doesn't actually take any operands though.
12177 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12179 MI->eraseFromParent(); // The pseudo is gone now.
12183 MachineBasicBlock *
12184 X86TargetLowering::EmitVAARG64WithCustomInserter(
12186 MachineBasicBlock *MBB) const {
12187 // Emit va_arg instruction on X86-64.
12189 // Operands to this pseudo-instruction:
12190 // 0 ) Output : destination address (reg)
12191 // 1-5) Input : va_list address (addr, i64mem)
12192 // 6 ) ArgSize : Size (in bytes) of vararg type
12193 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12194 // 8 ) Align : Alignment of type
12195 // 9 ) EFLAGS (implicit-def)
12197 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12198 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12200 unsigned DestReg = MI->getOperand(0).getReg();
12201 MachineOperand &Base = MI->getOperand(1);
12202 MachineOperand &Scale = MI->getOperand(2);
12203 MachineOperand &Index = MI->getOperand(3);
12204 MachineOperand &Disp = MI->getOperand(4);
12205 MachineOperand &Segment = MI->getOperand(5);
12206 unsigned ArgSize = MI->getOperand(6).getImm();
12207 unsigned ArgMode = MI->getOperand(7).getImm();
12208 unsigned Align = MI->getOperand(8).getImm();
12210 // Memory Reference
12211 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12212 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12213 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12215 // Machine Information
12216 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12217 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12218 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12219 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12220 DebugLoc DL = MI->getDebugLoc();
12222 // struct va_list {
12225 // i64 overflow_area (address)
12226 // i64 reg_save_area (address)
12228 // sizeof(va_list) = 24
12229 // alignment(va_list) = 8
12231 unsigned TotalNumIntRegs = 6;
12232 unsigned TotalNumXMMRegs = 8;
12233 bool UseGPOffset = (ArgMode == 1);
12234 bool UseFPOffset = (ArgMode == 2);
12235 unsigned MaxOffset = TotalNumIntRegs * 8 +
12236 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12238 /* Align ArgSize to a multiple of 8 */
12239 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12240 bool NeedsAlign = (Align > 8);
12242 MachineBasicBlock *thisMBB = MBB;
12243 MachineBasicBlock *overflowMBB;
12244 MachineBasicBlock *offsetMBB;
12245 MachineBasicBlock *endMBB;
12247 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12248 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12249 unsigned OffsetReg = 0;
12251 if (!UseGPOffset && !UseFPOffset) {
12252 // If we only pull from the overflow region, we don't create a branch.
12253 // We don't need to alter control flow.
12254 OffsetDestReg = 0; // unused
12255 OverflowDestReg = DestReg;
12258 overflowMBB = thisMBB;
12261 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12262 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12263 // If not, pull from overflow_area. (branch to overflowMBB)
12268 // offsetMBB overflowMBB
12273 // Registers for the PHI in endMBB
12274 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12275 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12277 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12278 MachineFunction *MF = MBB->getParent();
12279 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12280 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12281 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12283 MachineFunction::iterator MBBIter = MBB;
12286 // Insert the new basic blocks
12287 MF->insert(MBBIter, offsetMBB);
12288 MF->insert(MBBIter, overflowMBB);
12289 MF->insert(MBBIter, endMBB);
12291 // Transfer the remainder of MBB and its successor edges to endMBB.
12292 endMBB->splice(endMBB->begin(), thisMBB,
12293 llvm::next(MachineBasicBlock::iterator(MI)),
12295 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12297 // Make offsetMBB and overflowMBB successors of thisMBB
12298 thisMBB->addSuccessor(offsetMBB);
12299 thisMBB->addSuccessor(overflowMBB);
12301 // endMBB is a successor of both offsetMBB and overflowMBB
12302 offsetMBB->addSuccessor(endMBB);
12303 overflowMBB->addSuccessor(endMBB);
12305 // Load the offset value into a register
12306 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12307 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12311 .addDisp(Disp, UseFPOffset ? 4 : 0)
12312 .addOperand(Segment)
12313 .setMemRefs(MMOBegin, MMOEnd);
12315 // Check if there is enough room left to pull this argument.
12316 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12318 .addImm(MaxOffset + 8 - ArgSizeA8);
12320 // Branch to "overflowMBB" if offset >= max
12321 // Fall through to "offsetMBB" otherwise
12322 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12323 .addMBB(overflowMBB);
12326 // In offsetMBB, emit code to use the reg_save_area.
12328 assert(OffsetReg != 0);
12330 // Read the reg_save_area address.
12331 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12332 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12337 .addOperand(Segment)
12338 .setMemRefs(MMOBegin, MMOEnd);
12340 // Zero-extend the offset
12341 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12342 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12345 .addImm(X86::sub_32bit);
12347 // Add the offset to the reg_save_area to get the final address.
12348 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12349 .addReg(OffsetReg64)
12350 .addReg(RegSaveReg);
12352 // Compute the offset for the next argument
12353 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12354 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12356 .addImm(UseFPOffset ? 16 : 8);
12358 // Store it back into the va_list.
12359 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12363 .addDisp(Disp, UseFPOffset ? 4 : 0)
12364 .addOperand(Segment)
12365 .addReg(NextOffsetReg)
12366 .setMemRefs(MMOBegin, MMOEnd);
12369 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12374 // Emit code to use overflow area
12377 // Load the overflow_area address into a register.
12378 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12379 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12384 .addOperand(Segment)
12385 .setMemRefs(MMOBegin, MMOEnd);
12387 // If we need to align it, do so. Otherwise, just copy the address
12388 // to OverflowDestReg.
12390 // Align the overflow address
12391 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12392 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12394 // aligned_addr = (addr + (align-1)) & ~(align-1)
12395 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12396 .addReg(OverflowAddrReg)
12399 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12401 .addImm(~(uint64_t)(Align-1));
12403 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12404 .addReg(OverflowAddrReg);
12407 // Compute the next overflow address after this argument.
12408 // (the overflow address should be kept 8-byte aligned)
12409 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12410 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12411 .addReg(OverflowDestReg)
12412 .addImm(ArgSizeA8);
12414 // Store the new overflow address.
12415 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12420 .addOperand(Segment)
12421 .addReg(NextAddrReg)
12422 .setMemRefs(MMOBegin, MMOEnd);
12424 // If we branched, emit the PHI to the front of endMBB.
12426 BuildMI(*endMBB, endMBB->begin(), DL,
12427 TII->get(X86::PHI), DestReg)
12428 .addReg(OffsetDestReg).addMBB(offsetMBB)
12429 .addReg(OverflowDestReg).addMBB(overflowMBB);
12432 // Erase the pseudo instruction
12433 MI->eraseFromParent();
12438 MachineBasicBlock *
12439 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12441 MachineBasicBlock *MBB) const {
12442 // Emit code to save XMM registers to the stack. The ABI says that the
12443 // number of registers to save is given in %al, so it's theoretically
12444 // possible to do an indirect jump trick to avoid saving all of them,
12445 // however this code takes a simpler approach and just executes all
12446 // of the stores if %al is non-zero. It's less code, and it's probably
12447 // easier on the hardware branch predictor, and stores aren't all that
12448 // expensive anyway.
12450 // Create the new basic blocks. One block contains all the XMM stores,
12451 // and one block is the final destination regardless of whether any
12452 // stores were performed.
12453 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12454 MachineFunction *F = MBB->getParent();
12455 MachineFunction::iterator MBBIter = MBB;
12457 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12458 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12459 F->insert(MBBIter, XMMSaveMBB);
12460 F->insert(MBBIter, EndMBB);
12462 // Transfer the remainder of MBB and its successor edges to EndMBB.
12463 EndMBB->splice(EndMBB->begin(), MBB,
12464 llvm::next(MachineBasicBlock::iterator(MI)),
12466 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12468 // The original block will now fall through to the XMM save block.
12469 MBB->addSuccessor(XMMSaveMBB);
12470 // The XMMSaveMBB will fall through to the end block.
12471 XMMSaveMBB->addSuccessor(EndMBB);
12473 // Now add the instructions.
12474 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12475 DebugLoc DL = MI->getDebugLoc();
12477 unsigned CountReg = MI->getOperand(0).getReg();
12478 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12479 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12481 if (!Subtarget->isTargetWin64()) {
12482 // If %al is 0, branch around the XMM save block.
12483 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12484 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12485 MBB->addSuccessor(EndMBB);
12488 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12489 // In the XMM save block, save all the XMM argument registers.
12490 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12491 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12492 MachineMemOperand *MMO =
12493 F->getMachineMemOperand(
12494 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12495 MachineMemOperand::MOStore,
12496 /*Size=*/16, /*Align=*/16);
12497 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12498 .addFrameIndex(RegSaveFrameIndex)
12499 .addImm(/*Scale=*/1)
12500 .addReg(/*IndexReg=*/0)
12501 .addImm(/*Disp=*/Offset)
12502 .addReg(/*Segment=*/0)
12503 .addReg(MI->getOperand(i).getReg())
12504 .addMemOperand(MMO);
12507 MI->eraseFromParent(); // The pseudo instruction is gone now.
12512 // The EFLAGS operand of SelectItr might be missing a kill marker
12513 // because there were multiple uses of EFLAGS, and ISel didn't know
12514 // which to mark. Figure out whether SelectItr should have had a
12515 // kill marker, and set it if it should. Returns the correct kill
12517 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12518 MachineBasicBlock* BB,
12519 const TargetRegisterInfo* TRI) {
12520 // Scan forward through BB for a use/def of EFLAGS.
12521 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12522 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12523 const MachineInstr& mi = *miI;
12524 if (mi.readsRegister(X86::EFLAGS))
12526 if (mi.definesRegister(X86::EFLAGS))
12527 break; // Should have kill-flag - update below.
12530 // If we hit the end of the block, check whether EFLAGS is live into a
12532 if (miI == BB->end()) {
12533 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12534 sEnd = BB->succ_end();
12535 sItr != sEnd; ++sItr) {
12536 MachineBasicBlock* succ = *sItr;
12537 if (succ->isLiveIn(X86::EFLAGS))
12542 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12543 // out. SelectMI should have a kill flag on EFLAGS.
12544 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12548 MachineBasicBlock *
12549 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12550 MachineBasicBlock *BB) const {
12551 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12552 DebugLoc DL = MI->getDebugLoc();
12554 // To "insert" a SELECT_CC instruction, we actually have to insert the
12555 // diamond control-flow pattern. The incoming instruction knows the
12556 // destination vreg to set, the condition code register to branch on, the
12557 // true/false values to select between, and a branch opcode to use.
12558 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12559 MachineFunction::iterator It = BB;
12565 // cmpTY ccX, r1, r2
12567 // fallthrough --> copy0MBB
12568 MachineBasicBlock *thisMBB = BB;
12569 MachineFunction *F = BB->getParent();
12570 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12571 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12572 F->insert(It, copy0MBB);
12573 F->insert(It, sinkMBB);
12575 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12576 // live into the sink and copy blocks.
12577 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12578 if (!MI->killsRegister(X86::EFLAGS) &&
12579 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12580 copy0MBB->addLiveIn(X86::EFLAGS);
12581 sinkMBB->addLiveIn(X86::EFLAGS);
12584 // Transfer the remainder of BB and its successor edges to sinkMBB.
12585 sinkMBB->splice(sinkMBB->begin(), BB,
12586 llvm::next(MachineBasicBlock::iterator(MI)),
12588 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12590 // Add the true and fallthrough blocks as its successors.
12591 BB->addSuccessor(copy0MBB);
12592 BB->addSuccessor(sinkMBB);
12594 // Create the conditional branch instruction.
12596 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12597 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12600 // %FalseValue = ...
12601 // # fallthrough to sinkMBB
12602 copy0MBB->addSuccessor(sinkMBB);
12605 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12607 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12608 TII->get(X86::PHI), MI->getOperand(0).getReg())
12609 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12610 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12612 MI->eraseFromParent(); // The pseudo instruction is gone now.
12616 MachineBasicBlock *
12617 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12618 bool Is64Bit) const {
12619 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12620 DebugLoc DL = MI->getDebugLoc();
12621 MachineFunction *MF = BB->getParent();
12622 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12624 assert(getTargetMachine().Options.EnableSegmentedStacks);
12626 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12627 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12630 // ... [Till the alloca]
12631 // If stacklet is not large enough, jump to mallocMBB
12634 // Allocate by subtracting from RSP
12635 // Jump to continueMBB
12638 // Allocate by call to runtime
12642 // [rest of original BB]
12645 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12646 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12647 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12649 MachineRegisterInfo &MRI = MF->getRegInfo();
12650 const TargetRegisterClass *AddrRegClass =
12651 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12653 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12654 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12655 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12656 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12657 sizeVReg = MI->getOperand(1).getReg(),
12658 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12660 MachineFunction::iterator MBBIter = BB;
12663 MF->insert(MBBIter, bumpMBB);
12664 MF->insert(MBBIter, mallocMBB);
12665 MF->insert(MBBIter, continueMBB);
12667 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12668 (MachineBasicBlock::iterator(MI)), BB->end());
12669 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12671 // Add code to the main basic block to check if the stack limit has been hit,
12672 // and if so, jump to mallocMBB otherwise to bumpMBB.
12673 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12674 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12675 .addReg(tmpSPVReg).addReg(sizeVReg);
12676 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12677 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12678 .addReg(SPLimitVReg);
12679 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12681 // bumpMBB simply decreases the stack pointer, since we know the current
12682 // stacklet has enough space.
12683 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12684 .addReg(SPLimitVReg);
12685 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12686 .addReg(SPLimitVReg);
12687 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12689 // Calls into a routine in libgcc to allocate more space from the heap.
12690 const uint32_t *RegMask =
12691 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12693 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12695 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12696 .addExternalSymbol("__morestack_allocate_stack_space")
12697 .addRegMask(RegMask)
12698 .addReg(X86::RDI, RegState::Implicit)
12699 .addReg(X86::RAX, RegState::ImplicitDefine);
12701 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12703 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12704 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12705 .addExternalSymbol("__morestack_allocate_stack_space")
12706 .addRegMask(RegMask)
12707 .addReg(X86::EAX, RegState::ImplicitDefine);
12711 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12714 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12715 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12716 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12718 // Set up the CFG correctly.
12719 BB->addSuccessor(bumpMBB);
12720 BB->addSuccessor(mallocMBB);
12721 mallocMBB->addSuccessor(continueMBB);
12722 bumpMBB->addSuccessor(continueMBB);
12724 // Take care of the PHI nodes.
12725 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12726 MI->getOperand(0).getReg())
12727 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12728 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12730 // Delete the original pseudo instruction.
12731 MI->eraseFromParent();
12734 return continueMBB;
12737 MachineBasicBlock *
12738 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12739 MachineBasicBlock *BB) const {
12740 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12741 DebugLoc DL = MI->getDebugLoc();
12743 assert(!Subtarget->isTargetEnvMacho());
12745 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12746 // non-trivial part is impdef of ESP.
12748 if (Subtarget->isTargetWin64()) {
12749 if (Subtarget->isTargetCygMing()) {
12750 // ___chkstk(Mingw64):
12751 // Clobbers R10, R11, RAX and EFLAGS.
12753 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12754 .addExternalSymbol("___chkstk")
12755 .addReg(X86::RAX, RegState::Implicit)
12756 .addReg(X86::RSP, RegState::Implicit)
12757 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12758 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12759 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12761 // __chkstk(MSVCRT): does not update stack pointer.
12762 // Clobbers R10, R11 and EFLAGS.
12763 // FIXME: RAX(allocated size) might be reused and not killed.
12764 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12765 .addExternalSymbol("__chkstk")
12766 .addReg(X86::RAX, RegState::Implicit)
12767 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12768 // RAX has the offset to subtracted from RSP.
12769 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12774 const char *StackProbeSymbol =
12775 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12777 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12778 .addExternalSymbol(StackProbeSymbol)
12779 .addReg(X86::EAX, RegState::Implicit)
12780 .addReg(X86::ESP, RegState::Implicit)
12781 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12782 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12783 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12786 MI->eraseFromParent(); // The pseudo instruction is gone now.
12790 MachineBasicBlock *
12791 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12792 MachineBasicBlock *BB) const {
12793 // This is pretty easy. We're taking the value that we received from
12794 // our load from the relocation, sticking it in either RDI (x86-64)
12795 // or EAX and doing an indirect call. The return value will then
12796 // be in the normal return register.
12797 const X86InstrInfo *TII
12798 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12799 DebugLoc DL = MI->getDebugLoc();
12800 MachineFunction *F = BB->getParent();
12802 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12803 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12805 // Get a register mask for the lowered call.
12806 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12807 // proper register mask.
12808 const uint32_t *RegMask =
12809 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12810 if (Subtarget->is64Bit()) {
12811 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12812 TII->get(X86::MOV64rm), X86::RDI)
12814 .addImm(0).addReg(0)
12815 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12816 MI->getOperand(3).getTargetFlags())
12818 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12819 addDirectMem(MIB, X86::RDI);
12820 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12821 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12822 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12823 TII->get(X86::MOV32rm), X86::EAX)
12825 .addImm(0).addReg(0)
12826 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12827 MI->getOperand(3).getTargetFlags())
12829 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12830 addDirectMem(MIB, X86::EAX);
12831 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12833 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12834 TII->get(X86::MOV32rm), X86::EAX)
12835 .addReg(TII->getGlobalBaseReg(F))
12836 .addImm(0).addReg(0)
12837 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12838 MI->getOperand(3).getTargetFlags())
12840 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12841 addDirectMem(MIB, X86::EAX);
12842 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12845 MI->eraseFromParent(); // The pseudo instruction is gone now.
12849 MachineBasicBlock *
12850 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12851 MachineBasicBlock *BB) const {
12852 switch (MI->getOpcode()) {
12853 default: llvm_unreachable("Unexpected instr type to insert");
12854 case X86::TAILJMPd64:
12855 case X86::TAILJMPr64:
12856 case X86::TAILJMPm64:
12857 llvm_unreachable("TAILJMP64 would not be touched here.");
12858 case X86::TCRETURNdi64:
12859 case X86::TCRETURNri64:
12860 case X86::TCRETURNmi64:
12862 case X86::WIN_ALLOCA:
12863 return EmitLoweredWinAlloca(MI, BB);
12864 case X86::SEG_ALLOCA_32:
12865 return EmitLoweredSegAlloca(MI, BB, false);
12866 case X86::SEG_ALLOCA_64:
12867 return EmitLoweredSegAlloca(MI, BB, true);
12868 case X86::TLSCall_32:
12869 case X86::TLSCall_64:
12870 return EmitLoweredTLSCall(MI, BB);
12871 case X86::CMOV_GR8:
12872 case X86::CMOV_FR32:
12873 case X86::CMOV_FR64:
12874 case X86::CMOV_V4F32:
12875 case X86::CMOV_V2F64:
12876 case X86::CMOV_V2I64:
12877 case X86::CMOV_V8F32:
12878 case X86::CMOV_V4F64:
12879 case X86::CMOV_V4I64:
12880 case X86::CMOV_GR16:
12881 case X86::CMOV_GR32:
12882 case X86::CMOV_RFP32:
12883 case X86::CMOV_RFP64:
12884 case X86::CMOV_RFP80:
12885 return EmitLoweredSelect(MI, BB);
12887 case X86::FP32_TO_INT16_IN_MEM:
12888 case X86::FP32_TO_INT32_IN_MEM:
12889 case X86::FP32_TO_INT64_IN_MEM:
12890 case X86::FP64_TO_INT16_IN_MEM:
12891 case X86::FP64_TO_INT32_IN_MEM:
12892 case X86::FP64_TO_INT64_IN_MEM:
12893 case X86::FP80_TO_INT16_IN_MEM:
12894 case X86::FP80_TO_INT32_IN_MEM:
12895 case X86::FP80_TO_INT64_IN_MEM: {
12896 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12897 DebugLoc DL = MI->getDebugLoc();
12899 // Change the floating point control register to use "round towards zero"
12900 // mode when truncating to an integer value.
12901 MachineFunction *F = BB->getParent();
12902 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12903 addFrameReference(BuildMI(*BB, MI, DL,
12904 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12906 // Load the old value of the high byte of the control word...
12908 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12909 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12912 // Set the high part to be round to zero...
12913 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12916 // Reload the modified control word now...
12917 addFrameReference(BuildMI(*BB, MI, DL,
12918 TII->get(X86::FLDCW16m)), CWFrameIdx);
12920 // Restore the memory image of control word to original value
12921 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12924 // Get the X86 opcode to use.
12926 switch (MI->getOpcode()) {
12927 default: llvm_unreachable("illegal opcode!");
12928 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12929 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12930 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12931 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12932 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12933 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12934 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12935 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12936 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12940 MachineOperand &Op = MI->getOperand(0);
12942 AM.BaseType = X86AddressMode::RegBase;
12943 AM.Base.Reg = Op.getReg();
12945 AM.BaseType = X86AddressMode::FrameIndexBase;
12946 AM.Base.FrameIndex = Op.getIndex();
12948 Op = MI->getOperand(1);
12950 AM.Scale = Op.getImm();
12951 Op = MI->getOperand(2);
12953 AM.IndexReg = Op.getImm();
12954 Op = MI->getOperand(3);
12955 if (Op.isGlobal()) {
12956 AM.GV = Op.getGlobal();
12958 AM.Disp = Op.getImm();
12960 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12961 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12963 // Reload the original control word now.
12964 addFrameReference(BuildMI(*BB, MI, DL,
12965 TII->get(X86::FLDCW16m)), CWFrameIdx);
12967 MI->eraseFromParent(); // The pseudo instruction is gone now.
12970 // String/text processing lowering.
12971 case X86::PCMPISTRM128REG:
12972 case X86::VPCMPISTRM128REG:
12973 case X86::PCMPISTRM128MEM:
12974 case X86::VPCMPISTRM128MEM:
12975 case X86::PCMPESTRM128REG:
12976 case X86::VPCMPESTRM128REG:
12977 case X86::PCMPESTRM128MEM:
12978 case X86::VPCMPESTRM128MEM: {
12981 switch (MI->getOpcode()) {
12982 default: llvm_unreachable("illegal opcode!");
12983 case X86::PCMPISTRM128REG:
12984 case X86::VPCMPISTRM128REG:
12985 NumArgs = 3; MemArg = false; break;
12986 case X86::PCMPISTRM128MEM:
12987 case X86::VPCMPISTRM128MEM:
12988 NumArgs = 3; MemArg = true; break;
12989 case X86::PCMPESTRM128REG:
12990 case X86::VPCMPESTRM128REG:
12991 NumArgs = 5; MemArg = false; break;
12992 case X86::PCMPESTRM128MEM:
12993 case X86::VPCMPESTRM128MEM:
12994 NumArgs = 5; MemArg = true; break;
12996 return EmitPCMP(MI, BB, NumArgs, MemArg);
12999 // Thread synchronization.
13001 return EmitMonitor(MI, BB);
13003 // Atomic Lowering.
13004 case X86::ATOMMIN32:
13005 case X86::ATOMMAX32:
13006 case X86::ATOMUMIN32:
13007 case X86::ATOMUMAX32:
13008 case X86::ATOMMIN16:
13009 case X86::ATOMMAX16:
13010 case X86::ATOMUMIN16:
13011 case X86::ATOMUMAX16:
13012 case X86::ATOMMIN64:
13013 case X86::ATOMMAX64:
13014 case X86::ATOMUMIN64:
13015 case X86::ATOMUMAX64: {
13017 switch (MI->getOpcode()) {
13018 default: llvm_unreachable("illegal opcode!");
13019 case X86::ATOMMIN32: Opc = X86::CMOVL32rr; break;
13020 case X86::ATOMMAX32: Opc = X86::CMOVG32rr; break;
13021 case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13022 case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13023 case X86::ATOMMIN16: Opc = X86::CMOVL16rr; break;
13024 case X86::ATOMMAX16: Opc = X86::CMOVG16rr; break;
13025 case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13026 case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13027 case X86::ATOMMIN64: Opc = X86::CMOVL64rr; break;
13028 case X86::ATOMMAX64: Opc = X86::CMOVG64rr; break;
13029 case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13030 case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13031 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13033 return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13036 case X86::ATOMAND32:
13037 case X86::ATOMOR32:
13038 case X86::ATOMXOR32:
13039 case X86::ATOMNAND32: {
13040 bool Invert = false;
13041 unsigned RegOpc, ImmOpc;
13042 switch (MI->getOpcode()) {
13043 default: llvm_unreachable("illegal opcode!");
13044 case X86::ATOMAND32:
13045 RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13046 case X86::ATOMOR32:
13047 RegOpc = X86::OR32rr; ImmOpc = X86::OR32ri; break;
13048 case X86::ATOMXOR32:
13049 RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13050 case X86::ATOMNAND32:
13051 RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13053 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13054 X86::MOV32rm, X86::LCMPXCHG32,
13055 X86::NOT32r, X86::EAX,
13056 &X86::GR32RegClass, Invert);
13059 case X86::ATOMAND16:
13060 case X86::ATOMOR16:
13061 case X86::ATOMXOR16:
13062 case X86::ATOMNAND16: {
13063 bool Invert = false;
13064 unsigned RegOpc, ImmOpc;
13065 switch (MI->getOpcode()) {
13066 default: llvm_unreachable("illegal opcode!");
13067 case X86::ATOMAND16:
13068 RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13069 case X86::ATOMOR16:
13070 RegOpc = X86::OR16rr; ImmOpc = X86::OR16ri; break;
13071 case X86::ATOMXOR16:
13072 RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13073 case X86::ATOMNAND16:
13074 RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13076 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13077 X86::MOV16rm, X86::LCMPXCHG16,
13078 X86::NOT16r, X86::AX,
13079 &X86::GR16RegClass, Invert);
13082 case X86::ATOMAND8:
13084 case X86::ATOMXOR8:
13085 case X86::ATOMNAND8: {
13086 bool Invert = false;
13087 unsigned RegOpc, ImmOpc;
13088 switch (MI->getOpcode()) {
13089 default: llvm_unreachable("illegal opcode!");
13090 case X86::ATOMAND8:
13091 RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13093 RegOpc = X86::OR8rr; ImmOpc = X86::OR8ri; break;
13094 case X86::ATOMXOR8:
13095 RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13096 case X86::ATOMNAND8:
13097 RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13099 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13100 X86::MOV8rm, X86::LCMPXCHG8,
13101 X86::NOT8r, X86::AL,
13102 &X86::GR8RegClass, Invert);
13105 // This group is for 64-bit host.
13106 case X86::ATOMAND64:
13107 case X86::ATOMOR64:
13108 case X86::ATOMXOR64:
13109 case X86::ATOMNAND64: {
13110 bool Invert = false;
13111 unsigned RegOpc, ImmOpc;
13112 switch (MI->getOpcode()) {
13113 default: llvm_unreachable("illegal opcode!");
13114 case X86::ATOMAND64:
13115 RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13116 case X86::ATOMOR64:
13117 RegOpc = X86::OR64rr; ImmOpc = X86::OR64ri32; break;
13118 case X86::ATOMXOR64:
13119 RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13120 case X86::ATOMNAND64:
13121 RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13123 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13124 X86::MOV64rm, X86::LCMPXCHG64,
13125 X86::NOT64r, X86::RAX,
13126 &X86::GR64RegClass, Invert);
13129 // This group does 64-bit operations on a 32-bit host.
13130 case X86::ATOMAND6432:
13131 case X86::ATOMOR6432:
13132 case X86::ATOMXOR6432:
13133 case X86::ATOMNAND6432:
13134 case X86::ATOMADD6432:
13135 case X86::ATOMSUB6432:
13136 case X86::ATOMSWAP6432: {
13137 bool Invert = false;
13138 unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13139 switch (MI->getOpcode()) {
13140 default: llvm_unreachable("illegal opcode!");
13141 case X86::ATOMAND6432:
13142 RegOpcL = RegOpcH = X86::AND32rr;
13143 ImmOpcL = ImmOpcH = X86::AND32ri;
13145 case X86::ATOMOR6432:
13146 RegOpcL = RegOpcH = X86::OR32rr;
13147 ImmOpcL = ImmOpcH = X86::OR32ri;
13149 case X86::ATOMXOR6432:
13150 RegOpcL = RegOpcH = X86::XOR32rr;
13151 ImmOpcL = ImmOpcH = X86::XOR32ri;
13153 case X86::ATOMNAND6432:
13154 RegOpcL = RegOpcH = X86::AND32rr;
13155 ImmOpcL = ImmOpcH = X86::AND32ri;
13158 case X86::ATOMADD6432:
13159 RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13160 ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13162 case X86::ATOMSUB6432:
13163 RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13164 ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13166 case X86::ATOMSWAP6432:
13167 RegOpcL = RegOpcH = X86::MOV32rr;
13168 ImmOpcL = ImmOpcH = X86::MOV32ri;
13171 return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13172 ImmOpcL, ImmOpcH, Invert);
13175 case X86::VASTART_SAVE_XMM_REGS:
13176 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13178 case X86::VAARG_64:
13179 return EmitVAARG64WithCustomInserter(MI, BB);
13183 //===----------------------------------------------------------------------===//
13184 // X86 Optimization Hooks
13185 //===----------------------------------------------------------------------===//
13187 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13190 const SelectionDAG &DAG,
13191 unsigned Depth) const {
13192 unsigned BitWidth = KnownZero.getBitWidth();
13193 unsigned Opc = Op.getOpcode();
13194 assert((Opc >= ISD::BUILTIN_OP_END ||
13195 Opc == ISD::INTRINSIC_WO_CHAIN ||
13196 Opc == ISD::INTRINSIC_W_CHAIN ||
13197 Opc == ISD::INTRINSIC_VOID) &&
13198 "Should use MaskedValueIsZero if you don't know whether Op"
13199 " is a target node!");
13201 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13215 // These nodes' second result is a boolean.
13216 if (Op.getResNo() == 0)
13219 case X86ISD::SETCC:
13220 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13222 case ISD::INTRINSIC_WO_CHAIN: {
13223 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13224 unsigned NumLoBits = 0;
13227 case Intrinsic::x86_sse_movmsk_ps:
13228 case Intrinsic::x86_avx_movmsk_ps_256:
13229 case Intrinsic::x86_sse2_movmsk_pd:
13230 case Intrinsic::x86_avx_movmsk_pd_256:
13231 case Intrinsic::x86_mmx_pmovmskb:
13232 case Intrinsic::x86_sse2_pmovmskb_128:
13233 case Intrinsic::x86_avx2_pmovmskb: {
13234 // High bits of movmskp{s|d}, pmovmskb are known zero.
13236 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13237 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13238 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13239 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13240 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13241 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13242 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13243 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13245 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13254 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13255 unsigned Depth) const {
13256 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13257 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13258 return Op.getValueType().getScalarType().getSizeInBits();
13264 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13265 /// node is a GlobalAddress + offset.
13266 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13267 const GlobalValue* &GA,
13268 int64_t &Offset) const {
13269 if (N->getOpcode() == X86ISD::Wrapper) {
13270 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13271 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13272 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13276 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13279 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13280 /// same as extracting the high 128-bit part of 256-bit vector and then
13281 /// inserting the result into the low part of a new 256-bit vector
13282 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13283 EVT VT = SVOp->getValueType(0);
13284 unsigned NumElems = VT.getVectorNumElements();
13286 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13287 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13288 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13289 SVOp->getMaskElt(j) >= 0)
13295 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13296 /// same as extracting the low 128-bit part of 256-bit vector and then
13297 /// inserting the result into the high part of a new 256-bit vector
13298 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13299 EVT VT = SVOp->getValueType(0);
13300 unsigned NumElems = VT.getVectorNumElements();
13302 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13303 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13304 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13305 SVOp->getMaskElt(j) >= 0)
13311 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13312 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13313 TargetLowering::DAGCombinerInfo &DCI,
13314 const X86Subtarget* Subtarget) {
13315 DebugLoc dl = N->getDebugLoc();
13316 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13317 SDValue V1 = SVOp->getOperand(0);
13318 SDValue V2 = SVOp->getOperand(1);
13319 EVT VT = SVOp->getValueType(0);
13320 unsigned NumElems = VT.getVectorNumElements();
13322 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13323 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13327 // V UNDEF BUILD_VECTOR UNDEF
13329 // CONCAT_VECTOR CONCAT_VECTOR
13332 // RESULT: V + zero extended
13334 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13335 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13336 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13339 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13342 // To match the shuffle mask, the first half of the mask should
13343 // be exactly the first vector, and all the rest a splat with the
13344 // first element of the second one.
13345 for (unsigned i = 0; i != NumElems/2; ++i)
13346 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13347 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13350 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13351 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13352 if (Ld->hasNUsesOfValue(1, 0)) {
13353 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13354 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13356 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13358 Ld->getPointerInfo(),
13359 Ld->getAlignment(),
13360 false/*isVolatile*/, true/*ReadMem*/,
13361 false/*WriteMem*/);
13362 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13366 // Emit a zeroed vector and insert the desired subvector on its
13368 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13369 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13370 return DCI.CombineTo(N, InsV);
13373 //===--------------------------------------------------------------------===//
13374 // Combine some shuffles into subvector extracts and inserts:
13377 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13378 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13379 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13380 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13381 return DCI.CombineTo(N, InsV);
13384 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13385 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13386 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13387 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13388 return DCI.CombineTo(N, InsV);
13394 /// PerformShuffleCombine - Performs several different shuffle combines.
13395 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13396 TargetLowering::DAGCombinerInfo &DCI,
13397 const X86Subtarget *Subtarget) {
13398 DebugLoc dl = N->getDebugLoc();
13399 EVT VT = N->getValueType(0);
13401 // Don't create instructions with illegal types after legalize types has run.
13402 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13403 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13406 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13407 if (Subtarget->hasAVX() && VT.is256BitVector() &&
13408 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13409 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13411 // Only handle 128 wide vector from here on.
13412 if (!VT.is128BitVector())
13415 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13416 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13417 // consecutive, non-overlapping, and in the right order.
13418 SmallVector<SDValue, 16> Elts;
13419 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13420 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13422 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13426 /// DCI, PerformTruncateCombine - Converts truncate operation to
13427 /// a sequence of vector shuffle operations.
13428 /// It is possible when we truncate 256-bit vector to 128-bit vector
13430 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13431 DAGCombinerInfo &DCI) const {
13432 if (!DCI.isBeforeLegalizeOps())
13435 if (!Subtarget->hasAVX())
13438 EVT VT = N->getValueType(0);
13439 SDValue Op = N->getOperand(0);
13440 EVT OpVT = Op.getValueType();
13441 DebugLoc dl = N->getDebugLoc();
13443 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13445 if (Subtarget->hasAVX2()) {
13446 // AVX2: v4i64 -> v4i32
13449 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13451 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13452 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13455 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13456 DAG.getIntPtrConstant(0));
13459 // AVX: v4i64 -> v4i32
13460 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13461 DAG.getIntPtrConstant(0));
13463 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13464 DAG.getIntPtrConstant(2));
13466 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13467 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13470 static const int ShufMask1[] = {0, 2, 0, 0};
13472 SDValue Undef = DAG.getUNDEF(VT);
13473 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13474 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13477 static const int ShufMask2[] = {0, 1, 4, 5};
13479 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13482 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13484 if (Subtarget->hasAVX2()) {
13485 // AVX2: v8i32 -> v8i16
13487 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13490 SmallVector<SDValue,32> pshufbMask;
13491 for (unsigned i = 0; i < 2; ++i) {
13492 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13493 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13494 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13495 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13496 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13497 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13498 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13499 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13500 for (unsigned j = 0; j < 8; ++j)
13501 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13503 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13504 &pshufbMask[0], 32);
13505 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13507 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13509 static const int ShufMask[] = {0, 2, -1, -1};
13510 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13513 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13514 DAG.getIntPtrConstant(0));
13516 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13519 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13520 DAG.getIntPtrConstant(0));
13522 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13523 DAG.getIntPtrConstant(4));
13525 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13526 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13529 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13530 -1, -1, -1, -1, -1, -1, -1, -1};
13532 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13533 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13534 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13536 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13537 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13540 static const int ShufMask2[] = {0, 1, 4, 5};
13542 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13543 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13549 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13550 /// specific shuffle of a load can be folded into a single element load.
13551 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13552 /// shuffles have been customed lowered so we need to handle those here.
13553 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13554 TargetLowering::DAGCombinerInfo &DCI) {
13555 if (DCI.isBeforeLegalizeOps())
13558 SDValue InVec = N->getOperand(0);
13559 SDValue EltNo = N->getOperand(1);
13561 if (!isa<ConstantSDNode>(EltNo))
13564 EVT VT = InVec.getValueType();
13566 bool HasShuffleIntoBitcast = false;
13567 if (InVec.getOpcode() == ISD::BITCAST) {
13568 // Don't duplicate a load with other uses.
13569 if (!InVec.hasOneUse())
13571 EVT BCVT = InVec.getOperand(0).getValueType();
13572 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13574 InVec = InVec.getOperand(0);
13575 HasShuffleIntoBitcast = true;
13578 if (!isTargetShuffle(InVec.getOpcode()))
13581 // Don't duplicate a load with other uses.
13582 if (!InVec.hasOneUse())
13585 SmallVector<int, 16> ShuffleMask;
13587 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13591 // Select the input vector, guarding against out of range extract vector.
13592 unsigned NumElems = VT.getVectorNumElements();
13593 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13594 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13595 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13596 : InVec.getOperand(1);
13598 // If inputs to shuffle are the same for both ops, then allow 2 uses
13599 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13601 if (LdNode.getOpcode() == ISD::BITCAST) {
13602 // Don't duplicate a load with other uses.
13603 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13606 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13607 LdNode = LdNode.getOperand(0);
13610 if (!ISD::isNormalLoad(LdNode.getNode()))
13613 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13615 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13618 if (HasShuffleIntoBitcast) {
13619 // If there's a bitcast before the shuffle, check if the load type and
13620 // alignment is valid.
13621 unsigned Align = LN0->getAlignment();
13622 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13623 unsigned NewAlign = TLI.getTargetData()->
13624 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13626 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13630 // All checks match so transform back to vector_shuffle so that DAG combiner
13631 // can finish the job
13632 DebugLoc dl = N->getDebugLoc();
13634 // Create shuffle node taking into account the case that its a unary shuffle
13635 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13636 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13637 InVec.getOperand(0), Shuffle,
13639 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13640 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13644 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13645 /// generation and convert it from being a bunch of shuffles and extracts
13646 /// to a simple store and scalar loads to extract the elements.
13647 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13648 TargetLowering::DAGCombinerInfo &DCI) {
13649 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13650 if (NewOp.getNode())
13653 SDValue InputVector = N->getOperand(0);
13655 // Only operate on vectors of 4 elements, where the alternative shuffling
13656 // gets to be more expensive.
13657 if (InputVector.getValueType() != MVT::v4i32)
13660 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13661 // single use which is a sign-extend or zero-extend, and all elements are
13663 SmallVector<SDNode *, 4> Uses;
13664 unsigned ExtractedElements = 0;
13665 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13666 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13667 if (UI.getUse().getResNo() != InputVector.getResNo())
13670 SDNode *Extract = *UI;
13671 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13674 if (Extract->getValueType(0) != MVT::i32)
13676 if (!Extract->hasOneUse())
13678 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13679 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13681 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13684 // Record which element was extracted.
13685 ExtractedElements |=
13686 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13688 Uses.push_back(Extract);
13691 // If not all the elements were used, this may not be worthwhile.
13692 if (ExtractedElements != 15)
13695 // Ok, we've now decided to do the transformation.
13696 DebugLoc dl = InputVector.getDebugLoc();
13698 // Store the value to a temporary stack slot.
13699 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13700 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13701 MachinePointerInfo(), false, false, 0);
13703 // Replace each use (extract) with a load of the appropriate element.
13704 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13705 UE = Uses.end(); UI != UE; ++UI) {
13706 SDNode *Extract = *UI;
13708 // cOMpute the element's address.
13709 SDValue Idx = Extract->getOperand(1);
13711 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13712 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13714 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13716 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13717 StackPtr, OffsetVal);
13719 // Load the scalar.
13720 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13721 ScalarAddr, MachinePointerInfo(),
13722 false, false, false, 0);
13724 // Replace the exact with the load.
13725 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13728 // The replacement was made in place; don't return anything.
13732 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13734 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13735 TargetLowering::DAGCombinerInfo &DCI,
13736 const X86Subtarget *Subtarget) {
13737 DebugLoc DL = N->getDebugLoc();
13738 SDValue Cond = N->getOperand(0);
13739 // Get the LHS/RHS of the select.
13740 SDValue LHS = N->getOperand(1);
13741 SDValue RHS = N->getOperand(2);
13742 EVT VT = LHS.getValueType();
13744 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13745 // instructions match the semantics of the common C idiom x<y?x:y but not
13746 // x<=y?x:y, because of how they handle negative zero (which can be
13747 // ignored in unsafe-math mode).
13748 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13749 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13750 (Subtarget->hasSSE2() ||
13751 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13752 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13754 unsigned Opcode = 0;
13755 // Check for x CC y ? x : y.
13756 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13757 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13761 // Converting this to a min would handle NaNs incorrectly, and swapping
13762 // the operands would cause it to handle comparisons between positive
13763 // and negative zero incorrectly.
13764 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13765 if (!DAG.getTarget().Options.UnsafeFPMath &&
13766 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13768 std::swap(LHS, RHS);
13770 Opcode = X86ISD::FMIN;
13773 // Converting this to a min would handle comparisons between positive
13774 // and negative zero incorrectly.
13775 if (!DAG.getTarget().Options.UnsafeFPMath &&
13776 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13778 Opcode = X86ISD::FMIN;
13781 // Converting this to a min would handle both negative zeros and NaNs
13782 // incorrectly, but we can swap the operands to fix both.
13783 std::swap(LHS, RHS);
13787 Opcode = X86ISD::FMIN;
13791 // Converting this to a max would handle comparisons between positive
13792 // and negative zero incorrectly.
13793 if (!DAG.getTarget().Options.UnsafeFPMath &&
13794 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13796 Opcode = X86ISD::FMAX;
13799 // Converting this to a max would handle NaNs incorrectly, and swapping
13800 // the operands would cause it to handle comparisons between positive
13801 // and negative zero incorrectly.
13802 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13803 if (!DAG.getTarget().Options.UnsafeFPMath &&
13804 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13806 std::swap(LHS, RHS);
13808 Opcode = X86ISD::FMAX;
13811 // Converting this to a max would handle both negative zeros and NaNs
13812 // incorrectly, but we can swap the operands to fix both.
13813 std::swap(LHS, RHS);
13817 Opcode = X86ISD::FMAX;
13820 // Check for x CC y ? y : x -- a min/max with reversed arms.
13821 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13822 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13826 // Converting this to a min would handle comparisons between positive
13827 // and negative zero incorrectly, and swapping the operands would
13828 // cause it to handle NaNs incorrectly.
13829 if (!DAG.getTarget().Options.UnsafeFPMath &&
13830 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13831 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13833 std::swap(LHS, RHS);
13835 Opcode = X86ISD::FMIN;
13838 // Converting this to a min would handle NaNs incorrectly.
13839 if (!DAG.getTarget().Options.UnsafeFPMath &&
13840 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13842 Opcode = X86ISD::FMIN;
13845 // Converting this to a min would handle both negative zeros and NaNs
13846 // incorrectly, but we can swap the operands to fix both.
13847 std::swap(LHS, RHS);
13851 Opcode = X86ISD::FMIN;
13855 // Converting this to a max would handle NaNs incorrectly.
13856 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13858 Opcode = X86ISD::FMAX;
13861 // Converting this to a max would handle comparisons between positive
13862 // and negative zero incorrectly, and swapping the operands would
13863 // cause it to handle NaNs incorrectly.
13864 if (!DAG.getTarget().Options.UnsafeFPMath &&
13865 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13866 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13868 std::swap(LHS, RHS);
13870 Opcode = X86ISD::FMAX;
13873 // Converting this to a max would handle both negative zeros and NaNs
13874 // incorrectly, but we can swap the operands to fix both.
13875 std::swap(LHS, RHS);
13879 Opcode = X86ISD::FMAX;
13885 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13888 // If this is a select between two integer constants, try to do some
13890 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13891 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13892 // Don't do this for crazy integer types.
13893 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13894 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13895 // so that TrueC (the true value) is larger than FalseC.
13896 bool NeedsCondInvert = false;
13898 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13899 // Efficiently invertible.
13900 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13901 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13902 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13903 NeedsCondInvert = true;
13904 std::swap(TrueC, FalseC);
13907 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13908 if (FalseC->getAPIntValue() == 0 &&
13909 TrueC->getAPIntValue().isPowerOf2()) {
13910 if (NeedsCondInvert) // Invert the condition if needed.
13911 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13912 DAG.getConstant(1, Cond.getValueType()));
13914 // Zero extend the condition if needed.
13915 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13917 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13918 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13919 DAG.getConstant(ShAmt, MVT::i8));
13922 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13923 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13924 if (NeedsCondInvert) // Invert the condition if needed.
13925 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13926 DAG.getConstant(1, Cond.getValueType()));
13928 // Zero extend the condition if needed.
13929 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13930 FalseC->getValueType(0), Cond);
13931 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13932 SDValue(FalseC, 0));
13935 // Optimize cases that will turn into an LEA instruction. This requires
13936 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13937 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13938 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13939 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13941 bool isFastMultiplier = false;
13943 switch ((unsigned char)Diff) {
13945 case 1: // result = add base, cond
13946 case 2: // result = lea base( , cond*2)
13947 case 3: // result = lea base(cond, cond*2)
13948 case 4: // result = lea base( , cond*4)
13949 case 5: // result = lea base(cond, cond*4)
13950 case 8: // result = lea base( , cond*8)
13951 case 9: // result = lea base(cond, cond*8)
13952 isFastMultiplier = true;
13957 if (isFastMultiplier) {
13958 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13959 if (NeedsCondInvert) // Invert the condition if needed.
13960 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13961 DAG.getConstant(1, Cond.getValueType()));
13963 // Zero extend the condition if needed.
13964 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13966 // Scale the condition by the difference.
13968 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13969 DAG.getConstant(Diff, Cond.getValueType()));
13971 // Add the base if non-zero.
13972 if (FalseC->getAPIntValue() != 0)
13973 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13974 SDValue(FalseC, 0));
13981 // Canonicalize max and min:
13982 // (x > y) ? x : y -> (x >= y) ? x : y
13983 // (x < y) ? x : y -> (x <= y) ? x : y
13984 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13985 // the need for an extra compare
13986 // against zero. e.g.
13987 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13989 // testl %edi, %edi
13991 // cmovgl %edi, %eax
13995 // cmovsl %eax, %edi
13996 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13997 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13998 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13999 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14004 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14005 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14006 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14007 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14012 // If we know that this node is legal then we know that it is going to be
14013 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14014 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14015 // to simplify previous instructions.
14016 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14017 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14018 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14019 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14021 // Don't optimize vector selects that map to mask-registers.
14025 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14026 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14028 APInt KnownZero, KnownOne;
14029 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14030 DCI.isBeforeLegalizeOps());
14031 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14032 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14033 DCI.CommitTargetLoweringOpt(TLO);
14039 // Check whether a boolean test is testing a boolean value generated by
14040 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14043 // Simplify the following patterns:
14044 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14045 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14046 // to (Op EFLAGS Cond)
14048 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14049 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14050 // to (Op EFLAGS !Cond)
14052 // where Op could be BRCOND or CMOV.
14054 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14055 // Quit if not CMP and SUB with its value result used.
14056 if (Cmp.getOpcode() != X86ISD::CMP &&
14057 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14060 // Quit if not used as a boolean value.
14061 if (CC != X86::COND_E && CC != X86::COND_NE)
14064 // Check CMP operands. One of them should be 0 or 1 and the other should be
14065 // an SetCC or extended from it.
14066 SDValue Op1 = Cmp.getOperand(0);
14067 SDValue Op2 = Cmp.getOperand(1);
14070 const ConstantSDNode* C = 0;
14071 bool needOppositeCond = (CC == X86::COND_E);
14073 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14075 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14077 else // Quit if all operands are not constants.
14080 if (C->getZExtValue() == 1)
14081 needOppositeCond = !needOppositeCond;
14082 else if (C->getZExtValue() != 0)
14083 // Quit if the constant is neither 0 or 1.
14086 // Skip 'zext' node.
14087 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14088 SetCC = SetCC.getOperand(0);
14090 // Quit if not SETCC.
14091 // FIXME: So far we only handle the boolean value generated from SETCC. If
14092 // there is other ways to generate boolean values, we need handle them here
14094 if (SetCC.getOpcode() != X86ISD::SETCC)
14097 // Set the condition code or opposite one if necessary.
14098 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14099 if (needOppositeCond)
14100 CC = X86::GetOppositeBranchCondition(CC);
14102 return SetCC.getOperand(1);
14105 /// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14106 /// updated. If only flag result is used and the result is evaluated from a
14107 /// series of element extraction, try to combine it into a PTEST.
14108 static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14110 const X86Subtarget *Subtarget) {
14111 SDNode *N = Or.getNode();
14112 DebugLoc DL = N->getDebugLoc();
14114 // Only SSE4.1 and beyond supports PTEST or like.
14115 if (!Subtarget->hasSSE41())
14118 if (N->getOpcode() != X86ISD::OR)
14121 // Quit if the value result of OR is used.
14122 if (N->hasAnyUseOfValue(0))
14125 // Quit if not used as a boolean value.
14126 if (CC != X86::COND_E && CC != X86::COND_NE)
14129 SmallVector<SDValue, 8> Opnds;
14131 EVT VT = MVT::Other;
14134 // Recognize a special case where a vector is casted into wide integer to
14136 Opnds.push_back(N->getOperand(0));
14137 Opnds.push_back(N->getOperand(1));
14139 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14140 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14141 // BFS traverse all OR'd operands.
14142 if (I->getOpcode() == ISD::OR) {
14143 Opnds.push_back(I->getOperand(0));
14144 Opnds.push_back(I->getOperand(1));
14145 // Re-evaluate the number of nodes to be traversed.
14146 e += 2; // 2 more nodes (LHS and RHS) are pushed.
14150 // Quit if a non-EXTRACT_VECTOR_ELT
14151 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14154 // Quit if without a constant index.
14155 SDValue Idx = I->getOperand(1);
14156 if (!isa<ConstantSDNode>(Idx))
14159 // Check if all elements are extracted from the same vector.
14160 SDValue ExtractedFromVec = I->getOperand(0);
14161 if (VecIn.getNode() == 0) {
14162 VT = ExtractedFromVec.getValueType();
14163 // FIXME: only 128-bit vector is supported so far.
14164 if (!VT.is128BitVector())
14166 VecIn = ExtractedFromVec;
14167 } else if (VecIn != ExtractedFromVec)
14170 // Record the constant index.
14171 Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14174 assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14176 // Quit if not all elements are used.
14177 if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14180 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14183 static bool isValidFCMOVCondition(X86::CondCode CC) {
14199 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14200 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14201 TargetLowering::DAGCombinerInfo &DCI,
14202 const X86Subtarget *Subtarget) {
14203 DebugLoc DL = N->getDebugLoc();
14205 // If the flag operand isn't dead, don't touch this CMOV.
14206 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14209 SDValue FalseOp = N->getOperand(0);
14210 SDValue TrueOp = N->getOperand(1);
14211 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14212 SDValue Cond = N->getOperand(3);
14214 if (CC == X86::COND_E || CC == X86::COND_NE) {
14215 switch (Cond.getOpcode()) {
14219 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14220 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14221 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14227 Flags = checkBoolTestSetCCCombine(Cond, CC);
14228 if (Flags.getNode() &&
14229 // Extra check as FCMOV only supports a subset of X86 cond.
14230 (FalseOp.getValueType() != MVT::f80 || isValidFCMOVCondition(CC))) {
14231 SDValue Ops[] = { FalseOp, TrueOp,
14232 DAG.getConstant(CC, MVT::i8), Flags };
14233 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14234 Ops, array_lengthof(Ops));
14237 Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14238 if (Flags.getNode()) {
14239 SDValue Ops[] = { FalseOp, TrueOp,
14240 DAG.getConstant(CC, MVT::i8), Flags };
14241 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14242 Ops, array_lengthof(Ops));
14245 // If this is a select between two integer constants, try to do some
14246 // optimizations. Note that the operands are ordered the opposite of SELECT
14248 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14249 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14250 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14251 // larger than FalseC (the false value).
14252 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14253 CC = X86::GetOppositeBranchCondition(CC);
14254 std::swap(TrueC, FalseC);
14257 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14258 // This is efficient for any integer data type (including i8/i16) and
14260 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14261 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14262 DAG.getConstant(CC, MVT::i8), Cond);
14264 // Zero extend the condition if needed.
14265 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14267 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14268 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14269 DAG.getConstant(ShAmt, MVT::i8));
14270 if (N->getNumValues() == 2) // Dead flag value?
14271 return DCI.CombineTo(N, Cond, SDValue());
14275 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14276 // for any integer data type, including i8/i16.
14277 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14278 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14279 DAG.getConstant(CC, MVT::i8), Cond);
14281 // Zero extend the condition if needed.
14282 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14283 FalseC->getValueType(0), Cond);
14284 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14285 SDValue(FalseC, 0));
14287 if (N->getNumValues() == 2) // Dead flag value?
14288 return DCI.CombineTo(N, Cond, SDValue());
14292 // Optimize cases that will turn into an LEA instruction. This requires
14293 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14294 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14295 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14296 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14298 bool isFastMultiplier = false;
14300 switch ((unsigned char)Diff) {
14302 case 1: // result = add base, cond
14303 case 2: // result = lea base( , cond*2)
14304 case 3: // result = lea base(cond, cond*2)
14305 case 4: // result = lea base( , cond*4)
14306 case 5: // result = lea base(cond, cond*4)
14307 case 8: // result = lea base( , cond*8)
14308 case 9: // result = lea base(cond, cond*8)
14309 isFastMultiplier = true;
14314 if (isFastMultiplier) {
14315 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14316 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14317 DAG.getConstant(CC, MVT::i8), Cond);
14318 // Zero extend the condition if needed.
14319 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14321 // Scale the condition by the difference.
14323 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14324 DAG.getConstant(Diff, Cond.getValueType()));
14326 // Add the base if non-zero.
14327 if (FalseC->getAPIntValue() != 0)
14328 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14329 SDValue(FalseC, 0));
14330 if (N->getNumValues() == 2) // Dead flag value?
14331 return DCI.CombineTo(N, Cond, SDValue());
14341 /// PerformMulCombine - Optimize a single multiply with constant into two
14342 /// in order to implement it with two cheaper instructions, e.g.
14343 /// LEA + SHL, LEA + LEA.
14344 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14345 TargetLowering::DAGCombinerInfo &DCI) {
14346 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14349 EVT VT = N->getValueType(0);
14350 if (VT != MVT::i64)
14353 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14356 uint64_t MulAmt = C->getZExtValue();
14357 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14360 uint64_t MulAmt1 = 0;
14361 uint64_t MulAmt2 = 0;
14362 if ((MulAmt % 9) == 0) {
14364 MulAmt2 = MulAmt / 9;
14365 } else if ((MulAmt % 5) == 0) {
14367 MulAmt2 = MulAmt / 5;
14368 } else if ((MulAmt % 3) == 0) {
14370 MulAmt2 = MulAmt / 3;
14373 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14374 DebugLoc DL = N->getDebugLoc();
14376 if (isPowerOf2_64(MulAmt2) &&
14377 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14378 // If second multiplifer is pow2, issue it first. We want the multiply by
14379 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14381 std::swap(MulAmt1, MulAmt2);
14384 if (isPowerOf2_64(MulAmt1))
14385 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14386 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14388 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14389 DAG.getConstant(MulAmt1, VT));
14391 if (isPowerOf2_64(MulAmt2))
14392 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14393 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14395 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14396 DAG.getConstant(MulAmt2, VT));
14398 // Do not add new nodes to DAG combiner worklist.
14399 DCI.CombineTo(N, NewMul, false);
14404 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14405 SDValue N0 = N->getOperand(0);
14406 SDValue N1 = N->getOperand(1);
14407 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14408 EVT VT = N0.getValueType();
14410 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14411 // since the result of setcc_c is all zero's or all ones.
14412 if (VT.isInteger() && !VT.isVector() &&
14413 N1C && N0.getOpcode() == ISD::AND &&
14414 N0.getOperand(1).getOpcode() == ISD::Constant) {
14415 SDValue N00 = N0.getOperand(0);
14416 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14417 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14418 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14419 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14420 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14421 APInt ShAmt = N1C->getAPIntValue();
14422 Mask = Mask.shl(ShAmt);
14424 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14425 N00, DAG.getConstant(Mask, VT));
14430 // Hardware support for vector shifts is sparse which makes us scalarize the
14431 // vector operations in many cases. Also, on sandybridge ADD is faster than
14433 // (shl V, 1) -> add V,V
14434 if (isSplatVector(N1.getNode())) {
14435 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14436 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14437 // We shift all of the values by one. In many cases we do not have
14438 // hardware support for this operation. This is better expressed as an ADD
14440 if (N1C && (1 == N1C->getZExtValue())) {
14441 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14448 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14450 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14451 TargetLowering::DAGCombinerInfo &DCI,
14452 const X86Subtarget *Subtarget) {
14453 EVT VT = N->getValueType(0);
14454 if (N->getOpcode() == ISD::SHL) {
14455 SDValue V = PerformSHLCombine(N, DAG);
14456 if (V.getNode()) return V;
14459 // On X86 with SSE2 support, we can transform this to a vector shift if
14460 // all elements are shifted by the same amount. We can't do this in legalize
14461 // because the a constant vector is typically transformed to a constant pool
14462 // so we have no knowledge of the shift amount.
14463 if (!Subtarget->hasSSE2())
14466 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14467 (!Subtarget->hasAVX2() ||
14468 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14471 SDValue ShAmtOp = N->getOperand(1);
14472 EVT EltVT = VT.getVectorElementType();
14473 DebugLoc DL = N->getDebugLoc();
14474 SDValue BaseShAmt = SDValue();
14475 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14476 unsigned NumElts = VT.getVectorNumElements();
14478 for (; i != NumElts; ++i) {
14479 SDValue Arg = ShAmtOp.getOperand(i);
14480 if (Arg.getOpcode() == ISD::UNDEF) continue;
14484 // Handle the case where the build_vector is all undef
14485 // FIXME: Should DAG allow this?
14489 for (; i != NumElts; ++i) {
14490 SDValue Arg = ShAmtOp.getOperand(i);
14491 if (Arg.getOpcode() == ISD::UNDEF) continue;
14492 if (Arg != BaseShAmt) {
14496 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14497 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14498 SDValue InVec = ShAmtOp.getOperand(0);
14499 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14500 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14502 for (; i != NumElts; ++i) {
14503 SDValue Arg = InVec.getOperand(i);
14504 if (Arg.getOpcode() == ISD::UNDEF) continue;
14508 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14510 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14511 if (C->getZExtValue() == SplatIdx)
14512 BaseShAmt = InVec.getOperand(1);
14515 if (BaseShAmt.getNode() == 0) {
14516 // Don't create instructions with illegal types after legalize
14518 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14519 !DCI.isBeforeLegalize())
14522 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14523 DAG.getIntPtrConstant(0));
14528 // The shift amount is an i32.
14529 if (EltVT.bitsGT(MVT::i32))
14530 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14531 else if (EltVT.bitsLT(MVT::i32))
14532 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14534 // The shift amount is identical so we can do a vector shift.
14535 SDValue ValOp = N->getOperand(0);
14536 switch (N->getOpcode()) {
14538 llvm_unreachable("Unknown shift opcode!");
14540 switch (VT.getSimpleVT().SimpleTy) {
14541 default: return SDValue();
14548 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14551 switch (VT.getSimpleVT().SimpleTy) {
14552 default: return SDValue();
14557 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14560 switch (VT.getSimpleVT().SimpleTy) {
14561 default: return SDValue();
14568 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14574 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14575 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14576 // and friends. Likewise for OR -> CMPNEQSS.
14577 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14578 TargetLowering::DAGCombinerInfo &DCI,
14579 const X86Subtarget *Subtarget) {
14582 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14583 // we're requiring SSE2 for both.
14584 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14585 SDValue N0 = N->getOperand(0);
14586 SDValue N1 = N->getOperand(1);
14587 SDValue CMP0 = N0->getOperand(1);
14588 SDValue CMP1 = N1->getOperand(1);
14589 DebugLoc DL = N->getDebugLoc();
14591 // The SETCCs should both refer to the same CMP.
14592 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14595 SDValue CMP00 = CMP0->getOperand(0);
14596 SDValue CMP01 = CMP0->getOperand(1);
14597 EVT VT = CMP00.getValueType();
14599 if (VT == MVT::f32 || VT == MVT::f64) {
14600 bool ExpectingFlags = false;
14601 // Check for any users that want flags:
14602 for (SDNode::use_iterator UI = N->use_begin(),
14604 !ExpectingFlags && UI != UE; ++UI)
14605 switch (UI->getOpcode()) {
14610 ExpectingFlags = true;
14612 case ISD::CopyToReg:
14613 case ISD::SIGN_EXTEND:
14614 case ISD::ZERO_EXTEND:
14615 case ISD::ANY_EXTEND:
14619 if (!ExpectingFlags) {
14620 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14621 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14623 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14624 X86::CondCode tmp = cc0;
14629 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14630 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14631 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14632 X86ISD::NodeType NTOperator = is64BitFP ?
14633 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14634 // FIXME: need symbolic constants for these magic numbers.
14635 // See X86ATTInstPrinter.cpp:printSSECC().
14636 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14637 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14638 DAG.getConstant(x86cc, MVT::i8));
14639 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14641 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14642 DAG.getConstant(1, MVT::i32));
14643 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14644 return OneBitOfTruth;
14652 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14653 /// so it can be folded inside ANDNP.
14654 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14655 EVT VT = N->getValueType(0);
14657 // Match direct AllOnes for 128 and 256-bit vectors
14658 if (ISD::isBuildVectorAllOnes(N))
14661 // Look through a bit convert.
14662 if (N->getOpcode() == ISD::BITCAST)
14663 N = N->getOperand(0).getNode();
14665 // Sometimes the operand may come from a insert_subvector building a 256-bit
14667 if (VT.is256BitVector() &&
14668 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14669 SDValue V1 = N->getOperand(0);
14670 SDValue V2 = N->getOperand(1);
14672 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14673 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14674 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14675 ISD::isBuildVectorAllOnes(V2.getNode()))
14682 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14683 TargetLowering::DAGCombinerInfo &DCI,
14684 const X86Subtarget *Subtarget) {
14685 if (DCI.isBeforeLegalizeOps())
14688 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14692 EVT VT = N->getValueType(0);
14694 // Create ANDN, BLSI, and BLSR instructions
14695 // BLSI is X & (-X)
14696 // BLSR is X & (X-1)
14697 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14698 SDValue N0 = N->getOperand(0);
14699 SDValue N1 = N->getOperand(1);
14700 DebugLoc DL = N->getDebugLoc();
14702 // Check LHS for not
14703 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14704 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14705 // Check RHS for not
14706 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14707 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14709 // Check LHS for neg
14710 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14711 isZero(N0.getOperand(0)))
14712 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14714 // Check RHS for neg
14715 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14716 isZero(N1.getOperand(0)))
14717 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14719 // Check LHS for X-1
14720 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14721 isAllOnes(N0.getOperand(1)))
14722 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14724 // Check RHS for X-1
14725 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14726 isAllOnes(N1.getOperand(1)))
14727 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14732 // Want to form ANDNP nodes:
14733 // 1) In the hopes of then easily combining them with OR and AND nodes
14734 // to form PBLEND/PSIGN.
14735 // 2) To match ANDN packed intrinsics
14736 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14739 SDValue N0 = N->getOperand(0);
14740 SDValue N1 = N->getOperand(1);
14741 DebugLoc DL = N->getDebugLoc();
14743 // Check LHS for vnot
14744 if (N0.getOpcode() == ISD::XOR &&
14745 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14746 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14747 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14749 // Check RHS for vnot
14750 if (N1.getOpcode() == ISD::XOR &&
14751 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14752 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14753 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14758 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14759 TargetLowering::DAGCombinerInfo &DCI,
14760 const X86Subtarget *Subtarget) {
14761 if (DCI.isBeforeLegalizeOps())
14764 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14768 EVT VT = N->getValueType(0);
14770 SDValue N0 = N->getOperand(0);
14771 SDValue N1 = N->getOperand(1);
14773 // look for psign/blend
14774 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14775 if (!Subtarget->hasSSSE3() ||
14776 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14779 // Canonicalize pandn to RHS
14780 if (N0.getOpcode() == X86ISD::ANDNP)
14782 // or (and (m, y), (pandn m, x))
14783 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14784 SDValue Mask = N1.getOperand(0);
14785 SDValue X = N1.getOperand(1);
14787 if (N0.getOperand(0) == Mask)
14788 Y = N0.getOperand(1);
14789 if (N0.getOperand(1) == Mask)
14790 Y = N0.getOperand(0);
14792 // Check to see if the mask appeared in both the AND and ANDNP and
14796 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14797 // Look through mask bitcast.
14798 if (Mask.getOpcode() == ISD::BITCAST)
14799 Mask = Mask.getOperand(0);
14800 if (X.getOpcode() == ISD::BITCAST)
14801 X = X.getOperand(0);
14802 if (Y.getOpcode() == ISD::BITCAST)
14803 Y = Y.getOperand(0);
14805 EVT MaskVT = Mask.getValueType();
14807 // Validate that the Mask operand is a vector sra node.
14808 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14809 // there is no psrai.b
14810 if (Mask.getOpcode() != X86ISD::VSRAI)
14813 // Check that the SRA is all signbits.
14814 SDValue SraC = Mask.getOperand(1);
14815 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14816 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14817 if ((SraAmt + 1) != EltBits)
14820 DebugLoc DL = N->getDebugLoc();
14822 // Now we know we at least have a plendvb with the mask val. See if
14823 // we can form a psignb/w/d.
14824 // psign = x.type == y.type == mask.type && y = sub(0, x);
14825 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14826 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14827 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14828 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14829 "Unsupported VT for PSIGN");
14830 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14831 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14833 // PBLENDVB only available on SSE 4.1
14834 if (!Subtarget->hasSSE41())
14837 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14839 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14840 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14841 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14842 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14843 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14847 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14850 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14851 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14853 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14855 if (!N0.hasOneUse() || !N1.hasOneUse())
14858 SDValue ShAmt0 = N0.getOperand(1);
14859 if (ShAmt0.getValueType() != MVT::i8)
14861 SDValue ShAmt1 = N1.getOperand(1);
14862 if (ShAmt1.getValueType() != MVT::i8)
14864 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14865 ShAmt0 = ShAmt0.getOperand(0);
14866 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14867 ShAmt1 = ShAmt1.getOperand(0);
14869 DebugLoc DL = N->getDebugLoc();
14870 unsigned Opc = X86ISD::SHLD;
14871 SDValue Op0 = N0.getOperand(0);
14872 SDValue Op1 = N1.getOperand(0);
14873 if (ShAmt0.getOpcode() == ISD::SUB) {
14874 Opc = X86ISD::SHRD;
14875 std::swap(Op0, Op1);
14876 std::swap(ShAmt0, ShAmt1);
14879 unsigned Bits = VT.getSizeInBits();
14880 if (ShAmt1.getOpcode() == ISD::SUB) {
14881 SDValue Sum = ShAmt1.getOperand(0);
14882 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14883 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14884 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14885 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14886 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14887 return DAG.getNode(Opc, DL, VT,
14889 DAG.getNode(ISD::TRUNCATE, DL,
14892 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14893 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14895 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14896 return DAG.getNode(Opc, DL, VT,
14897 N0.getOperand(0), N1.getOperand(0),
14898 DAG.getNode(ISD::TRUNCATE, DL,
14905 // Generate NEG and CMOV for integer abs.
14906 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14907 EVT VT = N->getValueType(0);
14909 // Since X86 does not have CMOV for 8-bit integer, we don't convert
14910 // 8-bit integer abs to NEG and CMOV.
14911 if (VT.isInteger() && VT.getSizeInBits() == 8)
14914 SDValue N0 = N->getOperand(0);
14915 SDValue N1 = N->getOperand(1);
14916 DebugLoc DL = N->getDebugLoc();
14918 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14919 // and change it to SUB and CMOV.
14920 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14921 N0.getOpcode() == ISD::ADD &&
14922 N0.getOperand(1) == N1 &&
14923 N1.getOpcode() == ISD::SRA &&
14924 N1.getOperand(0) == N0.getOperand(0))
14925 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14926 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14927 // Generate SUB & CMOV.
14928 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14929 DAG.getConstant(0, VT), N0.getOperand(0));
14931 SDValue Ops[] = { N0.getOperand(0), Neg,
14932 DAG.getConstant(X86::COND_GE, MVT::i8),
14933 SDValue(Neg.getNode(), 1) };
14934 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14935 Ops, array_lengthof(Ops));
14940 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14941 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14942 TargetLowering::DAGCombinerInfo &DCI,
14943 const X86Subtarget *Subtarget) {
14944 if (DCI.isBeforeLegalizeOps())
14947 if (Subtarget->hasCMov()) {
14948 SDValue RV = performIntegerAbsCombine(N, DAG);
14953 // Try forming BMI if it is available.
14954 if (!Subtarget->hasBMI())
14957 EVT VT = N->getValueType(0);
14959 if (VT != MVT::i32 && VT != MVT::i64)
14962 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14964 // Create BLSMSK instructions by finding X ^ (X-1)
14965 SDValue N0 = N->getOperand(0);
14966 SDValue N1 = N->getOperand(1);
14967 DebugLoc DL = N->getDebugLoc();
14969 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14970 isAllOnes(N0.getOperand(1)))
14971 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14973 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14974 isAllOnes(N1.getOperand(1)))
14975 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14980 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14981 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14982 TargetLowering::DAGCombinerInfo &DCI,
14983 const X86Subtarget *Subtarget) {
14984 LoadSDNode *Ld = cast<LoadSDNode>(N);
14985 EVT RegVT = Ld->getValueType(0);
14986 EVT MemVT = Ld->getMemoryVT();
14987 DebugLoc dl = Ld->getDebugLoc();
14988 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14990 ISD::LoadExtType Ext = Ld->getExtensionType();
14992 // If this is a vector EXT Load then attempt to optimize it using a
14993 // shuffle. We need SSE4 for the shuffles.
14994 // TODO: It is possible to support ZExt by zeroing the undef values
14995 // during the shuffle phase or after the shuffle.
14996 if (RegVT.isVector() && RegVT.isInteger() &&
14997 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14998 assert(MemVT != RegVT && "Cannot extend to the same type");
14999 assert(MemVT.isVector() && "Must load a vector from memory");
15001 unsigned NumElems = RegVT.getVectorNumElements();
15002 unsigned RegSz = RegVT.getSizeInBits();
15003 unsigned MemSz = MemVT.getSizeInBits();
15004 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15006 // All sizes must be a power of two.
15007 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15010 // Attempt to load the original value using scalar loads.
15011 // Find the largest scalar type that divides the total loaded size.
15012 MVT SclrLoadTy = MVT::i8;
15013 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15014 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15015 MVT Tp = (MVT::SimpleValueType)tp;
15016 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15021 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15022 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15024 SclrLoadTy = MVT::f64;
15026 // Calculate the number of scalar loads that we need to perform
15027 // in order to load our vector from memory.
15028 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15030 // Represent our vector as a sequence of elements which are the
15031 // largest scalar that we can load.
15032 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15033 RegSz/SclrLoadTy.getSizeInBits());
15035 // Represent the data using the same element type that is stored in
15036 // memory. In practice, we ''widen'' MemVT.
15037 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15038 RegSz/MemVT.getScalarType().getSizeInBits());
15040 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15041 "Invalid vector type");
15043 // We can't shuffle using an illegal type.
15044 if (!TLI.isTypeLegal(WideVecVT))
15047 SmallVector<SDValue, 8> Chains;
15048 SDValue Ptr = Ld->getBasePtr();
15049 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15050 TLI.getPointerTy());
15051 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15053 for (unsigned i = 0; i < NumLoads; ++i) {
15054 // Perform a single load.
15055 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15056 Ptr, Ld->getPointerInfo(),
15057 Ld->isVolatile(), Ld->isNonTemporal(),
15058 Ld->isInvariant(), Ld->getAlignment());
15059 Chains.push_back(ScalarLoad.getValue(1));
15060 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15061 // another round of DAGCombining.
15063 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15065 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15066 ScalarLoad, DAG.getIntPtrConstant(i));
15068 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15071 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15074 // Bitcast the loaded value to a vector of the original element type, in
15075 // the size of the target vector type.
15076 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15077 unsigned SizeRatio = RegSz/MemSz;
15079 // Redistribute the loaded elements into the different locations.
15080 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15081 for (unsigned i = 0; i != NumElems; ++i)
15082 ShuffleVec[i*SizeRatio] = i;
15084 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15085 DAG.getUNDEF(WideVecVT),
15088 // Bitcast to the requested type.
15089 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15090 // Replace the original load with the new sequence
15091 // and return the new chain.
15092 return DCI.CombineTo(N, Shuff, TF, true);
15098 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15099 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15100 const X86Subtarget *Subtarget) {
15101 StoreSDNode *St = cast<StoreSDNode>(N);
15102 EVT VT = St->getValue().getValueType();
15103 EVT StVT = St->getMemoryVT();
15104 DebugLoc dl = St->getDebugLoc();
15105 SDValue StoredVal = St->getOperand(1);
15106 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15108 // If we are saving a concatenation of two XMM registers, perform two stores.
15109 // On Sandy Bridge, 256-bit memory operations are executed by two
15110 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15111 // memory operation.
15112 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15113 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15114 StoredVal.getNumOperands() == 2) {
15115 SDValue Value0 = StoredVal.getOperand(0);
15116 SDValue Value1 = StoredVal.getOperand(1);
15118 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15119 SDValue Ptr0 = St->getBasePtr();
15120 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15122 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15123 St->getPointerInfo(), St->isVolatile(),
15124 St->isNonTemporal(), St->getAlignment());
15125 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15126 St->getPointerInfo(), St->isVolatile(),
15127 St->isNonTemporal(), St->getAlignment());
15128 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15131 // Optimize trunc store (of multiple scalars) to shuffle and store.
15132 // First, pack all of the elements in one place. Next, store to memory
15133 // in fewer chunks.
15134 if (St->isTruncatingStore() && VT.isVector()) {
15135 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15136 unsigned NumElems = VT.getVectorNumElements();
15137 assert(StVT != VT && "Cannot truncate to the same type");
15138 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15139 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15141 // From, To sizes and ElemCount must be pow of two
15142 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15143 // We are going to use the original vector elt for storing.
15144 // Accumulated smaller vector elements must be a multiple of the store size.
15145 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15147 unsigned SizeRatio = FromSz / ToSz;
15149 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15151 // Create a type on which we perform the shuffle
15152 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15153 StVT.getScalarType(), NumElems*SizeRatio);
15155 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15157 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15158 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15159 for (unsigned i = 0; i != NumElems; ++i)
15160 ShuffleVec[i] = i * SizeRatio;
15162 // Can't shuffle using an illegal type.
15163 if (!TLI.isTypeLegal(WideVecVT))
15166 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15167 DAG.getUNDEF(WideVecVT),
15169 // At this point all of the data is stored at the bottom of the
15170 // register. We now need to save it to mem.
15172 // Find the largest store unit
15173 MVT StoreType = MVT::i8;
15174 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15175 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15176 MVT Tp = (MVT::SimpleValueType)tp;
15177 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15181 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15182 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15183 (64 <= NumElems * ToSz))
15184 StoreType = MVT::f64;
15186 // Bitcast the original vector into a vector of store-size units
15187 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15188 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15189 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15190 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15191 SmallVector<SDValue, 8> Chains;
15192 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15193 TLI.getPointerTy());
15194 SDValue Ptr = St->getBasePtr();
15196 // Perform one or more big stores into memory.
15197 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15198 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15199 StoreType, ShuffWide,
15200 DAG.getIntPtrConstant(i));
15201 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15202 St->getPointerInfo(), St->isVolatile(),
15203 St->isNonTemporal(), St->getAlignment());
15204 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15205 Chains.push_back(Ch);
15208 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15213 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15214 // the FP state in cases where an emms may be missing.
15215 // A preferable solution to the general problem is to figure out the right
15216 // places to insert EMMS. This qualifies as a quick hack.
15218 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15219 if (VT.getSizeInBits() != 64)
15222 const Function *F = DAG.getMachineFunction().getFunction();
15223 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15224 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15225 && Subtarget->hasSSE2();
15226 if ((VT.isVector() ||
15227 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15228 isa<LoadSDNode>(St->getValue()) &&
15229 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15230 St->getChain().hasOneUse() && !St->isVolatile()) {
15231 SDNode* LdVal = St->getValue().getNode();
15232 LoadSDNode *Ld = 0;
15233 int TokenFactorIndex = -1;
15234 SmallVector<SDValue, 8> Ops;
15235 SDNode* ChainVal = St->getChain().getNode();
15236 // Must be a store of a load. We currently handle two cases: the load
15237 // is a direct child, and it's under an intervening TokenFactor. It is
15238 // possible to dig deeper under nested TokenFactors.
15239 if (ChainVal == LdVal)
15240 Ld = cast<LoadSDNode>(St->getChain());
15241 else if (St->getValue().hasOneUse() &&
15242 ChainVal->getOpcode() == ISD::TokenFactor) {
15243 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15244 if (ChainVal->getOperand(i).getNode() == LdVal) {
15245 TokenFactorIndex = i;
15246 Ld = cast<LoadSDNode>(St->getValue());
15248 Ops.push_back(ChainVal->getOperand(i));
15252 if (!Ld || !ISD::isNormalLoad(Ld))
15255 // If this is not the MMX case, i.e. we are just turning i64 load/store
15256 // into f64 load/store, avoid the transformation if there are multiple
15257 // uses of the loaded value.
15258 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15261 DebugLoc LdDL = Ld->getDebugLoc();
15262 DebugLoc StDL = N->getDebugLoc();
15263 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15264 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15266 if (Subtarget->is64Bit() || F64IsLegal) {
15267 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15268 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15269 Ld->getPointerInfo(), Ld->isVolatile(),
15270 Ld->isNonTemporal(), Ld->isInvariant(),
15271 Ld->getAlignment());
15272 SDValue NewChain = NewLd.getValue(1);
15273 if (TokenFactorIndex != -1) {
15274 Ops.push_back(NewChain);
15275 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15278 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15279 St->getPointerInfo(),
15280 St->isVolatile(), St->isNonTemporal(),
15281 St->getAlignment());
15284 // Otherwise, lower to two pairs of 32-bit loads / stores.
15285 SDValue LoAddr = Ld->getBasePtr();
15286 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15287 DAG.getConstant(4, MVT::i32));
15289 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15290 Ld->getPointerInfo(),
15291 Ld->isVolatile(), Ld->isNonTemporal(),
15292 Ld->isInvariant(), Ld->getAlignment());
15293 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15294 Ld->getPointerInfo().getWithOffset(4),
15295 Ld->isVolatile(), Ld->isNonTemporal(),
15297 MinAlign(Ld->getAlignment(), 4));
15299 SDValue NewChain = LoLd.getValue(1);
15300 if (TokenFactorIndex != -1) {
15301 Ops.push_back(LoLd);
15302 Ops.push_back(HiLd);
15303 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15307 LoAddr = St->getBasePtr();
15308 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15309 DAG.getConstant(4, MVT::i32));
15311 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15312 St->getPointerInfo(),
15313 St->isVolatile(), St->isNonTemporal(),
15314 St->getAlignment());
15315 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15316 St->getPointerInfo().getWithOffset(4),
15318 St->isNonTemporal(),
15319 MinAlign(St->getAlignment(), 4));
15320 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15325 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15326 /// and return the operands for the horizontal operation in LHS and RHS. A
15327 /// horizontal operation performs the binary operation on successive elements
15328 /// of its first operand, then on successive elements of its second operand,
15329 /// returning the resulting values in a vector. For example, if
15330 /// A = < float a0, float a1, float a2, float a3 >
15332 /// B = < float b0, float b1, float b2, float b3 >
15333 /// then the result of doing a horizontal operation on A and B is
15334 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15335 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15336 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15337 /// set to A, RHS to B, and the routine returns 'true'.
15338 /// Note that the binary operation should have the property that if one of the
15339 /// operands is UNDEF then the result is UNDEF.
15340 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15341 // Look for the following pattern: if
15342 // A = < float a0, float a1, float a2, float a3 >
15343 // B = < float b0, float b1, float b2, float b3 >
15345 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15346 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15347 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15348 // which is A horizontal-op B.
15350 // At least one of the operands should be a vector shuffle.
15351 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15352 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15355 EVT VT = LHS.getValueType();
15357 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15358 "Unsupported vector type for horizontal add/sub");
15360 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15361 // operate independently on 128-bit lanes.
15362 unsigned NumElts = VT.getVectorNumElements();
15363 unsigned NumLanes = VT.getSizeInBits()/128;
15364 unsigned NumLaneElts = NumElts / NumLanes;
15365 assert((NumLaneElts % 2 == 0) &&
15366 "Vector type should have an even number of elements in each lane");
15367 unsigned HalfLaneElts = NumLaneElts/2;
15369 // View LHS in the form
15370 // LHS = VECTOR_SHUFFLE A, B, LMask
15371 // If LHS is not a shuffle then pretend it is the shuffle
15372 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15373 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15376 SmallVector<int, 16> LMask(NumElts);
15377 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15378 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15379 A = LHS.getOperand(0);
15380 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15381 B = LHS.getOperand(1);
15382 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15383 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15385 if (LHS.getOpcode() != ISD::UNDEF)
15387 for (unsigned i = 0; i != NumElts; ++i)
15391 // Likewise, view RHS in the form
15392 // RHS = VECTOR_SHUFFLE C, D, RMask
15394 SmallVector<int, 16> RMask(NumElts);
15395 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15396 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15397 C = RHS.getOperand(0);
15398 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15399 D = RHS.getOperand(1);
15400 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15401 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15403 if (RHS.getOpcode() != ISD::UNDEF)
15405 for (unsigned i = 0; i != NumElts; ++i)
15409 // Check that the shuffles are both shuffling the same vectors.
15410 if (!(A == C && B == D) && !(A == D && B == C))
15413 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15414 if (!A.getNode() && !B.getNode())
15417 // If A and B occur in reverse order in RHS, then "swap" them (which means
15418 // rewriting the mask).
15420 CommuteVectorShuffleMask(RMask, NumElts);
15422 // At this point LHS and RHS are equivalent to
15423 // LHS = VECTOR_SHUFFLE A, B, LMask
15424 // RHS = VECTOR_SHUFFLE A, B, RMask
15425 // Check that the masks correspond to performing a horizontal operation.
15426 for (unsigned i = 0; i != NumElts; ++i) {
15427 int LIdx = LMask[i], RIdx = RMask[i];
15429 // Ignore any UNDEF components.
15430 if (LIdx < 0 || RIdx < 0 ||
15431 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15432 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15435 // Check that successive elements are being operated on. If not, this is
15436 // not a horizontal operation.
15437 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15438 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15439 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15440 if (!(LIdx == Index && RIdx == Index + 1) &&
15441 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15445 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15446 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15450 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15451 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15452 const X86Subtarget *Subtarget) {
15453 EVT VT = N->getValueType(0);
15454 SDValue LHS = N->getOperand(0);
15455 SDValue RHS = N->getOperand(1);
15457 // Try to synthesize horizontal adds from adds of shuffles.
15458 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15459 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15460 isHorizontalBinOp(LHS, RHS, true))
15461 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15465 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15466 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15467 const X86Subtarget *Subtarget) {
15468 EVT VT = N->getValueType(0);
15469 SDValue LHS = N->getOperand(0);
15470 SDValue RHS = N->getOperand(1);
15472 // Try to synthesize horizontal subs from subs of shuffles.
15473 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15474 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15475 isHorizontalBinOp(LHS, RHS, false))
15476 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15480 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15481 /// X86ISD::FXOR nodes.
15482 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15483 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15484 // F[X]OR(0.0, x) -> x
15485 // F[X]OR(x, 0.0) -> x
15486 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15487 if (C->getValueAPF().isPosZero())
15488 return N->getOperand(1);
15489 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15490 if (C->getValueAPF().isPosZero())
15491 return N->getOperand(0);
15495 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15496 /// X86ISD::FMAX nodes.
15497 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15498 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15500 // Only perform optimizations if UnsafeMath is used.
15501 if (!DAG.getTarget().Options.UnsafeFPMath)
15504 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15505 // into FMINC and FMAXC, which are Commutative operations.
15506 unsigned NewOp = 0;
15507 switch (N->getOpcode()) {
15508 default: llvm_unreachable("unknown opcode");
15509 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
15510 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
15513 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15514 N->getOperand(0), N->getOperand(1));
15518 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15519 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15520 // FAND(0.0, x) -> 0.0
15521 // FAND(x, 0.0) -> 0.0
15522 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15523 if (C->getValueAPF().isPosZero())
15524 return N->getOperand(0);
15525 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15526 if (C->getValueAPF().isPosZero())
15527 return N->getOperand(1);
15531 static SDValue PerformBTCombine(SDNode *N,
15533 TargetLowering::DAGCombinerInfo &DCI) {
15534 // BT ignores high bits in the bit index operand.
15535 SDValue Op1 = N->getOperand(1);
15536 if (Op1.hasOneUse()) {
15537 unsigned BitWidth = Op1.getValueSizeInBits();
15538 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15539 APInt KnownZero, KnownOne;
15540 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15541 !DCI.isBeforeLegalizeOps());
15542 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15543 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15544 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15545 DCI.CommitTargetLoweringOpt(TLO);
15550 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15551 SDValue Op = N->getOperand(0);
15552 if (Op.getOpcode() == ISD::BITCAST)
15553 Op = Op.getOperand(0);
15554 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15555 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15556 VT.getVectorElementType().getSizeInBits() ==
15557 OpVT.getVectorElementType().getSizeInBits()) {
15558 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15563 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15564 TargetLowering::DAGCombinerInfo &DCI,
15565 const X86Subtarget *Subtarget) {
15566 if (!DCI.isBeforeLegalizeOps())
15569 if (!Subtarget->hasAVX())
15572 EVT VT = N->getValueType(0);
15573 SDValue Op = N->getOperand(0);
15574 EVT OpVT = Op.getValueType();
15575 DebugLoc dl = N->getDebugLoc();
15577 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15578 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15580 if (Subtarget->hasAVX2())
15581 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15583 // Optimize vectors in AVX mode
15584 // Sign extend v8i16 to v8i32 and
15587 // Divide input vector into two parts
15588 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15589 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15590 // concat the vectors to original VT
15592 unsigned NumElems = OpVT.getVectorNumElements();
15593 SDValue Undef = DAG.getUNDEF(OpVT);
15595 SmallVector<int,8> ShufMask1(NumElems, -1);
15596 for (unsigned i = 0; i != NumElems/2; ++i)
15599 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15601 SmallVector<int,8> ShufMask2(NumElems, -1);
15602 for (unsigned i = 0; i != NumElems/2; ++i)
15603 ShufMask2[i] = i + NumElems/2;
15605 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15607 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15608 VT.getVectorNumElements()/2);
15610 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15611 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15613 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15618 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15619 const X86Subtarget* Subtarget) {
15620 DebugLoc dl = N->getDebugLoc();
15621 EVT VT = N->getValueType(0);
15623 // Let legalize expand this if it isn't a legal type yet.
15624 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15627 EVT ScalarVT = VT.getScalarType();
15628 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15629 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15632 SDValue A = N->getOperand(0);
15633 SDValue B = N->getOperand(1);
15634 SDValue C = N->getOperand(2);
15636 bool NegA = (A.getOpcode() == ISD::FNEG);
15637 bool NegB = (B.getOpcode() == ISD::FNEG);
15638 bool NegC = (C.getOpcode() == ISD::FNEG);
15640 // Negative multiplication when NegA xor NegB
15641 bool NegMul = (NegA != NegB);
15643 A = A.getOperand(0);
15645 B = B.getOperand(0);
15647 C = C.getOperand(0);
15651 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15653 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15655 return DAG.getNode(Opcode, dl, VT, A, B, C);
15658 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15659 TargetLowering::DAGCombinerInfo &DCI,
15660 const X86Subtarget *Subtarget) {
15661 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15662 // (and (i32 x86isd::setcc_carry), 1)
15663 // This eliminates the zext. This transformation is necessary because
15664 // ISD::SETCC is always legalized to i8.
15665 DebugLoc dl = N->getDebugLoc();
15666 SDValue N0 = N->getOperand(0);
15667 EVT VT = N->getValueType(0);
15668 EVT OpVT = N0.getValueType();
15670 if (N0.getOpcode() == ISD::AND &&
15672 N0.getOperand(0).hasOneUse()) {
15673 SDValue N00 = N0.getOperand(0);
15674 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15676 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15677 if (!C || C->getZExtValue() != 1)
15679 return DAG.getNode(ISD::AND, dl, VT,
15680 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15681 N00.getOperand(0), N00.getOperand(1)),
15682 DAG.getConstant(1, VT));
15685 // Optimize vectors in AVX mode:
15688 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15689 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15690 // Concat upper and lower parts.
15693 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15694 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15695 // Concat upper and lower parts.
15697 if (!DCI.isBeforeLegalizeOps())
15700 if (!Subtarget->hasAVX())
15703 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15704 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15706 if (Subtarget->hasAVX2())
15707 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15709 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15710 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15711 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15713 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15714 VT.getVectorNumElements()/2);
15716 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15717 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15719 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15725 // Optimize x == -y --> x+y == 0
15726 // x != -y --> x+y != 0
15727 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15728 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15729 SDValue LHS = N->getOperand(0);
15730 SDValue RHS = N->getOperand(1);
15732 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15733 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15734 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15735 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15736 LHS.getValueType(), RHS, LHS.getOperand(1));
15737 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15738 addV, DAG.getConstant(0, addV.getValueType()), CC);
15740 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15741 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15742 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15743 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15744 RHS.getValueType(), LHS, RHS.getOperand(1));
15745 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15746 addV, DAG.getConstant(0, addV.getValueType()), CC);
15751 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15752 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15753 TargetLowering::DAGCombinerInfo &DCI,
15754 const X86Subtarget *Subtarget) {
15755 DebugLoc DL = N->getDebugLoc();
15756 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15757 SDValue EFLAGS = N->getOperand(1);
15759 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15760 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15762 if (CC == X86::COND_B)
15763 return DAG.getNode(ISD::AND, DL, MVT::i8,
15764 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15765 DAG.getConstant(CC, MVT::i8), EFLAGS),
15766 DAG.getConstant(1, MVT::i8));
15770 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15771 if (Flags.getNode()) {
15772 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15773 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15776 Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15777 if (Flags.getNode()) {
15778 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15779 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15785 // Optimize branch condition evaluation.
15787 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15788 TargetLowering::DAGCombinerInfo &DCI,
15789 const X86Subtarget *Subtarget) {
15790 DebugLoc DL = N->getDebugLoc();
15791 SDValue Chain = N->getOperand(0);
15792 SDValue Dest = N->getOperand(1);
15793 SDValue EFLAGS = N->getOperand(3);
15794 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15798 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15799 if (Flags.getNode()) {
15800 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15801 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15805 Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15806 if (Flags.getNode()) {
15807 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15808 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15815 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15816 SDValue Op0 = N->getOperand(0);
15817 EVT InVT = Op0->getValueType(0);
15819 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15820 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15821 DebugLoc dl = N->getDebugLoc();
15822 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15823 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15824 // Notice that we use SINT_TO_FP because we know that the high bits
15825 // are zero and SINT_TO_FP is better supported by the hardware.
15826 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15832 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15833 const X86TargetLowering *XTLI) {
15834 SDValue Op0 = N->getOperand(0);
15835 EVT InVT = Op0->getValueType(0);
15837 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15838 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15839 DebugLoc dl = N->getDebugLoc();
15840 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15841 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15842 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15845 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15846 // a 32-bit target where SSE doesn't support i64->FP operations.
15847 if (Op0.getOpcode() == ISD::LOAD) {
15848 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15849 EVT VT = Ld->getValueType(0);
15850 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15851 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15852 !XTLI->getSubtarget()->is64Bit() &&
15853 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15854 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15855 Ld->getChain(), Op0, DAG);
15856 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15863 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15864 EVT VT = N->getValueType(0);
15866 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15867 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15868 DebugLoc dl = N->getDebugLoc();
15869 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15870 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15871 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15877 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15878 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15879 X86TargetLowering::DAGCombinerInfo &DCI) {
15880 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15881 // the result is either zero or one (depending on the input carry bit).
15882 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15883 if (X86::isZeroNode(N->getOperand(0)) &&
15884 X86::isZeroNode(N->getOperand(1)) &&
15885 // We don't have a good way to replace an EFLAGS use, so only do this when
15887 SDValue(N, 1).use_empty()) {
15888 DebugLoc DL = N->getDebugLoc();
15889 EVT VT = N->getValueType(0);
15890 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15891 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15892 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15893 DAG.getConstant(X86::COND_B,MVT::i8),
15895 DAG.getConstant(1, VT));
15896 return DCI.CombineTo(N, Res1, CarryOut);
15902 // fold (add Y, (sete X, 0)) -> adc 0, Y
15903 // (add Y, (setne X, 0)) -> sbb -1, Y
15904 // (sub (sete X, 0), Y) -> sbb 0, Y
15905 // (sub (setne X, 0), Y) -> adc -1, Y
15906 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15907 DebugLoc DL = N->getDebugLoc();
15909 // Look through ZExts.
15910 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15911 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15914 SDValue SetCC = Ext.getOperand(0);
15915 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15918 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15919 if (CC != X86::COND_E && CC != X86::COND_NE)
15922 SDValue Cmp = SetCC.getOperand(1);
15923 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15924 !X86::isZeroNode(Cmp.getOperand(1)) ||
15925 !Cmp.getOperand(0).getValueType().isInteger())
15928 SDValue CmpOp0 = Cmp.getOperand(0);
15929 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15930 DAG.getConstant(1, CmpOp0.getValueType()));
15932 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15933 if (CC == X86::COND_NE)
15934 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15935 DL, OtherVal.getValueType(), OtherVal,
15936 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15937 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15938 DL, OtherVal.getValueType(), OtherVal,
15939 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15942 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15943 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15944 const X86Subtarget *Subtarget) {
15945 EVT VT = N->getValueType(0);
15946 SDValue Op0 = N->getOperand(0);
15947 SDValue Op1 = N->getOperand(1);
15949 // Try to synthesize horizontal adds from adds of shuffles.
15950 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15951 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15952 isHorizontalBinOp(Op0, Op1, true))
15953 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15955 return OptimizeConditionalInDecrement(N, DAG);
15958 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15959 const X86Subtarget *Subtarget) {
15960 SDValue Op0 = N->getOperand(0);
15961 SDValue Op1 = N->getOperand(1);
15963 // X86 can't encode an immediate LHS of a sub. See if we can push the
15964 // negation into a preceding instruction.
15965 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15966 // If the RHS of the sub is a XOR with one use and a constant, invert the
15967 // immediate. Then add one to the LHS of the sub so we can turn
15968 // X-Y -> X+~Y+1, saving one register.
15969 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15970 isa<ConstantSDNode>(Op1.getOperand(1))) {
15971 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15972 EVT VT = Op0.getValueType();
15973 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15975 DAG.getConstant(~XorC, VT));
15976 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15977 DAG.getConstant(C->getAPIntValue()+1, VT));
15981 // Try to synthesize horizontal adds from adds of shuffles.
15982 EVT VT = N->getValueType(0);
15983 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15984 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15985 isHorizontalBinOp(Op0, Op1, true))
15986 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15988 return OptimizeConditionalInDecrement(N, DAG);
15991 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15992 DAGCombinerInfo &DCI) const {
15993 SelectionDAG &DAG = DCI.DAG;
15994 switch (N->getOpcode()) {
15996 case ISD::EXTRACT_VECTOR_ELT:
15997 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15999 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16000 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16001 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16002 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16003 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16004 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16007 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16008 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16009 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16010 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16011 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16012 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16013 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16014 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16015 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
16016 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16017 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16019 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16021 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16022 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16023 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16024 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16025 case ISD::ANY_EXTEND:
16026 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16027 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16028 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG, DCI);
16029 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16030 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16031 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16032 case X86ISD::SHUFP: // Handle all target specific shuffles
16033 case X86ISD::PALIGN:
16034 case X86ISD::UNPCKH:
16035 case X86ISD::UNPCKL:
16036 case X86ISD::MOVHLPS:
16037 case X86ISD::MOVLHPS:
16038 case X86ISD::PSHUFD:
16039 case X86ISD::PSHUFHW:
16040 case X86ISD::PSHUFLW:
16041 case X86ISD::MOVSS:
16042 case X86ISD::MOVSD:
16043 case X86ISD::VPERMILP:
16044 case X86ISD::VPERM2X128:
16045 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16046 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16052 /// isTypeDesirableForOp - Return true if the target has native support for
16053 /// the specified value type and it is 'desirable' to use the type for the
16054 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16055 /// instruction encodings are longer and some i16 instructions are slow.
16056 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16057 if (!isTypeLegal(VT))
16059 if (VT != MVT::i16)
16066 case ISD::SIGN_EXTEND:
16067 case ISD::ZERO_EXTEND:
16068 case ISD::ANY_EXTEND:
16081 /// IsDesirableToPromoteOp - This method query the target whether it is
16082 /// beneficial for dag combiner to promote the specified node. If true, it
16083 /// should return the desired promotion type by reference.
16084 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16085 EVT VT = Op.getValueType();
16086 if (VT != MVT::i16)
16089 bool Promote = false;
16090 bool Commute = false;
16091 switch (Op.getOpcode()) {
16094 LoadSDNode *LD = cast<LoadSDNode>(Op);
16095 // If the non-extending load has a single use and it's not live out, then it
16096 // might be folded.
16097 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16098 Op.hasOneUse()*/) {
16099 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16100 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16101 // The only case where we'd want to promote LOAD (rather then it being
16102 // promoted as an operand is when it's only use is liveout.
16103 if (UI->getOpcode() != ISD::CopyToReg)
16110 case ISD::SIGN_EXTEND:
16111 case ISD::ZERO_EXTEND:
16112 case ISD::ANY_EXTEND:
16117 SDValue N0 = Op.getOperand(0);
16118 // Look out for (store (shl (load), x)).
16119 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16132 SDValue N0 = Op.getOperand(0);
16133 SDValue N1 = Op.getOperand(1);
16134 if (!Commute && MayFoldLoad(N1))
16136 // Avoid disabling potential load folding opportunities.
16137 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16139 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16149 //===----------------------------------------------------------------------===//
16150 // X86 Inline Assembly Support
16151 //===----------------------------------------------------------------------===//
16154 // Helper to match a string separated by whitespace.
16155 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16156 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16158 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16159 StringRef piece(*args[i]);
16160 if (!s.startswith(piece)) // Check if the piece matches.
16163 s = s.substr(piece.size());
16164 StringRef::size_type pos = s.find_first_not_of(" \t");
16165 if (pos == 0) // We matched a prefix.
16173 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16176 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16177 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16179 std::string AsmStr = IA->getAsmString();
16181 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16182 if (!Ty || Ty->getBitWidth() % 16 != 0)
16185 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16186 SmallVector<StringRef, 4> AsmPieces;
16187 SplitString(AsmStr, AsmPieces, ";\n");
16189 switch (AsmPieces.size()) {
16190 default: return false;
16192 // FIXME: this should verify that we are targeting a 486 or better. If not,
16193 // we will turn this bswap into something that will be lowered to logical
16194 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16195 // lower so don't worry about this.
16197 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16198 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16199 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16200 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16201 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16202 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16203 // No need to check constraints, nothing other than the equivalent of
16204 // "=r,0" would be valid here.
16205 return IntrinsicLowering::LowerToByteSwap(CI);
16208 // rorw $$8, ${0:w} --> llvm.bswap.i16
16209 if (CI->getType()->isIntegerTy(16) &&
16210 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16211 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16212 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16214 const std::string &ConstraintsStr = IA->getConstraintString();
16215 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16216 std::sort(AsmPieces.begin(), AsmPieces.end());
16217 if (AsmPieces.size() == 4 &&
16218 AsmPieces[0] == "~{cc}" &&
16219 AsmPieces[1] == "~{dirflag}" &&
16220 AsmPieces[2] == "~{flags}" &&
16221 AsmPieces[3] == "~{fpsr}")
16222 return IntrinsicLowering::LowerToByteSwap(CI);
16226 if (CI->getType()->isIntegerTy(32) &&
16227 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16228 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16229 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16230 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16232 const std::string &ConstraintsStr = IA->getConstraintString();
16233 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16234 std::sort(AsmPieces.begin(), AsmPieces.end());
16235 if (AsmPieces.size() == 4 &&
16236 AsmPieces[0] == "~{cc}" &&
16237 AsmPieces[1] == "~{dirflag}" &&
16238 AsmPieces[2] == "~{flags}" &&
16239 AsmPieces[3] == "~{fpsr}")
16240 return IntrinsicLowering::LowerToByteSwap(CI);
16243 if (CI->getType()->isIntegerTy(64)) {
16244 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16245 if (Constraints.size() >= 2 &&
16246 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16247 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16248 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16249 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16250 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16251 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16252 return IntrinsicLowering::LowerToByteSwap(CI);
16262 /// getConstraintType - Given a constraint letter, return the type of
16263 /// constraint it is for this target.
16264 X86TargetLowering::ConstraintType
16265 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16266 if (Constraint.size() == 1) {
16267 switch (Constraint[0]) {
16278 return C_RegisterClass;
16302 return TargetLowering::getConstraintType(Constraint);
16305 /// Examine constraint type and operand type and determine a weight value.
16306 /// This object must already have been set up with the operand type
16307 /// and the current alternative constraint selected.
16308 TargetLowering::ConstraintWeight
16309 X86TargetLowering::getSingleConstraintMatchWeight(
16310 AsmOperandInfo &info, const char *constraint) const {
16311 ConstraintWeight weight = CW_Invalid;
16312 Value *CallOperandVal = info.CallOperandVal;
16313 // If we don't have a value, we can't do a match,
16314 // but allow it at the lowest weight.
16315 if (CallOperandVal == NULL)
16317 Type *type = CallOperandVal->getType();
16318 // Look at the constraint type.
16319 switch (*constraint) {
16321 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16332 if (CallOperandVal->getType()->isIntegerTy())
16333 weight = CW_SpecificReg;
16338 if (type->isFloatingPointTy())
16339 weight = CW_SpecificReg;
16342 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16343 weight = CW_SpecificReg;
16347 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16348 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16349 weight = CW_Register;
16352 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16353 if (C->getZExtValue() <= 31)
16354 weight = CW_Constant;
16358 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16359 if (C->getZExtValue() <= 63)
16360 weight = CW_Constant;
16364 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16365 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16366 weight = CW_Constant;
16370 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16371 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16372 weight = CW_Constant;
16376 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16377 if (C->getZExtValue() <= 3)
16378 weight = CW_Constant;
16382 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16383 if (C->getZExtValue() <= 0xff)
16384 weight = CW_Constant;
16389 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16390 weight = CW_Constant;
16394 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16395 if ((C->getSExtValue() >= -0x80000000LL) &&
16396 (C->getSExtValue() <= 0x7fffffffLL))
16397 weight = CW_Constant;
16401 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16402 if (C->getZExtValue() <= 0xffffffff)
16403 weight = CW_Constant;
16410 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16411 /// with another that has more specific requirements based on the type of the
16412 /// corresponding operand.
16413 const char *X86TargetLowering::
16414 LowerXConstraint(EVT ConstraintVT) const {
16415 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16416 // 'f' like normal targets.
16417 if (ConstraintVT.isFloatingPoint()) {
16418 if (Subtarget->hasSSE2())
16420 if (Subtarget->hasSSE1())
16424 return TargetLowering::LowerXConstraint(ConstraintVT);
16427 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16428 /// vector. If it is invalid, don't add anything to Ops.
16429 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16430 std::string &Constraint,
16431 std::vector<SDValue>&Ops,
16432 SelectionDAG &DAG) const {
16433 SDValue Result(0, 0);
16435 // Only support length 1 constraints for now.
16436 if (Constraint.length() > 1) return;
16438 char ConstraintLetter = Constraint[0];
16439 switch (ConstraintLetter) {
16442 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16443 if (C->getZExtValue() <= 31) {
16444 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16450 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16451 if (C->getZExtValue() <= 63) {
16452 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16458 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16459 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16460 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16466 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16467 if (C->getZExtValue() <= 255) {
16468 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16474 // 32-bit signed value
16475 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16476 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16477 C->getSExtValue())) {
16478 // Widen to 64 bits here to get it sign extended.
16479 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16482 // FIXME gcc accepts some relocatable values here too, but only in certain
16483 // memory models; it's complicated.
16488 // 32-bit unsigned value
16489 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16490 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16491 C->getZExtValue())) {
16492 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16496 // FIXME gcc accepts some relocatable values here too, but only in certain
16497 // memory models; it's complicated.
16501 // Literal immediates are always ok.
16502 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16503 // Widen to 64 bits here to get it sign extended.
16504 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16508 // In any sort of PIC mode addresses need to be computed at runtime by
16509 // adding in a register or some sort of table lookup. These can't
16510 // be used as immediates.
16511 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16514 // If we are in non-pic codegen mode, we allow the address of a global (with
16515 // an optional displacement) to be used with 'i'.
16516 GlobalAddressSDNode *GA = 0;
16517 int64_t Offset = 0;
16519 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16521 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16522 Offset += GA->getOffset();
16524 } else if (Op.getOpcode() == ISD::ADD) {
16525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16526 Offset += C->getZExtValue();
16527 Op = Op.getOperand(0);
16530 } else if (Op.getOpcode() == ISD::SUB) {
16531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16532 Offset += -C->getZExtValue();
16533 Op = Op.getOperand(0);
16538 // Otherwise, this isn't something we can handle, reject it.
16542 const GlobalValue *GV = GA->getGlobal();
16543 // If we require an extra load to get this address, as in PIC mode, we
16544 // can't accept it.
16545 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16546 getTargetMachine())))
16549 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16550 GA->getValueType(0), Offset);
16555 if (Result.getNode()) {
16556 Ops.push_back(Result);
16559 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16562 std::pair<unsigned, const TargetRegisterClass*>
16563 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16565 // First, see if this is a constraint that directly corresponds to an LLVM
16567 if (Constraint.size() == 1) {
16568 // GCC Constraint Letters
16569 switch (Constraint[0]) {
16571 // TODO: Slight differences here in allocation order and leaving
16572 // RIP in the class. Do they matter any more here than they do
16573 // in the normal allocation?
16574 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16575 if (Subtarget->is64Bit()) {
16576 if (VT == MVT::i32 || VT == MVT::f32)
16577 return std::make_pair(0U, &X86::GR32RegClass);
16578 if (VT == MVT::i16)
16579 return std::make_pair(0U, &X86::GR16RegClass);
16580 if (VT == MVT::i8 || VT == MVT::i1)
16581 return std::make_pair(0U, &X86::GR8RegClass);
16582 if (VT == MVT::i64 || VT == MVT::f64)
16583 return std::make_pair(0U, &X86::GR64RegClass);
16586 // 32-bit fallthrough
16587 case 'Q': // Q_REGS
16588 if (VT == MVT::i32 || VT == MVT::f32)
16589 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16590 if (VT == MVT::i16)
16591 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16592 if (VT == MVT::i8 || VT == MVT::i1)
16593 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16594 if (VT == MVT::i64)
16595 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16597 case 'r': // GENERAL_REGS
16598 case 'l': // INDEX_REGS
16599 if (VT == MVT::i8 || VT == MVT::i1)
16600 return std::make_pair(0U, &X86::GR8RegClass);
16601 if (VT == MVT::i16)
16602 return std::make_pair(0U, &X86::GR16RegClass);
16603 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16604 return std::make_pair(0U, &X86::GR32RegClass);
16605 return std::make_pair(0U, &X86::GR64RegClass);
16606 case 'R': // LEGACY_REGS
16607 if (VT == MVT::i8 || VT == MVT::i1)
16608 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16609 if (VT == MVT::i16)
16610 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16611 if (VT == MVT::i32 || !Subtarget->is64Bit())
16612 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16613 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16614 case 'f': // FP Stack registers.
16615 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16616 // value to the correct fpstack register class.
16617 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16618 return std::make_pair(0U, &X86::RFP32RegClass);
16619 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16620 return std::make_pair(0U, &X86::RFP64RegClass);
16621 return std::make_pair(0U, &X86::RFP80RegClass);
16622 case 'y': // MMX_REGS if MMX allowed.
16623 if (!Subtarget->hasMMX()) break;
16624 return std::make_pair(0U, &X86::VR64RegClass);
16625 case 'Y': // SSE_REGS if SSE2 allowed
16626 if (!Subtarget->hasSSE2()) break;
16628 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16629 if (!Subtarget->hasSSE1()) break;
16631 switch (VT.getSimpleVT().SimpleTy) {
16633 // Scalar SSE types.
16636 return std::make_pair(0U, &X86::FR32RegClass);
16639 return std::make_pair(0U, &X86::FR64RegClass);
16647 return std::make_pair(0U, &X86::VR128RegClass);
16655 return std::make_pair(0U, &X86::VR256RegClass);
16661 // Use the default implementation in TargetLowering to convert the register
16662 // constraint into a member of a register class.
16663 std::pair<unsigned, const TargetRegisterClass*> Res;
16664 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16666 // Not found as a standard register?
16667 if (Res.second == 0) {
16668 // Map st(0) -> st(7) -> ST0
16669 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16670 tolower(Constraint[1]) == 's' &&
16671 tolower(Constraint[2]) == 't' &&
16672 Constraint[3] == '(' &&
16673 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16674 Constraint[5] == ')' &&
16675 Constraint[6] == '}') {
16677 Res.first = X86::ST0+Constraint[4]-'0';
16678 Res.second = &X86::RFP80RegClass;
16682 // GCC allows "st(0)" to be called just plain "st".
16683 if (StringRef("{st}").equals_lower(Constraint)) {
16684 Res.first = X86::ST0;
16685 Res.second = &X86::RFP80RegClass;
16690 if (StringRef("{flags}").equals_lower(Constraint)) {
16691 Res.first = X86::EFLAGS;
16692 Res.second = &X86::CCRRegClass;
16696 // 'A' means EAX + EDX.
16697 if (Constraint == "A") {
16698 Res.first = X86::EAX;
16699 Res.second = &X86::GR32_ADRegClass;
16705 // Otherwise, check to see if this is a register class of the wrong value
16706 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16707 // turn into {ax},{dx}.
16708 if (Res.second->hasType(VT))
16709 return Res; // Correct type already, nothing to do.
16711 // All of the single-register GCC register classes map their values onto
16712 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16713 // really want an 8-bit or 32-bit register, map to the appropriate register
16714 // class and return the appropriate register.
16715 if (Res.second == &X86::GR16RegClass) {
16716 if (VT == MVT::i8) {
16717 unsigned DestReg = 0;
16718 switch (Res.first) {
16720 case X86::AX: DestReg = X86::AL; break;
16721 case X86::DX: DestReg = X86::DL; break;
16722 case X86::CX: DestReg = X86::CL; break;
16723 case X86::BX: DestReg = X86::BL; break;
16726 Res.first = DestReg;
16727 Res.second = &X86::GR8RegClass;
16729 } else if (VT == MVT::i32) {
16730 unsigned DestReg = 0;
16731 switch (Res.first) {
16733 case X86::AX: DestReg = X86::EAX; break;
16734 case X86::DX: DestReg = X86::EDX; break;
16735 case X86::CX: DestReg = X86::ECX; break;
16736 case X86::BX: DestReg = X86::EBX; break;
16737 case X86::SI: DestReg = X86::ESI; break;
16738 case X86::DI: DestReg = X86::EDI; break;
16739 case X86::BP: DestReg = X86::EBP; break;
16740 case X86::SP: DestReg = X86::ESP; break;
16743 Res.first = DestReg;
16744 Res.second = &X86::GR32RegClass;
16746 } else if (VT == MVT::i64) {
16747 unsigned DestReg = 0;
16748 switch (Res.first) {
16750 case X86::AX: DestReg = X86::RAX; break;
16751 case X86::DX: DestReg = X86::RDX; break;
16752 case X86::CX: DestReg = X86::RCX; break;
16753 case X86::BX: DestReg = X86::RBX; break;
16754 case X86::SI: DestReg = X86::RSI; break;
16755 case X86::DI: DestReg = X86::RDI; break;
16756 case X86::BP: DestReg = X86::RBP; break;
16757 case X86::SP: DestReg = X86::RSP; break;
16760 Res.first = DestReg;
16761 Res.second = &X86::GR64RegClass;
16764 } else if (Res.second == &X86::FR32RegClass ||
16765 Res.second == &X86::FR64RegClass ||
16766 Res.second == &X86::VR128RegClass) {
16767 // Handle references to XMM physical registers that got mapped into the
16768 // wrong class. This can happen with constraints like {xmm0} where the
16769 // target independent register mapper will just pick the first match it can
16770 // find, ignoring the required type.
16772 if (VT == MVT::f32 || VT == MVT::i32)
16773 Res.second = &X86::FR32RegClass;
16774 else if (VT == MVT::f64 || VT == MVT::i64)
16775 Res.second = &X86::FR64RegClass;
16776 else if (X86::VR128RegClass.hasType(VT))
16777 Res.second = &X86::VR128RegClass;
16778 else if (X86::VR256RegClass.hasType(VT))
16779 Res.second = &X86::VR256RegClass;