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.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
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::FFLOOR, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
770 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
775 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
776 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
777 setTruncStoreAction((MVT::SimpleValueType)VT,
778 (MVT::SimpleValueType)InnerVT, Expand);
779 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
780 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
781 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
784 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
785 // with -msoft-float, disable use of MMX as well.
786 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
787 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
788 // No operations on x86mmx supported, everything uses intrinsics.
791 // MMX-sized vectors (other than x86mmx) are expected to be expanded
792 // into smaller operations.
793 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
794 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
795 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
796 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
797 setOperationAction(ISD::AND, MVT::v8i8, Expand);
798 setOperationAction(ISD::AND, MVT::v4i16, Expand);
799 setOperationAction(ISD::AND, MVT::v2i32, Expand);
800 setOperationAction(ISD::AND, MVT::v1i64, Expand);
801 setOperationAction(ISD::OR, MVT::v8i8, Expand);
802 setOperationAction(ISD::OR, MVT::v4i16, Expand);
803 setOperationAction(ISD::OR, MVT::v2i32, Expand);
804 setOperationAction(ISD::OR, MVT::v1i64, Expand);
805 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
806 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
807 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
808 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
809 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
810 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
811 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
812 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
813 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
814 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
815 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
816 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
817 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
818 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
819 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
820 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
821 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
823 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
824 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
826 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
827 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
828 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
829 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
831 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
832 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
833 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
834 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
835 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
836 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
837 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
840 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
841 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
843 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
844 // registers cannot be used even for integer operations.
845 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
846 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
847 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
848 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
850 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
851 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
852 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
853 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
854 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
855 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
856 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
857 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
858 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
859 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
860 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
861 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
862 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
863 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
864 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
865 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
866 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
868 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
869 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
870 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
871 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
873 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
874 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
876 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
877 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
879 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881 MVT VT = (MVT::SimpleValueType)i;
882 // Do not attempt to custom lower non-power-of-2 vectors
883 if (!isPowerOf2_32(VT.getVectorNumElements()))
885 // Do not attempt to custom lower non-128-bit vectors
886 if (!VT.is128BitVector())
888 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
889 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
890 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
893 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
894 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
895 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
896 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
900 if (Subtarget->is64Bit()) {
901 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
902 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
905 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907 MVT VT = (MVT::SimpleValueType)i;
909 // Do not attempt to promote non-128-bit vectors
910 if (!VT.is128BitVector())
913 setOperationAction(ISD::AND, VT, Promote);
914 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
915 setOperationAction(ISD::OR, VT, Promote);
916 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
917 setOperationAction(ISD::XOR, VT, Promote);
918 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
919 setOperationAction(ISD::LOAD, VT, Promote);
920 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
921 setOperationAction(ISD::SELECT, VT, Promote);
922 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
925 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
927 // Custom lower v2i64 and v2f64 selects.
928 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
929 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
930 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
931 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
933 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
934 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
937 if (Subtarget->hasSSE41()) {
938 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
939 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
940 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
941 setOperationAction(ISD::FRINT, MVT::f32, Legal);
942 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
943 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
944 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
945 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
946 setOperationAction(ISD::FRINT, MVT::f64, Legal);
947 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
949 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
950 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
952 // FIXME: Do we need to handle scalar-to-vector here?
953 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
955 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
956 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
957 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
958 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
959 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
961 // i8 and i16 vectors are custom , because the source register and source
962 // source memory operand types are not the same width. f32 vectors are
963 // custom since the immediate controlling the insert encodes additional
965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
970 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
971 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
972 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
973 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
975 // FIXME: these should be Legal but thats only for the case where
976 // the index is constant. For now custom expand to deal with that.
977 if (Subtarget->is64Bit()) {
978 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
979 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
983 if (Subtarget->hasSSE2()) {
984 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
985 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
987 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
988 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
990 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
991 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
993 if (Subtarget->hasAVX2()) {
994 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
995 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
997 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
998 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1000 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1002 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1003 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1005 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1006 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1008 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1012 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1013 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1014 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1015 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1016 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1017 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1018 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1020 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1021 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1022 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1024 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1025 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1026 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1027 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1028 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1029 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1030 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1031 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1033 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1034 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1035 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1036 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1037 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1038 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1039 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1040 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1042 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1043 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1044 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1046 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1047 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1049 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1050 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1052 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1053 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1055 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1056 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1057 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1058 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1060 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1061 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1062 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1064 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1069 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1070 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1071 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1072 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1073 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1074 setOperationAction(ISD::FMA, MVT::f32, Custom);
1075 setOperationAction(ISD::FMA, MVT::f64, Custom);
1078 if (Subtarget->hasAVX2()) {
1079 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1080 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1081 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1082 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1084 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1085 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1086 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1087 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1089 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1090 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1091 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1092 // Don't lower v32i8 because there is no 128-bit byte mul
1094 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1096 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1097 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1099 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1100 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1102 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1104 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1105 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1106 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1107 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1109 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1110 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1111 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1112 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1114 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1115 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1116 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1117 // Don't lower v32i8 because there is no 128-bit byte mul
1119 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1120 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1122 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1123 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1125 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1128 // Custom lower several nodes for 256-bit types.
1129 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1130 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1131 MVT VT = (MVT::SimpleValueType)i;
1133 // Extract subvector is special because the value type
1134 // (result) is 128-bit but the source is 256-bit wide.
1135 if (VT.is128BitVector())
1136 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1138 // Do not attempt to custom lower other non-256-bit vectors
1139 if (!VT.is256BitVector())
1142 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1143 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1144 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1145 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1146 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1147 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1148 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1151 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1152 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1153 MVT VT = (MVT::SimpleValueType)i;
1155 // Do not attempt to promote non-256-bit vectors
1156 if (!VT.is256BitVector())
1159 setOperationAction(ISD::AND, VT, Promote);
1160 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1161 setOperationAction(ISD::OR, VT, Promote);
1162 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1163 setOperationAction(ISD::XOR, VT, Promote);
1164 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1165 setOperationAction(ISD::LOAD, VT, Promote);
1166 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1167 setOperationAction(ISD::SELECT, VT, Promote);
1168 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1172 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1173 // of this type with custom code.
1174 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1175 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1176 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1180 // We want to custom lower some of our intrinsics.
1181 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1182 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1185 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1186 // handle type legalization for these operations here.
1188 // FIXME: We really should do custom legalization for addition and
1189 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1190 // than generic legalization for 64-bit multiplication-with-overflow, though.
1191 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1192 // Add/Sub/Mul with overflow operations are custom lowered.
1194 setOperationAction(ISD::SADDO, VT, Custom);
1195 setOperationAction(ISD::UADDO, VT, Custom);
1196 setOperationAction(ISD::SSUBO, VT, Custom);
1197 setOperationAction(ISD::USUBO, VT, Custom);
1198 setOperationAction(ISD::SMULO, VT, Custom);
1199 setOperationAction(ISD::UMULO, VT, Custom);
1202 // There are no 8-bit 3-address imul/mul instructions
1203 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1204 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1206 if (!Subtarget->is64Bit()) {
1207 // These libcalls are not available in 32-bit.
1208 setLibcallName(RTLIB::SHL_I128, 0);
1209 setLibcallName(RTLIB::SRL_I128, 0);
1210 setLibcallName(RTLIB::SRA_I128, 0);
1213 // We have target-specific dag combine patterns for the following nodes:
1214 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1215 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1216 setTargetDAGCombine(ISD::VSELECT);
1217 setTargetDAGCombine(ISD::SELECT);
1218 setTargetDAGCombine(ISD::SHL);
1219 setTargetDAGCombine(ISD::SRA);
1220 setTargetDAGCombine(ISD::SRL);
1221 setTargetDAGCombine(ISD::OR);
1222 setTargetDAGCombine(ISD::AND);
1223 setTargetDAGCombine(ISD::ADD);
1224 setTargetDAGCombine(ISD::FADD);
1225 setTargetDAGCombine(ISD::FSUB);
1226 setTargetDAGCombine(ISD::FMA);
1227 setTargetDAGCombine(ISD::SUB);
1228 setTargetDAGCombine(ISD::LOAD);
1229 setTargetDAGCombine(ISD::STORE);
1230 setTargetDAGCombine(ISD::ZERO_EXTEND);
1231 setTargetDAGCombine(ISD::ANY_EXTEND);
1232 setTargetDAGCombine(ISD::SIGN_EXTEND);
1233 setTargetDAGCombine(ISD::TRUNCATE);
1234 setTargetDAGCombine(ISD::UINT_TO_FP);
1235 setTargetDAGCombine(ISD::SINT_TO_FP);
1236 setTargetDAGCombine(ISD::SETCC);
1237 setTargetDAGCombine(ISD::FP_TO_SINT);
1238 if (Subtarget->is64Bit())
1239 setTargetDAGCombine(ISD::MUL);
1240 setTargetDAGCombine(ISD::XOR);
1242 computeRegisterProperties();
1244 // On Darwin, -Os means optimize for size without hurting performance,
1245 // do not reduce the limit.
1246 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1247 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1248 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1249 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1250 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1251 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1252 setPrefLoopAlignment(4); // 2^4 bytes.
1253 benefitFromCodePlacementOpt = true;
1255 // Predictable cmov don't hurt on atom because it's in-order.
1256 predictableSelectIsExpensive = !Subtarget->isAtom();
1258 setPrefFunctionAlignment(4); // 2^4 bytes.
1262 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1263 if (!VT.isVector()) return MVT::i8;
1264 return VT.changeVectorElementTypeToInteger();
1268 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1269 /// the desired ByVal argument alignment.
1270 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1273 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1274 if (VTy->getBitWidth() == 128)
1276 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1277 unsigned EltAlign = 0;
1278 getMaxByValAlign(ATy->getElementType(), EltAlign);
1279 if (EltAlign > MaxAlign)
1280 MaxAlign = EltAlign;
1281 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1282 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1283 unsigned EltAlign = 0;
1284 getMaxByValAlign(STy->getElementType(i), EltAlign);
1285 if (EltAlign > MaxAlign)
1286 MaxAlign = EltAlign;
1293 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1294 /// function arguments in the caller parameter area. For X86, aggregates
1295 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1296 /// are at 4-byte boundaries.
1297 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1298 if (Subtarget->is64Bit()) {
1299 // Max of 8 and alignment of type.
1300 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1307 if (Subtarget->hasSSE1())
1308 getMaxByValAlign(Ty, Align);
1312 /// getOptimalMemOpType - Returns the target specific optimal type for load
1313 /// and store operations as a result of memset, memcpy, and memmove
1314 /// lowering. If DstAlign is zero that means it's safe to destination
1315 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1316 /// means there isn't a need to check it against alignment requirement,
1317 /// probably because the source does not need to be loaded. If
1318 /// 'IsZeroVal' is true, that means it's safe to return a
1319 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1320 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1321 /// constant so it does not need to be loaded.
1322 /// It returns EVT::Other if the type should be determined using generic
1323 /// target-independent logic.
1325 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1326 unsigned DstAlign, unsigned SrcAlign,
1329 MachineFunction &MF) const {
1330 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1331 // linux. This is because the stack realignment code can't handle certain
1332 // cases like PR2962. This should be removed when PR2962 is fixed.
1333 const Function *F = MF.getFunction();
1335 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1337 (Subtarget->isUnalignedMemAccessFast() ||
1338 ((DstAlign == 0 || DstAlign >= 16) &&
1339 (SrcAlign == 0 || SrcAlign >= 16))) &&
1340 Subtarget->getStackAlignment() >= 16) {
1341 if (Subtarget->getStackAlignment() >= 32) {
1342 if (Subtarget->hasAVX2())
1344 if (Subtarget->hasAVX())
1347 if (Subtarget->hasSSE2())
1349 if (Subtarget->hasSSE1())
1351 } else if (!MemcpyStrSrc && Size >= 8 &&
1352 !Subtarget->is64Bit() &&
1353 Subtarget->getStackAlignment() >= 8 &&
1354 Subtarget->hasSSE2()) {
1355 // Do not use f64 to lower memcpy if source is string constant. It's
1356 // better to use i32 to avoid the loads.
1360 if (Subtarget->is64Bit() && Size >= 8)
1365 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1366 /// current function. The returned value is a member of the
1367 /// MachineJumpTableInfo::JTEntryKind enum.
1368 unsigned X86TargetLowering::getJumpTableEncoding() const {
1369 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1371 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1372 Subtarget->isPICStyleGOT())
1373 return MachineJumpTableInfo::EK_Custom32;
1375 // Otherwise, use the normal jump table encoding heuristics.
1376 return TargetLowering::getJumpTableEncoding();
1380 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1381 const MachineBasicBlock *MBB,
1382 unsigned uid,MCContext &Ctx) const{
1383 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1384 Subtarget->isPICStyleGOT());
1385 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1387 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1388 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1391 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1393 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1394 SelectionDAG &DAG) const {
1395 if (!Subtarget->is64Bit())
1396 // This doesn't have DebugLoc associated with it, but is not really the
1397 // same as a Register.
1398 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1402 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1403 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1405 const MCExpr *X86TargetLowering::
1406 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1407 MCContext &Ctx) const {
1408 // X86-64 uses RIP relative addressing based on the jump table label.
1409 if (Subtarget->isPICStyleRIPRel())
1410 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1412 // Otherwise, the reference is relative to the PIC base.
1413 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1416 // FIXME: Why this routine is here? Move to RegInfo!
1417 std::pair<const TargetRegisterClass*, uint8_t>
1418 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1419 const TargetRegisterClass *RRC = 0;
1421 switch (VT.getSimpleVT().SimpleTy) {
1423 return TargetLowering::findRepresentativeClass(VT);
1424 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1425 RRC = Subtarget->is64Bit() ?
1426 (const TargetRegisterClass*)&X86::GR64RegClass :
1427 (const TargetRegisterClass*)&X86::GR32RegClass;
1430 RRC = &X86::VR64RegClass;
1432 case MVT::f32: case MVT::f64:
1433 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1434 case MVT::v4f32: case MVT::v2f64:
1435 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1437 RRC = &X86::VR128RegClass;
1440 return std::make_pair(RRC, Cost);
1443 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1444 unsigned &Offset) const {
1445 if (!Subtarget->isTargetLinux())
1448 if (Subtarget->is64Bit()) {
1449 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1451 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1464 //===----------------------------------------------------------------------===//
1465 // Return Value Calling Convention Implementation
1466 //===----------------------------------------------------------------------===//
1468 #include "X86GenCallingConv.inc"
1471 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1472 MachineFunction &MF, bool isVarArg,
1473 const SmallVectorImpl<ISD::OutputArg> &Outs,
1474 LLVMContext &Context) const {
1475 SmallVector<CCValAssign, 16> RVLocs;
1476 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1478 return CCInfo.CheckReturn(Outs, RetCC_X86);
1482 X86TargetLowering::LowerReturn(SDValue Chain,
1483 CallingConv::ID CallConv, bool isVarArg,
1484 const SmallVectorImpl<ISD::OutputArg> &Outs,
1485 const SmallVectorImpl<SDValue> &OutVals,
1486 DebugLoc dl, SelectionDAG &DAG) const {
1487 MachineFunction &MF = DAG.getMachineFunction();
1488 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1490 SmallVector<CCValAssign, 16> RVLocs;
1491 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1492 RVLocs, *DAG.getContext());
1493 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1495 // Add the regs to the liveout set for the function.
1496 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1497 for (unsigned i = 0; i != RVLocs.size(); ++i)
1498 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1499 MRI.addLiveOut(RVLocs[i].getLocReg());
1503 SmallVector<SDValue, 6> RetOps;
1504 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1505 // Operand #1 = Bytes To Pop
1506 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1509 // Copy the result values into the output registers.
1510 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1511 CCValAssign &VA = RVLocs[i];
1512 assert(VA.isRegLoc() && "Can only return in registers!");
1513 SDValue ValToCopy = OutVals[i];
1514 EVT ValVT = ValToCopy.getValueType();
1516 // Promote values to the appropriate types
1517 if (VA.getLocInfo() == CCValAssign::SExt)
1518 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1519 else if (VA.getLocInfo() == CCValAssign::ZExt)
1520 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1521 else if (VA.getLocInfo() == CCValAssign::AExt)
1522 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1523 else if (VA.getLocInfo() == CCValAssign::BCvt)
1524 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1526 // If this is x86-64, and we disabled SSE, we can't return FP values,
1527 // or SSE or MMX vectors.
1528 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1529 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1530 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1531 report_fatal_error("SSE register return with SSE disabled");
1533 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1534 // llvm-gcc has never done it right and no one has noticed, so this
1535 // should be OK for now.
1536 if (ValVT == MVT::f64 &&
1537 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1538 report_fatal_error("SSE2 register return with SSE2 disabled");
1540 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1541 // the RET instruction and handled by the FP Stackifier.
1542 if (VA.getLocReg() == X86::ST0 ||
1543 VA.getLocReg() == X86::ST1) {
1544 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1545 // change the value to the FP stack register class.
1546 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1547 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1548 RetOps.push_back(ValToCopy);
1549 // Don't emit a copytoreg.
1553 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1554 // which is returned in RAX / RDX.
1555 if (Subtarget->is64Bit()) {
1556 if (ValVT == MVT::x86mmx) {
1557 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1558 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1559 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1561 // If we don't have SSE2 available, convert to v4f32 so the generated
1562 // register is legal.
1563 if (!Subtarget->hasSSE2())
1564 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1569 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1570 Flag = Chain.getValue(1);
1573 // The x86-64 ABI for returning structs by value requires that we copy
1574 // the sret argument into %rax for the return. We saved the argument into
1575 // a virtual register in the entry block, so now we copy the value out
1577 if (Subtarget->is64Bit() &&
1578 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1579 MachineFunction &MF = DAG.getMachineFunction();
1580 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1581 unsigned Reg = FuncInfo->getSRetReturnReg();
1583 "SRetReturnReg should have been set in LowerFormalArguments().");
1584 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1586 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1587 Flag = Chain.getValue(1);
1589 // RAX now acts like a return value.
1590 MRI.addLiveOut(X86::RAX);
1593 RetOps[0] = Chain; // Update chain.
1595 // Add the flag if we have it.
1597 RetOps.push_back(Flag);
1599 return DAG.getNode(X86ISD::RET_FLAG, dl,
1600 MVT::Other, &RetOps[0], RetOps.size());
1603 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1604 if (N->getNumValues() != 1)
1606 if (!N->hasNUsesOfValue(1, 0))
1609 SDValue TCChain = Chain;
1610 SDNode *Copy = *N->use_begin();
1611 if (Copy->getOpcode() == ISD::CopyToReg) {
1612 // If the copy has a glue operand, we conservatively assume it isn't safe to
1613 // perform a tail call.
1614 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1616 TCChain = Copy->getOperand(0);
1617 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1620 bool HasRet = false;
1621 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1623 if (UI->getOpcode() != X86ISD::RET_FLAG)
1636 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1637 ISD::NodeType ExtendKind) const {
1639 // TODO: Is this also valid on 32-bit?
1640 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1641 ReturnMVT = MVT::i8;
1643 ReturnMVT = MVT::i32;
1645 EVT MinVT = getRegisterType(Context, ReturnMVT);
1646 return VT.bitsLT(MinVT) ? MinVT : VT;
1649 /// LowerCallResult - Lower the result values of a call into the
1650 /// appropriate copies out of appropriate physical registers.
1653 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1654 CallingConv::ID CallConv, bool isVarArg,
1655 const SmallVectorImpl<ISD::InputArg> &Ins,
1656 DebugLoc dl, SelectionDAG &DAG,
1657 SmallVectorImpl<SDValue> &InVals) const {
1659 // Assign locations to each value returned by this call.
1660 SmallVector<CCValAssign, 16> RVLocs;
1661 bool Is64Bit = Subtarget->is64Bit();
1662 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1663 getTargetMachine(), RVLocs, *DAG.getContext());
1664 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1666 // Copy all of the result registers out of their specified physreg.
1667 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1668 CCValAssign &VA = RVLocs[i];
1669 EVT CopyVT = VA.getValVT();
1671 // If this is x86-64, and we disabled SSE, we can't return FP values
1672 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1673 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1674 report_fatal_error("SSE register return with SSE disabled");
1679 // If this is a call to a function that returns an fp value on the floating
1680 // point stack, we must guarantee the value is popped from the stack, so
1681 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1682 // if the return value is not used. We use the FpPOP_RETVAL instruction
1684 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1685 // If we prefer to use the value in xmm registers, copy it out as f80 and
1686 // use a truncate to move it from fp stack reg to xmm reg.
1687 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1688 SDValue Ops[] = { Chain, InFlag };
1689 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1690 MVT::Other, MVT::Glue, Ops, 2), 1);
1691 Val = Chain.getValue(0);
1693 // Round the f80 to the right size, which also moves it to the appropriate
1695 if (CopyVT != VA.getValVT())
1696 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1697 // This truncation won't change the value.
1698 DAG.getIntPtrConstant(1));
1700 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1701 CopyVT, InFlag).getValue(1);
1702 Val = Chain.getValue(0);
1704 InFlag = Chain.getValue(2);
1705 InVals.push_back(Val);
1712 //===----------------------------------------------------------------------===//
1713 // C & StdCall & Fast Calling Convention implementation
1714 //===----------------------------------------------------------------------===//
1715 // StdCall calling convention seems to be standard for many Windows' API
1716 // routines and around. It differs from C calling convention just a little:
1717 // callee should clean up the stack, not caller. Symbols should be also
1718 // decorated in some fancy way :) It doesn't support any vector arguments.
1719 // For info on fast calling convention see Fast Calling Convention (tail call)
1720 // implementation LowerX86_32FastCCCallTo.
1722 /// CallIsStructReturn - Determines whether a call uses struct return
1724 enum StructReturnType {
1729 static StructReturnType
1730 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1732 return NotStructReturn;
1734 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1735 if (!Flags.isSRet())
1736 return NotStructReturn;
1737 if (Flags.isInReg())
1738 return RegStructReturn;
1739 return StackStructReturn;
1742 /// ArgsAreStructReturn - Determines whether a function uses struct
1743 /// return semantics.
1744 static StructReturnType
1745 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1747 return NotStructReturn;
1749 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1750 if (!Flags.isSRet())
1751 return NotStructReturn;
1752 if (Flags.isInReg())
1753 return RegStructReturn;
1754 return StackStructReturn;
1757 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1758 /// by "Src" to address "Dst" with size and alignment information specified by
1759 /// the specific parameter attribute. The copy will be passed as a byval
1760 /// function parameter.
1762 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1763 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1765 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1767 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1768 /*isVolatile*/false, /*AlwaysInline=*/true,
1769 MachinePointerInfo(), MachinePointerInfo());
1772 /// IsTailCallConvention - Return true if the calling convention is one that
1773 /// supports tail call optimization.
1774 static bool IsTailCallConvention(CallingConv::ID CC) {
1775 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1778 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1779 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1783 CallingConv::ID CalleeCC = CS.getCallingConv();
1784 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1790 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1791 /// a tailcall target by changing its ABI.
1792 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1793 bool GuaranteedTailCallOpt) {
1794 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1798 X86TargetLowering::LowerMemArgument(SDValue Chain,
1799 CallingConv::ID CallConv,
1800 const SmallVectorImpl<ISD::InputArg> &Ins,
1801 DebugLoc dl, SelectionDAG &DAG,
1802 const CCValAssign &VA,
1803 MachineFrameInfo *MFI,
1805 // Create the nodes corresponding to a load from this parameter slot.
1806 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1807 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1808 getTargetMachine().Options.GuaranteedTailCallOpt);
1809 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1812 // If value is passed by pointer we have address passed instead of the value
1814 if (VA.getLocInfo() == CCValAssign::Indirect)
1815 ValVT = VA.getLocVT();
1817 ValVT = VA.getValVT();
1819 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1820 // changed with more analysis.
1821 // In case of tail call optimization mark all arguments mutable. Since they
1822 // could be overwritten by lowering of arguments in case of a tail call.
1823 if (Flags.isByVal()) {
1824 unsigned Bytes = Flags.getByValSize();
1825 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1826 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1827 return DAG.getFrameIndex(FI, getPointerTy());
1829 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1830 VA.getLocMemOffset(), isImmutable);
1831 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1832 return DAG.getLoad(ValVT, dl, Chain, FIN,
1833 MachinePointerInfo::getFixedStack(FI),
1834 false, false, false, 0);
1839 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1840 CallingConv::ID CallConv,
1842 const SmallVectorImpl<ISD::InputArg> &Ins,
1845 SmallVectorImpl<SDValue> &InVals)
1847 MachineFunction &MF = DAG.getMachineFunction();
1848 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1850 const Function* Fn = MF.getFunction();
1851 if (Fn->hasExternalLinkage() &&
1852 Subtarget->isTargetCygMing() &&
1853 Fn->getName() == "main")
1854 FuncInfo->setForceFramePointer(true);
1856 MachineFrameInfo *MFI = MF.getFrameInfo();
1857 bool Is64Bit = Subtarget->is64Bit();
1858 bool IsWindows = Subtarget->isTargetWindows();
1859 bool IsWin64 = Subtarget->isTargetWin64();
1861 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1862 "Var args not supported with calling convention fastcc or ghc");
1864 // Assign locations to all of the incoming arguments.
1865 SmallVector<CCValAssign, 16> ArgLocs;
1866 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1867 ArgLocs, *DAG.getContext());
1869 // Allocate shadow area for Win64
1871 CCInfo.AllocateStack(32, 8);
1874 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1876 unsigned LastVal = ~0U;
1878 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1879 CCValAssign &VA = ArgLocs[i];
1880 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1882 assert(VA.getValNo() != LastVal &&
1883 "Don't support value assigned to multiple locs yet");
1885 LastVal = VA.getValNo();
1887 if (VA.isRegLoc()) {
1888 EVT RegVT = VA.getLocVT();
1889 const TargetRegisterClass *RC;
1890 if (RegVT == MVT::i32)
1891 RC = &X86::GR32RegClass;
1892 else if (Is64Bit && RegVT == MVT::i64)
1893 RC = &X86::GR64RegClass;
1894 else if (RegVT == MVT::f32)
1895 RC = &X86::FR32RegClass;
1896 else if (RegVT == MVT::f64)
1897 RC = &X86::FR64RegClass;
1898 else if (RegVT.is256BitVector())
1899 RC = &X86::VR256RegClass;
1900 else if (RegVT.is128BitVector())
1901 RC = &X86::VR128RegClass;
1902 else if (RegVT == MVT::x86mmx)
1903 RC = &X86::VR64RegClass;
1905 llvm_unreachable("Unknown argument type!");
1907 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1908 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1910 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1911 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1913 if (VA.getLocInfo() == CCValAssign::SExt)
1914 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1915 DAG.getValueType(VA.getValVT()));
1916 else if (VA.getLocInfo() == CCValAssign::ZExt)
1917 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1918 DAG.getValueType(VA.getValVT()));
1919 else if (VA.getLocInfo() == CCValAssign::BCvt)
1920 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1922 if (VA.isExtInLoc()) {
1923 // Handle MMX values passed in XMM regs.
1924 if (RegVT.isVector()) {
1925 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1928 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1931 assert(VA.isMemLoc());
1932 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1935 // If value is passed via pointer - do a load.
1936 if (VA.getLocInfo() == CCValAssign::Indirect)
1937 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1938 MachinePointerInfo(), false, false, false, 0);
1940 InVals.push_back(ArgValue);
1943 // The x86-64 ABI for returning structs by value requires that we copy
1944 // the sret argument into %rax for the return. Save the argument into
1945 // a virtual register so that we can access it from the return points.
1946 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1947 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1948 unsigned Reg = FuncInfo->getSRetReturnReg();
1950 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1951 FuncInfo->setSRetReturnReg(Reg);
1953 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1954 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1957 unsigned StackSize = CCInfo.getNextStackOffset();
1958 // Align stack specially for tail calls.
1959 if (FuncIsMadeTailCallSafe(CallConv,
1960 MF.getTarget().Options.GuaranteedTailCallOpt))
1961 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1963 // If the function takes variable number of arguments, make a frame index for
1964 // the start of the first vararg value... for expansion of llvm.va_start.
1966 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1967 CallConv != CallingConv::X86_ThisCall)) {
1968 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1971 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1973 // FIXME: We should really autogenerate these arrays
1974 static const uint16_t GPR64ArgRegsWin64[] = {
1975 X86::RCX, X86::RDX, X86::R8, X86::R9
1977 static const uint16_t GPR64ArgRegs64Bit[] = {
1978 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1980 static const uint16_t XMMArgRegs64Bit[] = {
1981 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1982 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1984 const uint16_t *GPR64ArgRegs;
1985 unsigned NumXMMRegs = 0;
1988 // The XMM registers which might contain var arg parameters are shadowed
1989 // in their paired GPR. So we only need to save the GPR to their home
1991 TotalNumIntRegs = 4;
1992 GPR64ArgRegs = GPR64ArgRegsWin64;
1994 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1995 GPR64ArgRegs = GPR64ArgRegs64Bit;
1997 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2000 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2003 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2004 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2005 "SSE register cannot be used when SSE is disabled!");
2006 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2007 NoImplicitFloatOps) &&
2008 "SSE register cannot be used when SSE is disabled!");
2009 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2010 !Subtarget->hasSSE1())
2011 // Kernel mode asks for SSE to be disabled, so don't push them
2013 TotalNumXMMRegs = 0;
2016 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2017 // Get to the caller-allocated home save location. Add 8 to account
2018 // for the return address.
2019 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2020 FuncInfo->setRegSaveFrameIndex(
2021 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2022 // Fixup to set vararg frame on shadow area (4 x i64).
2024 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2026 // For X86-64, if there are vararg parameters that are passed via
2027 // registers, then we must store them to their spots on the stack so
2028 // they may be loaded by deferencing the result of va_next.
2029 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2030 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2031 FuncInfo->setRegSaveFrameIndex(
2032 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2036 // Store the integer parameter registers.
2037 SmallVector<SDValue, 8> MemOps;
2038 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2040 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2041 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2042 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2043 DAG.getIntPtrConstant(Offset));
2044 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2045 &X86::GR64RegClass);
2046 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2048 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2049 MachinePointerInfo::getFixedStack(
2050 FuncInfo->getRegSaveFrameIndex(), Offset),
2052 MemOps.push_back(Store);
2056 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2057 // Now store the XMM (fp + vector) parameter registers.
2058 SmallVector<SDValue, 11> SaveXMMOps;
2059 SaveXMMOps.push_back(Chain);
2061 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2062 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2063 SaveXMMOps.push_back(ALVal);
2065 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2066 FuncInfo->getRegSaveFrameIndex()));
2067 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2068 FuncInfo->getVarArgsFPOffset()));
2070 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2071 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2072 &X86::VR128RegClass);
2073 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2074 SaveXMMOps.push_back(Val);
2076 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2078 &SaveXMMOps[0], SaveXMMOps.size()));
2081 if (!MemOps.empty())
2082 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2083 &MemOps[0], MemOps.size());
2087 // Some CCs need callee pop.
2088 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2089 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2090 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2092 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2093 // If this is an sret function, the return should pop the hidden pointer.
2094 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2095 argsAreStructReturn(Ins) == StackStructReturn)
2096 FuncInfo->setBytesToPopOnReturn(4);
2100 // RegSaveFrameIndex is X86-64 only.
2101 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2102 if (CallConv == CallingConv::X86_FastCall ||
2103 CallConv == CallingConv::X86_ThisCall)
2104 // fastcc functions can't have varargs.
2105 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2108 FuncInfo->setArgumentStackSize(StackSize);
2114 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2115 SDValue StackPtr, SDValue Arg,
2116 DebugLoc dl, SelectionDAG &DAG,
2117 const CCValAssign &VA,
2118 ISD::ArgFlagsTy Flags) const {
2119 unsigned LocMemOffset = VA.getLocMemOffset();
2120 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2121 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2122 if (Flags.isByVal())
2123 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2125 return DAG.getStore(Chain, dl, Arg, PtrOff,
2126 MachinePointerInfo::getStack(LocMemOffset),
2130 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2131 /// optimization is performed and it is required.
2133 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2134 SDValue &OutRetAddr, SDValue Chain,
2135 bool IsTailCall, bool Is64Bit,
2136 int FPDiff, DebugLoc dl) const {
2137 // Adjust the Return address stack slot.
2138 EVT VT = getPointerTy();
2139 OutRetAddr = getReturnAddressFrameIndex(DAG);
2141 // Load the "old" Return address.
2142 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2143 false, false, false, 0);
2144 return SDValue(OutRetAddr.getNode(), 1);
2147 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2148 /// optimization is performed and it is required (FPDiff!=0).
2150 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2151 SDValue Chain, SDValue RetAddrFrIdx,
2152 bool Is64Bit, int FPDiff, DebugLoc dl) {
2153 // Store the return address to the appropriate stack slot.
2154 if (!FPDiff) return Chain;
2155 // Calculate the new stack slot for the return address.
2156 int SlotSize = Is64Bit ? 8 : 4;
2157 int NewReturnAddrFI =
2158 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2159 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2160 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2161 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2162 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2168 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2169 SmallVectorImpl<SDValue> &InVals) const {
2170 SelectionDAG &DAG = CLI.DAG;
2171 DebugLoc &dl = CLI.DL;
2172 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2173 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2174 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2175 SDValue Chain = CLI.Chain;
2176 SDValue Callee = CLI.Callee;
2177 CallingConv::ID CallConv = CLI.CallConv;
2178 bool &isTailCall = CLI.IsTailCall;
2179 bool isVarArg = CLI.IsVarArg;
2181 MachineFunction &MF = DAG.getMachineFunction();
2182 bool Is64Bit = Subtarget->is64Bit();
2183 bool IsWin64 = Subtarget->isTargetWin64();
2184 bool IsWindows = Subtarget->isTargetWindows();
2185 StructReturnType SR = callIsStructReturn(Outs);
2186 bool IsSibcall = false;
2188 if (MF.getTarget().Options.DisableTailCalls)
2192 // Check if it's really possible to do a tail call.
2193 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2194 isVarArg, SR != NotStructReturn,
2195 MF.getFunction()->hasStructRetAttr(),
2196 Outs, OutVals, Ins, DAG);
2198 // Sibcalls are automatically detected tailcalls which do not require
2200 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2207 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2208 "Var args not supported with calling convention fastcc or ghc");
2210 // Analyze operands of the call, assigning locations to each operand.
2211 SmallVector<CCValAssign, 16> ArgLocs;
2212 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2213 ArgLocs, *DAG.getContext());
2215 // Allocate shadow area for Win64
2217 CCInfo.AllocateStack(32, 8);
2220 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2222 // Get a count of how many bytes are to be pushed on the stack.
2223 unsigned NumBytes = CCInfo.getNextStackOffset();
2225 // This is a sibcall. The memory operands are available in caller's
2226 // own caller's stack.
2228 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2229 IsTailCallConvention(CallConv))
2230 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2233 if (isTailCall && !IsSibcall) {
2234 // Lower arguments at fp - stackoffset + fpdiff.
2235 unsigned NumBytesCallerPushed =
2236 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2237 FPDiff = NumBytesCallerPushed - NumBytes;
2239 // Set the delta of movement of the returnaddr stackslot.
2240 // But only set if delta is greater than previous delta.
2241 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2242 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2246 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2248 SDValue RetAddrFrIdx;
2249 // Load return address for tail calls.
2250 if (isTailCall && FPDiff)
2251 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2252 Is64Bit, FPDiff, dl);
2254 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2255 SmallVector<SDValue, 8> MemOpChains;
2258 // Walk the register/memloc assignments, inserting copies/loads. In the case
2259 // of tail call optimization arguments are handle later.
2260 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2261 CCValAssign &VA = ArgLocs[i];
2262 EVT RegVT = VA.getLocVT();
2263 SDValue Arg = OutVals[i];
2264 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2265 bool isByVal = Flags.isByVal();
2267 // Promote the value if needed.
2268 switch (VA.getLocInfo()) {
2269 default: llvm_unreachable("Unknown loc info!");
2270 case CCValAssign::Full: break;
2271 case CCValAssign::SExt:
2272 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2274 case CCValAssign::ZExt:
2275 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2277 case CCValAssign::AExt:
2278 if (RegVT.is128BitVector()) {
2279 // Special case: passing MMX values in XMM registers.
2280 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2281 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2282 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2284 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2286 case CCValAssign::BCvt:
2287 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2289 case CCValAssign::Indirect: {
2290 // Store the argument.
2291 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2292 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2293 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2294 MachinePointerInfo::getFixedStack(FI),
2301 if (VA.isRegLoc()) {
2302 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2303 if (isVarArg && IsWin64) {
2304 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2305 // shadow reg if callee is a varargs function.
2306 unsigned ShadowReg = 0;
2307 switch (VA.getLocReg()) {
2308 case X86::XMM0: ShadowReg = X86::RCX; break;
2309 case X86::XMM1: ShadowReg = X86::RDX; break;
2310 case X86::XMM2: ShadowReg = X86::R8; break;
2311 case X86::XMM3: ShadowReg = X86::R9; break;
2314 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2316 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2317 assert(VA.isMemLoc());
2318 if (StackPtr.getNode() == 0)
2319 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2320 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2321 dl, DAG, VA, Flags));
2325 if (!MemOpChains.empty())
2326 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2327 &MemOpChains[0], MemOpChains.size());
2329 if (Subtarget->isPICStyleGOT()) {
2330 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2333 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2334 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2336 // If we are tail calling and generating PIC/GOT style code load the
2337 // address of the callee into ECX. The value in ecx is used as target of
2338 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2339 // for tail calls on PIC/GOT architectures. Normally we would just put the
2340 // address of GOT into ebx and then call target@PLT. But for tail calls
2341 // ebx would be restored (since ebx is callee saved) before jumping to the
2344 // Note: The actual moving to ECX is done further down.
2345 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2346 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2347 !G->getGlobal()->hasProtectedVisibility())
2348 Callee = LowerGlobalAddress(Callee, DAG);
2349 else if (isa<ExternalSymbolSDNode>(Callee))
2350 Callee = LowerExternalSymbol(Callee, DAG);
2354 if (Is64Bit && isVarArg && !IsWin64) {
2355 // From AMD64 ABI document:
2356 // For calls that may call functions that use varargs or stdargs
2357 // (prototype-less calls or calls to functions containing ellipsis (...) in
2358 // the declaration) %al is used as hidden argument to specify the number
2359 // of SSE registers used. The contents of %al do not need to match exactly
2360 // the number of registers, but must be an ubound on the number of SSE
2361 // registers used and is in the range 0 - 8 inclusive.
2363 // Count the number of XMM registers allocated.
2364 static const uint16_t XMMArgRegs[] = {
2365 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2366 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2368 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2369 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2370 && "SSE registers cannot be used when SSE is disabled");
2372 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2373 DAG.getConstant(NumXMMRegs, MVT::i8)));
2376 // For tail calls lower the arguments to the 'real' stack slot.
2378 // Force all the incoming stack arguments to be loaded from the stack
2379 // before any new outgoing arguments are stored to the stack, because the
2380 // outgoing stack slots may alias the incoming argument stack slots, and
2381 // the alias isn't otherwise explicit. This is slightly more conservative
2382 // than necessary, because it means that each store effectively depends
2383 // on every argument instead of just those arguments it would clobber.
2384 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2386 SmallVector<SDValue, 8> MemOpChains2;
2389 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2390 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2391 CCValAssign &VA = ArgLocs[i];
2394 assert(VA.isMemLoc());
2395 SDValue Arg = OutVals[i];
2396 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2397 // Create frame index.
2398 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2399 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2400 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2401 FIN = DAG.getFrameIndex(FI, getPointerTy());
2403 if (Flags.isByVal()) {
2404 // Copy relative to framepointer.
2405 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2406 if (StackPtr.getNode() == 0)
2407 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2409 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2411 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2415 // Store relative to framepointer.
2416 MemOpChains2.push_back(
2417 DAG.getStore(ArgChain, dl, Arg, FIN,
2418 MachinePointerInfo::getFixedStack(FI),
2424 if (!MemOpChains2.empty())
2425 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2426 &MemOpChains2[0], MemOpChains2.size());
2428 // Store the return address to the appropriate stack slot.
2429 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2433 // Build a sequence of copy-to-reg nodes chained together with token chain
2434 // and flag operands which copy the outgoing args into registers.
2436 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2437 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2438 RegsToPass[i].second, InFlag);
2439 InFlag = Chain.getValue(1);
2442 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2443 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2444 // In the 64-bit large code model, we have to make all calls
2445 // through a register, since the call instruction's 32-bit
2446 // pc-relative offset may not be large enough to hold the whole
2448 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2449 // If the callee is a GlobalAddress node (quite common, every direct call
2450 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2453 // We should use extra load for direct calls to dllimported functions in
2455 const GlobalValue *GV = G->getGlobal();
2456 if (!GV->hasDLLImportLinkage()) {
2457 unsigned char OpFlags = 0;
2458 bool ExtraLoad = false;
2459 unsigned WrapperKind = ISD::DELETED_NODE;
2461 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2462 // external symbols most go through the PLT in PIC mode. If the symbol
2463 // has hidden or protected visibility, or if it is static or local, then
2464 // we don't need to use the PLT - we can directly call it.
2465 if (Subtarget->isTargetELF() &&
2466 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2467 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2468 OpFlags = X86II::MO_PLT;
2469 } else if (Subtarget->isPICStyleStubAny() &&
2470 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2471 (!Subtarget->getTargetTriple().isMacOSX() ||
2472 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2473 // PC-relative references to external symbols should go through $stub,
2474 // unless we're building with the leopard linker or later, which
2475 // automatically synthesizes these stubs.
2476 OpFlags = X86II::MO_DARWIN_STUB;
2477 } else if (Subtarget->isPICStyleRIPRel() &&
2478 isa<Function>(GV) &&
2479 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2480 // If the function is marked as non-lazy, generate an indirect call
2481 // which loads from the GOT directly. This avoids runtime overhead
2482 // at the cost of eager binding (and one extra byte of encoding).
2483 OpFlags = X86II::MO_GOTPCREL;
2484 WrapperKind = X86ISD::WrapperRIP;
2488 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2489 G->getOffset(), OpFlags);
2491 // Add a wrapper if needed.
2492 if (WrapperKind != ISD::DELETED_NODE)
2493 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2494 // Add extra indirection if needed.
2496 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2497 MachinePointerInfo::getGOT(),
2498 false, false, false, 0);
2500 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2501 unsigned char OpFlags = 0;
2503 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2504 // external symbols should go through the PLT.
2505 if (Subtarget->isTargetELF() &&
2506 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2507 OpFlags = X86II::MO_PLT;
2508 } else if (Subtarget->isPICStyleStubAny() &&
2509 (!Subtarget->getTargetTriple().isMacOSX() ||
2510 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2511 // PC-relative references to external symbols should go through $stub,
2512 // unless we're building with the leopard linker or later, which
2513 // automatically synthesizes these stubs.
2514 OpFlags = X86II::MO_DARWIN_STUB;
2517 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2521 // Returns a chain & a flag for retval copy to use.
2522 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2523 SmallVector<SDValue, 8> Ops;
2525 if (!IsSibcall && isTailCall) {
2526 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2527 DAG.getIntPtrConstant(0, true), InFlag);
2528 InFlag = Chain.getValue(1);
2531 Ops.push_back(Chain);
2532 Ops.push_back(Callee);
2535 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2537 // Add argument registers to the end of the list so that they are known live
2539 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2540 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2541 RegsToPass[i].second.getValueType()));
2543 // Add a register mask operand representing the call-preserved registers.
2544 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2545 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2546 assert(Mask && "Missing call preserved mask for calling convention");
2547 Ops.push_back(DAG.getRegisterMask(Mask));
2549 if (InFlag.getNode())
2550 Ops.push_back(InFlag);
2554 //// If this is the first return lowered for this function, add the regs
2555 //// to the liveout set for the function.
2556 // This isn't right, although it's probably harmless on x86; liveouts
2557 // should be computed from returns not tail calls. Consider a void
2558 // function making a tail call to a function returning int.
2559 return DAG.getNode(X86ISD::TC_RETURN, dl,
2560 NodeTys, &Ops[0], Ops.size());
2563 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2564 InFlag = Chain.getValue(1);
2566 // Create the CALLSEQ_END node.
2567 unsigned NumBytesForCalleeToPush;
2568 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2569 getTargetMachine().Options.GuaranteedTailCallOpt))
2570 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2571 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2572 SR == StackStructReturn)
2573 // If this is a call to a struct-return function, the callee
2574 // pops the hidden struct pointer, so we have to push it back.
2575 // This is common for Darwin/X86, Linux & Mingw32 targets.
2576 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2577 NumBytesForCalleeToPush = 4;
2579 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2581 // Returns a flag for retval copy to use.
2583 Chain = DAG.getCALLSEQ_END(Chain,
2584 DAG.getIntPtrConstant(NumBytes, true),
2585 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2588 InFlag = Chain.getValue(1);
2591 // Handle result values, copying them out of physregs into vregs that we
2593 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2594 Ins, dl, DAG, InVals);
2598 //===----------------------------------------------------------------------===//
2599 // Fast Calling Convention (tail call) implementation
2600 //===----------------------------------------------------------------------===//
2602 // Like std call, callee cleans arguments, convention except that ECX is
2603 // reserved for storing the tail called function address. Only 2 registers are
2604 // free for argument passing (inreg). Tail call optimization is performed
2606 // * tailcallopt is enabled
2607 // * caller/callee are fastcc
2608 // On X86_64 architecture with GOT-style position independent code only local
2609 // (within module) calls are supported at the moment.
2610 // To keep the stack aligned according to platform abi the function
2611 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2612 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2613 // If a tail called function callee has more arguments than the caller the
2614 // caller needs to make sure that there is room to move the RETADDR to. This is
2615 // achieved by reserving an area the size of the argument delta right after the
2616 // original REtADDR, but before the saved framepointer or the spilled registers
2617 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2629 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2630 /// for a 16 byte align requirement.
2632 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2633 SelectionDAG& DAG) const {
2634 MachineFunction &MF = DAG.getMachineFunction();
2635 const TargetMachine &TM = MF.getTarget();
2636 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2637 unsigned StackAlignment = TFI.getStackAlignment();
2638 uint64_t AlignMask = StackAlignment - 1;
2639 int64_t Offset = StackSize;
2640 uint64_t SlotSize = TD->getPointerSize();
2641 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2642 // Number smaller than 12 so just add the difference.
2643 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2645 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2646 Offset = ((~AlignMask) & Offset) + StackAlignment +
2647 (StackAlignment-SlotSize);
2652 /// MatchingStackOffset - Return true if the given stack call argument is
2653 /// already available in the same position (relatively) of the caller's
2654 /// incoming argument stack.
2656 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2657 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2658 const X86InstrInfo *TII) {
2659 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2661 if (Arg.getOpcode() == ISD::CopyFromReg) {
2662 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2663 if (!TargetRegisterInfo::isVirtualRegister(VR))
2665 MachineInstr *Def = MRI->getVRegDef(VR);
2668 if (!Flags.isByVal()) {
2669 if (!TII->isLoadFromStackSlot(Def, FI))
2672 unsigned Opcode = Def->getOpcode();
2673 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2674 Def->getOperand(1).isFI()) {
2675 FI = Def->getOperand(1).getIndex();
2676 Bytes = Flags.getByValSize();
2680 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2681 if (Flags.isByVal())
2682 // ByVal argument is passed in as a pointer but it's now being
2683 // dereferenced. e.g.
2684 // define @foo(%struct.X* %A) {
2685 // tail call @bar(%struct.X* byval %A)
2688 SDValue Ptr = Ld->getBasePtr();
2689 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2692 FI = FINode->getIndex();
2693 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2694 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2695 FI = FINode->getIndex();
2696 Bytes = Flags.getByValSize();
2700 assert(FI != INT_MAX);
2701 if (!MFI->isFixedObjectIndex(FI))
2703 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2706 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2707 /// for tail call optimization. Targets which want to do tail call
2708 /// optimization should implement this function.
2710 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2711 CallingConv::ID CalleeCC,
2713 bool isCalleeStructRet,
2714 bool isCallerStructRet,
2715 const SmallVectorImpl<ISD::OutputArg> &Outs,
2716 const SmallVectorImpl<SDValue> &OutVals,
2717 const SmallVectorImpl<ISD::InputArg> &Ins,
2718 SelectionDAG& DAG) const {
2719 if (!IsTailCallConvention(CalleeCC) &&
2720 CalleeCC != CallingConv::C)
2723 // If -tailcallopt is specified, make fastcc functions tail-callable.
2724 const MachineFunction &MF = DAG.getMachineFunction();
2725 const Function *CallerF = DAG.getMachineFunction().getFunction();
2726 CallingConv::ID CallerCC = CallerF->getCallingConv();
2727 bool CCMatch = CallerCC == CalleeCC;
2729 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2730 if (IsTailCallConvention(CalleeCC) && CCMatch)
2735 // Look for obvious safe cases to perform tail call optimization that do not
2736 // require ABI changes. This is what gcc calls sibcall.
2738 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2739 // emit a special epilogue.
2740 if (RegInfo->needsStackRealignment(MF))
2743 // Also avoid sibcall optimization if either caller or callee uses struct
2744 // return semantics.
2745 if (isCalleeStructRet || isCallerStructRet)
2748 // An stdcall caller is expected to clean up its arguments; the callee
2749 // isn't going to do that.
2750 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2753 // Do not sibcall optimize vararg calls unless all arguments are passed via
2755 if (isVarArg && !Outs.empty()) {
2757 // Optimizing for varargs on Win64 is unlikely to be safe without
2758 // additional testing.
2759 if (Subtarget->isTargetWin64())
2762 SmallVector<CCValAssign, 16> ArgLocs;
2763 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2764 getTargetMachine(), ArgLocs, *DAG.getContext());
2766 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2767 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2768 if (!ArgLocs[i].isRegLoc())
2772 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2773 // stack. Therefore, if it's not used by the call it is not safe to optimize
2774 // this into a sibcall.
2775 bool Unused = false;
2776 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2783 SmallVector<CCValAssign, 16> RVLocs;
2784 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2785 getTargetMachine(), RVLocs, *DAG.getContext());
2786 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2787 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2788 CCValAssign &VA = RVLocs[i];
2789 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2794 // If the calling conventions do not match, then we'd better make sure the
2795 // results are returned in the same way as what the caller expects.
2797 SmallVector<CCValAssign, 16> RVLocs1;
2798 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2799 getTargetMachine(), RVLocs1, *DAG.getContext());
2800 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2802 SmallVector<CCValAssign, 16> RVLocs2;
2803 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2804 getTargetMachine(), RVLocs2, *DAG.getContext());
2805 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2807 if (RVLocs1.size() != RVLocs2.size())
2809 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2810 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2812 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2814 if (RVLocs1[i].isRegLoc()) {
2815 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2818 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2824 // If the callee takes no arguments then go on to check the results of the
2826 if (!Outs.empty()) {
2827 // Check if stack adjustment is needed. For now, do not do this if any
2828 // argument is passed on the stack.
2829 SmallVector<CCValAssign, 16> ArgLocs;
2830 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2831 getTargetMachine(), ArgLocs, *DAG.getContext());
2833 // Allocate shadow area for Win64
2834 if (Subtarget->isTargetWin64()) {
2835 CCInfo.AllocateStack(32, 8);
2838 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2839 if (CCInfo.getNextStackOffset()) {
2840 MachineFunction &MF = DAG.getMachineFunction();
2841 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2844 // Check if the arguments are already laid out in the right way as
2845 // the caller's fixed stack objects.
2846 MachineFrameInfo *MFI = MF.getFrameInfo();
2847 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2848 const X86InstrInfo *TII =
2849 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2850 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2851 CCValAssign &VA = ArgLocs[i];
2852 SDValue Arg = OutVals[i];
2853 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2854 if (VA.getLocInfo() == CCValAssign::Indirect)
2856 if (!VA.isRegLoc()) {
2857 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2864 // If the tailcall address may be in a register, then make sure it's
2865 // possible to register allocate for it. In 32-bit, the call address can
2866 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2867 // callee-saved registers are restored. These happen to be the same
2868 // registers used to pass 'inreg' arguments so watch out for those.
2869 if (!Subtarget->is64Bit() &&
2870 !isa<GlobalAddressSDNode>(Callee) &&
2871 !isa<ExternalSymbolSDNode>(Callee)) {
2872 unsigned NumInRegs = 0;
2873 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2874 CCValAssign &VA = ArgLocs[i];
2877 unsigned Reg = VA.getLocReg();
2880 case X86::EAX: case X86::EDX: case X86::ECX:
2881 if (++NumInRegs == 3)
2893 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2894 const TargetLibraryInfo *libInfo) const {
2895 return X86::createFastISel(funcInfo, libInfo);
2899 //===----------------------------------------------------------------------===//
2900 // Other Lowering Hooks
2901 //===----------------------------------------------------------------------===//
2903 static bool MayFoldLoad(SDValue Op) {
2904 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2907 static bool MayFoldIntoStore(SDValue Op) {
2908 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2911 static bool isTargetShuffle(unsigned Opcode) {
2913 default: return false;
2914 case X86ISD::PSHUFD:
2915 case X86ISD::PSHUFHW:
2916 case X86ISD::PSHUFLW:
2918 case X86ISD::PALIGN:
2919 case X86ISD::MOVLHPS:
2920 case X86ISD::MOVLHPD:
2921 case X86ISD::MOVHLPS:
2922 case X86ISD::MOVLPS:
2923 case X86ISD::MOVLPD:
2924 case X86ISD::MOVSHDUP:
2925 case X86ISD::MOVSLDUP:
2926 case X86ISD::MOVDDUP:
2929 case X86ISD::UNPCKL:
2930 case X86ISD::UNPCKH:
2931 case X86ISD::VPERMILP:
2932 case X86ISD::VPERM2X128:
2933 case X86ISD::VPERMI:
2938 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2939 SDValue V1, SelectionDAG &DAG) {
2941 default: llvm_unreachable("Unknown x86 shuffle node");
2942 case X86ISD::MOVSHDUP:
2943 case X86ISD::MOVSLDUP:
2944 case X86ISD::MOVDDUP:
2945 return DAG.getNode(Opc, dl, VT, V1);
2949 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2950 SDValue V1, unsigned TargetMask,
2951 SelectionDAG &DAG) {
2953 default: llvm_unreachable("Unknown x86 shuffle node");
2954 case X86ISD::PSHUFD:
2955 case X86ISD::PSHUFHW:
2956 case X86ISD::PSHUFLW:
2957 case X86ISD::VPERMILP:
2958 case X86ISD::VPERMI:
2959 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2963 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2964 SDValue V1, SDValue V2, unsigned TargetMask,
2965 SelectionDAG &DAG) {
2967 default: llvm_unreachable("Unknown x86 shuffle node");
2968 case X86ISD::PALIGN:
2970 case X86ISD::VPERM2X128:
2971 return DAG.getNode(Opc, dl, VT, V1, V2,
2972 DAG.getConstant(TargetMask, MVT::i8));
2976 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2977 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2979 default: llvm_unreachable("Unknown x86 shuffle node");
2980 case X86ISD::MOVLHPS:
2981 case X86ISD::MOVLHPD:
2982 case X86ISD::MOVHLPS:
2983 case X86ISD::MOVLPS:
2984 case X86ISD::MOVLPD:
2987 case X86ISD::UNPCKL:
2988 case X86ISD::UNPCKH:
2989 return DAG.getNode(Opc, dl, VT, V1, V2);
2993 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2994 MachineFunction &MF = DAG.getMachineFunction();
2995 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2996 int ReturnAddrIndex = FuncInfo->getRAIndex();
2998 if (ReturnAddrIndex == 0) {
2999 // Set up a frame object for the return address.
3000 uint64_t SlotSize = TD->getPointerSize();
3001 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3003 FuncInfo->setRAIndex(ReturnAddrIndex);
3006 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3010 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3011 bool hasSymbolicDisplacement) {
3012 // Offset should fit into 32 bit immediate field.
3013 if (!isInt<32>(Offset))
3016 // If we don't have a symbolic displacement - we don't have any extra
3018 if (!hasSymbolicDisplacement)
3021 // FIXME: Some tweaks might be needed for medium code model.
3022 if (M != CodeModel::Small && M != CodeModel::Kernel)
3025 // For small code model we assume that latest object is 16MB before end of 31
3026 // bits boundary. We may also accept pretty large negative constants knowing
3027 // that all objects are in the positive half of address space.
3028 if (M == CodeModel::Small && Offset < 16*1024*1024)
3031 // For kernel code model we know that all object resist in the negative half
3032 // of 32bits address space. We may not accept negative offsets, since they may
3033 // be just off and we may accept pretty large positive ones.
3034 if (M == CodeModel::Kernel && Offset > 0)
3040 /// isCalleePop - Determines whether the callee is required to pop its
3041 /// own arguments. Callee pop is necessary to support tail calls.
3042 bool X86::isCalleePop(CallingConv::ID CallingConv,
3043 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3047 switch (CallingConv) {
3050 case CallingConv::X86_StdCall:
3052 case CallingConv::X86_FastCall:
3054 case CallingConv::X86_ThisCall:
3056 case CallingConv::Fast:
3058 case CallingConv::GHC:
3063 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3064 /// specific condition code, returning the condition code and the LHS/RHS of the
3065 /// comparison to make.
3066 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3067 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3069 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3070 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3071 // X > -1 -> X == 0, jump !sign.
3072 RHS = DAG.getConstant(0, RHS.getValueType());
3073 return X86::COND_NS;
3075 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3076 // X < 0 -> X == 0, jump on sign.
3079 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3081 RHS = DAG.getConstant(0, RHS.getValueType());
3082 return X86::COND_LE;
3086 switch (SetCCOpcode) {
3087 default: llvm_unreachable("Invalid integer condition!");
3088 case ISD::SETEQ: return X86::COND_E;
3089 case ISD::SETGT: return X86::COND_G;
3090 case ISD::SETGE: return X86::COND_GE;
3091 case ISD::SETLT: return X86::COND_L;
3092 case ISD::SETLE: return X86::COND_LE;
3093 case ISD::SETNE: return X86::COND_NE;
3094 case ISD::SETULT: return X86::COND_B;
3095 case ISD::SETUGT: return X86::COND_A;
3096 case ISD::SETULE: return X86::COND_BE;
3097 case ISD::SETUGE: return X86::COND_AE;
3101 // First determine if it is required or is profitable to flip the operands.
3103 // If LHS is a foldable load, but RHS is not, flip the condition.
3104 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3105 !ISD::isNON_EXTLoad(RHS.getNode())) {
3106 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3107 std::swap(LHS, RHS);
3110 switch (SetCCOpcode) {
3116 std::swap(LHS, RHS);
3120 // On a floating point condition, the flags are set as follows:
3122 // 0 | 0 | 0 | X > Y
3123 // 0 | 0 | 1 | X < Y
3124 // 1 | 0 | 0 | X == Y
3125 // 1 | 1 | 1 | unordered
3126 switch (SetCCOpcode) {
3127 default: llvm_unreachable("Condcode should be pre-legalized away");
3129 case ISD::SETEQ: return X86::COND_E;
3130 case ISD::SETOLT: // flipped
3132 case ISD::SETGT: return X86::COND_A;
3133 case ISD::SETOLE: // flipped
3135 case ISD::SETGE: return X86::COND_AE;
3136 case ISD::SETUGT: // flipped
3138 case ISD::SETLT: return X86::COND_B;
3139 case ISD::SETUGE: // flipped
3141 case ISD::SETLE: return X86::COND_BE;
3143 case ISD::SETNE: return X86::COND_NE;
3144 case ISD::SETUO: return X86::COND_P;
3145 case ISD::SETO: return X86::COND_NP;
3147 case ISD::SETUNE: return X86::COND_INVALID;
3151 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3152 /// code. Current x86 isa includes the following FP cmov instructions:
3153 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3154 static bool hasFPCMov(unsigned X86CC) {
3170 /// isFPImmLegal - Returns true if the target can instruction select the
3171 /// specified FP immediate natively. If false, the legalizer will
3172 /// materialize the FP immediate as a load from a constant pool.
3173 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3174 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3175 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3181 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3182 /// the specified range (L, H].
3183 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3184 return (Val < 0) || (Val >= Low && Val < Hi);
3187 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3188 /// specified value.
3189 static bool isUndefOrEqual(int Val, int CmpVal) {
3190 if (Val < 0 || Val == CmpVal)
3195 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3196 /// from position Pos and ending in Pos+Size, falls within the specified
3197 /// sequential range (L, L+Pos]. or is undef.
3198 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3199 unsigned Pos, unsigned Size, int Low) {
3200 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3201 if (!isUndefOrEqual(Mask[i], Low))
3206 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3207 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3208 /// the second operand.
3209 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3210 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3211 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3212 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3213 return (Mask[0] < 2 && Mask[1] < 2);
3217 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3218 /// is suitable for input to PSHUFHW.
3219 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3220 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3223 // Lower quadword copied in order or undef.
3224 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3227 // Upper quadword shuffled.
3228 for (unsigned i = 4; i != 8; ++i)
3229 if (!isUndefOrInRange(Mask[i], 4, 8))
3232 if (VT == MVT::v16i16) {
3233 // Lower quadword copied in order or undef.
3234 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3237 // Upper quadword shuffled.
3238 for (unsigned i = 12; i != 16; ++i)
3239 if (!isUndefOrInRange(Mask[i], 12, 16))
3246 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3247 /// is suitable for input to PSHUFLW.
3248 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3249 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3252 // Upper quadword copied in order.
3253 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3256 // Lower quadword shuffled.
3257 for (unsigned i = 0; i != 4; ++i)
3258 if (!isUndefOrInRange(Mask[i], 0, 4))
3261 if (VT == MVT::v16i16) {
3262 // Upper quadword copied in order.
3263 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3266 // Lower quadword shuffled.
3267 for (unsigned i = 8; i != 12; ++i)
3268 if (!isUndefOrInRange(Mask[i], 8, 12))
3275 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3276 /// is suitable for input to PALIGNR.
3277 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3278 const X86Subtarget *Subtarget) {
3279 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3280 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3283 unsigned NumElts = VT.getVectorNumElements();
3284 unsigned NumLanes = VT.getSizeInBits()/128;
3285 unsigned NumLaneElts = NumElts/NumLanes;
3287 // Do not handle 64-bit element shuffles with palignr.
3288 if (NumLaneElts == 2)
3291 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3293 for (i = 0; i != NumLaneElts; ++i) {
3298 // Lane is all undef, go to next lane
3299 if (i == NumLaneElts)
3302 int Start = Mask[i+l];
3304 // Make sure its in this lane in one of the sources
3305 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3306 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3309 // If not lane 0, then we must match lane 0
3310 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3313 // Correct second source to be contiguous with first source
3314 if (Start >= (int)NumElts)
3315 Start -= NumElts - NumLaneElts;
3317 // Make sure we're shifting in the right direction.
3318 if (Start <= (int)(i+l))
3323 // Check the rest of the elements to see if they are consecutive.
3324 for (++i; i != NumLaneElts; ++i) {
3325 int Idx = Mask[i+l];
3327 // Make sure its in this lane
3328 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3329 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3332 // If not lane 0, then we must match lane 0
3333 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3336 if (Idx >= (int)NumElts)
3337 Idx -= NumElts - NumLaneElts;
3339 if (!isUndefOrEqual(Idx, Start+i))
3348 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3349 /// the two vector operands have swapped position.
3350 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3351 unsigned NumElems) {
3352 for (unsigned i = 0; i != NumElems; ++i) {
3356 else if (idx < (int)NumElems)
3357 Mask[i] = idx + NumElems;
3359 Mask[i] = idx - NumElems;
3363 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3364 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3365 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3366 /// reverse of what x86 shuffles want.
3367 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3368 bool Commuted = false) {
3369 if (!HasAVX && VT.getSizeInBits() == 256)
3372 unsigned NumElems = VT.getVectorNumElements();
3373 unsigned NumLanes = VT.getSizeInBits()/128;
3374 unsigned NumLaneElems = NumElems/NumLanes;
3376 if (NumLaneElems != 2 && NumLaneElems != 4)
3379 // VSHUFPSY 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 => X7 X6 X5 X4 X3 X2 X1 X0
3384 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3386 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3387 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3389 // VSHUFPDY divides the resulting vector into 4 chunks.
3390 // The sources are also splitted into 4 chunks, and each destination
3391 // chunk must come from a different source chunk.
3393 // SRC1 => X3 X2 X1 X0
3394 // SRC2 => Y3 Y2 Y1 Y0
3396 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3398 unsigned HalfLaneElems = NumLaneElems/2;
3399 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3400 for (unsigned i = 0; i != NumLaneElems; ++i) {
3401 int Idx = Mask[i+l];
3402 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3403 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3405 // For VSHUFPSY, the mask of the second half must be the same as the
3406 // first but with the appropriate offsets. This works in the same way as
3407 // VPERMILPS works with masks.
3408 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3410 if (!isUndefOrEqual(Idx, Mask[i]+l))
3418 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3419 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3420 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3421 if (!VT.is128BitVector())
3424 unsigned NumElems = VT.getVectorNumElements();
3429 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3430 return isUndefOrEqual(Mask[0], 6) &&
3431 isUndefOrEqual(Mask[1], 7) &&
3432 isUndefOrEqual(Mask[2], 2) &&
3433 isUndefOrEqual(Mask[3], 3);
3436 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3437 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3439 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3440 if (!VT.is128BitVector())
3443 unsigned NumElems = VT.getVectorNumElements();
3448 return isUndefOrEqual(Mask[0], 2) &&
3449 isUndefOrEqual(Mask[1], 3) &&
3450 isUndefOrEqual(Mask[2], 2) &&
3451 isUndefOrEqual(Mask[3], 3);
3454 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3455 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3456 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3457 if (!VT.is128BitVector())
3460 unsigned NumElems = VT.getVectorNumElements();
3462 if (NumElems != 2 && NumElems != 4)
3465 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3466 if (!isUndefOrEqual(Mask[i], i + NumElems))
3469 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3470 if (!isUndefOrEqual(Mask[i], i))
3476 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3477 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3478 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3479 if (!VT.is128BitVector())
3482 unsigned NumElems = VT.getVectorNumElements();
3484 if (NumElems != 2 && NumElems != 4)
3487 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3488 if (!isUndefOrEqual(Mask[i], i))
3491 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3492 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3499 // Some special combinations that can be optimized.
3502 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3503 SelectionDAG &DAG) {
3504 EVT VT = SVOp->getValueType(0);
3505 DebugLoc dl = SVOp->getDebugLoc();
3507 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3510 ArrayRef<int> Mask = SVOp->getMask();
3512 // These are the special masks that may be optimized.
3513 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3514 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3515 bool MatchEvenMask = true;
3516 bool MatchOddMask = true;
3517 for (int i=0; i<8; ++i) {
3518 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3519 MatchEvenMask = false;
3520 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3521 MatchOddMask = false;
3524 if (!MatchEvenMask && !MatchOddMask)
3527 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3529 SDValue Op0 = SVOp->getOperand(0);
3530 SDValue Op1 = SVOp->getOperand(1);
3532 if (MatchEvenMask) {
3533 // Shift the second operand right to 32 bits.
3534 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3535 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3537 // Shift the first operand left to 32 bits.
3538 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3539 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3541 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3542 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3545 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3546 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3547 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3548 bool HasAVX2, bool V2IsSplat = false) {
3549 unsigned NumElts = VT.getVectorNumElements();
3551 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3552 "Unsupported vector type for unpckh");
3554 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3555 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3558 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3559 // independently on 128-bit lanes.
3560 unsigned NumLanes = VT.getSizeInBits()/128;
3561 unsigned NumLaneElts = NumElts/NumLanes;
3563 for (unsigned l = 0; l != NumLanes; ++l) {
3564 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3565 i != (l+1)*NumLaneElts;
3568 int BitI1 = Mask[i+1];
3569 if (!isUndefOrEqual(BitI, j))
3572 if (!isUndefOrEqual(BitI1, NumElts))
3575 if (!isUndefOrEqual(BitI1, j + NumElts))
3584 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3585 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3586 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3587 bool HasAVX2, bool V2IsSplat = false) {
3588 unsigned NumElts = VT.getVectorNumElements();
3590 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3591 "Unsupported vector type for unpckh");
3593 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3594 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3597 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3598 // independently on 128-bit lanes.
3599 unsigned NumLanes = VT.getSizeInBits()/128;
3600 unsigned NumLaneElts = NumElts/NumLanes;
3602 for (unsigned l = 0; l != NumLanes; ++l) {
3603 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3604 i != (l+1)*NumLaneElts; i += 2, ++j) {
3606 int BitI1 = Mask[i+1];
3607 if (!isUndefOrEqual(BitI, j))
3610 if (isUndefOrEqual(BitI1, NumElts))
3613 if (!isUndefOrEqual(BitI1, j+NumElts))
3621 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3622 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3624 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3626 unsigned NumElts = VT.getVectorNumElements();
3628 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3629 "Unsupported vector type for unpckh");
3631 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3632 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3635 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3636 // FIXME: Need a better way to get rid of this, there's no latency difference
3637 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3638 // the former later. We should also remove the "_undef" special mask.
3639 if (NumElts == 4 && VT.getSizeInBits() == 256)
3642 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3643 // independently on 128-bit lanes.
3644 unsigned NumLanes = VT.getSizeInBits()/128;
3645 unsigned NumLaneElts = NumElts/NumLanes;
3647 for (unsigned l = 0; l != NumLanes; ++l) {
3648 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3649 i != (l+1)*NumLaneElts;
3652 int BitI1 = Mask[i+1];
3654 if (!isUndefOrEqual(BitI, j))
3656 if (!isUndefOrEqual(BitI1, j))
3664 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3665 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3667 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3668 unsigned NumElts = VT.getVectorNumElements();
3670 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3671 "Unsupported vector type for unpckh");
3673 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3674 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3677 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3678 // independently on 128-bit lanes.
3679 unsigned NumLanes = VT.getSizeInBits()/128;
3680 unsigned NumLaneElts = NumElts/NumLanes;
3682 for (unsigned l = 0; l != NumLanes; ++l) {
3683 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3684 i != (l+1)*NumLaneElts; i += 2, ++j) {
3686 int BitI1 = Mask[i+1];
3687 if (!isUndefOrEqual(BitI, j))
3689 if (!isUndefOrEqual(BitI1, j))
3696 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3697 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3698 /// MOVSD, and MOVD, i.e. setting the lowest element.
3699 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3700 if (VT.getVectorElementType().getSizeInBits() < 32)
3702 if (!VT.is128BitVector())
3705 unsigned NumElts = VT.getVectorNumElements();
3707 if (!isUndefOrEqual(Mask[0], NumElts))
3710 for (unsigned i = 1; i != NumElts; ++i)
3711 if (!isUndefOrEqual(Mask[i], i))
3717 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3718 /// as permutations between 128-bit chunks or halves. As an example: this
3720 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3721 /// The first half comes from the second half of V1 and the second half from the
3722 /// the second half of V2.
3723 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3724 if (!HasAVX || !VT.is256BitVector())
3727 // The shuffle result is divided into half A and half B. In total the two
3728 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3729 // B must come from C, D, E or F.
3730 unsigned HalfSize = VT.getVectorNumElements()/2;
3731 bool MatchA = false, MatchB = false;
3733 // Check if A comes from one of C, D, E, F.
3734 for (unsigned Half = 0; Half != 4; ++Half) {
3735 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3741 // Check if B comes from one of C, D, E, F.
3742 for (unsigned Half = 0; Half != 4; ++Half) {
3743 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3749 return MatchA && MatchB;
3752 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3753 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3754 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3755 EVT VT = SVOp->getValueType(0);
3757 unsigned HalfSize = VT.getVectorNumElements()/2;
3759 unsigned FstHalf = 0, SndHalf = 0;
3760 for (unsigned i = 0; i < HalfSize; ++i) {
3761 if (SVOp->getMaskElt(i) > 0) {
3762 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3766 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3767 if (SVOp->getMaskElt(i) > 0) {
3768 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3773 return (FstHalf | (SndHalf << 4));
3776 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3777 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3778 /// Note that VPERMIL mask matching is different depending whether theunderlying
3779 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3780 /// to the same elements of the low, but to the higher half of the source.
3781 /// In VPERMILPD the two lanes could be shuffled independently of each other
3782 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3783 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3787 unsigned NumElts = VT.getVectorNumElements();
3788 // Only match 256-bit with 32/64-bit types
3789 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3792 unsigned NumLanes = VT.getSizeInBits()/128;
3793 unsigned LaneSize = NumElts/NumLanes;
3794 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3795 for (unsigned i = 0; i != LaneSize; ++i) {
3796 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3798 if (NumElts != 8 || l == 0)
3800 // VPERMILPS handling
3803 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3811 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3812 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3813 /// element of vector 2 and the other elements to come from vector 1 in order.
3814 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3815 bool V2IsSplat = false, bool V2IsUndef = false) {
3816 if (!VT.is128BitVector())
3819 unsigned NumOps = VT.getVectorNumElements();
3820 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3823 if (!isUndefOrEqual(Mask[0], 0))
3826 for (unsigned i = 1; i != NumOps; ++i)
3827 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3828 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3829 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3835 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3836 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3837 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3838 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3839 const X86Subtarget *Subtarget) {
3840 if (!Subtarget->hasSSE3())
3843 unsigned NumElems = VT.getVectorNumElements();
3845 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3846 (VT.getSizeInBits() == 256 && NumElems != 8))
3849 // "i+1" is the value the indexed mask element must have
3850 for (unsigned i = 0; i != NumElems; i += 2)
3851 if (!isUndefOrEqual(Mask[i], i+1) ||
3852 !isUndefOrEqual(Mask[i+1], i+1))
3858 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3859 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3860 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3861 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3862 const X86Subtarget *Subtarget) {
3863 if (!Subtarget->hasSSE3())
3866 unsigned NumElems = VT.getVectorNumElements();
3868 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3869 (VT.getSizeInBits() == 256 && NumElems != 8))
3872 // "i" is the value the indexed mask element must have
3873 for (unsigned i = 0; i != NumElems; i += 2)
3874 if (!isUndefOrEqual(Mask[i], i) ||
3875 !isUndefOrEqual(Mask[i+1], i))
3881 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3882 /// specifies a shuffle of elements that is suitable for input to 256-bit
3883 /// version of MOVDDUP.
3884 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3885 if (!HasAVX || !VT.is256BitVector())
3888 unsigned NumElts = VT.getVectorNumElements();
3892 for (unsigned i = 0; i != NumElts/2; ++i)
3893 if (!isUndefOrEqual(Mask[i], 0))
3895 for (unsigned i = NumElts/2; i != NumElts; ++i)
3896 if (!isUndefOrEqual(Mask[i], NumElts/2))
3901 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3902 /// specifies a shuffle of elements that is suitable for input to 128-bit
3903 /// version of MOVDDUP.
3904 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3905 if (!VT.is128BitVector())
3908 unsigned e = VT.getVectorNumElements() / 2;
3909 for (unsigned i = 0; i != e; ++i)
3910 if (!isUndefOrEqual(Mask[i], i))
3912 for (unsigned i = 0; i != e; ++i)
3913 if (!isUndefOrEqual(Mask[e+i], i))
3918 /// isVEXTRACTF128Index - Return true if the specified
3919 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3920 /// suitable for input to VEXTRACTF128.
3921 bool X86::isVEXTRACTF128Index(SDNode *N) {
3922 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3925 // The index should be aligned on a 128-bit boundary.
3927 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3929 unsigned VL = N->getValueType(0).getVectorNumElements();
3930 unsigned VBits = N->getValueType(0).getSizeInBits();
3931 unsigned ElSize = VBits / VL;
3932 bool Result = (Index * ElSize) % 128 == 0;
3937 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3938 /// operand specifies a subvector insert that is suitable for input to
3940 bool X86::isVINSERTF128Index(SDNode *N) {
3941 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3944 // The index should be aligned on a 128-bit boundary.
3946 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3948 unsigned VL = N->getValueType(0).getVectorNumElements();
3949 unsigned VBits = N->getValueType(0).getSizeInBits();
3950 unsigned ElSize = VBits / VL;
3951 bool Result = (Index * ElSize) % 128 == 0;
3956 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3957 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3958 /// Handles 128-bit and 256-bit.
3959 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3960 EVT VT = N->getValueType(0);
3962 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3963 "Unsupported vector type for PSHUF/SHUFP");
3965 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3966 // independently on 128-bit lanes.
3967 unsigned NumElts = VT.getVectorNumElements();
3968 unsigned NumLanes = VT.getSizeInBits()/128;
3969 unsigned NumLaneElts = NumElts/NumLanes;
3971 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3972 "Only supports 2 or 4 elements per lane");
3974 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3976 for (unsigned i = 0; i != NumElts; ++i) {
3977 int Elt = N->getMaskElt(i);
3978 if (Elt < 0) continue;
3979 Elt &= NumLaneElts - 1;
3980 unsigned ShAmt = (i << Shift) % 8;
3981 Mask |= Elt << ShAmt;
3987 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3988 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3989 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3990 EVT VT = N->getValueType(0);
3992 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3993 "Unsupported vector type for PSHUFHW");
3995 unsigned NumElts = VT.getVectorNumElements();
3998 for (unsigned l = 0; l != NumElts; l += 8) {
3999 // 8 nodes per lane, but we only care about the last 4.
4000 for (unsigned i = 0; i < 4; ++i) {
4001 int Elt = N->getMaskElt(l+i+4);
4002 if (Elt < 0) continue;
4003 Elt &= 0x3; // only 2-bits.
4004 Mask |= Elt << (i * 2);
4011 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4012 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4013 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4014 EVT VT = N->getValueType(0);
4016 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4017 "Unsupported vector type for PSHUFHW");
4019 unsigned NumElts = VT.getVectorNumElements();
4022 for (unsigned l = 0; l != NumElts; l += 8) {
4023 // 8 nodes per lane, but we only care about the first 4.
4024 for (unsigned i = 0; i < 4; ++i) {
4025 int Elt = N->getMaskElt(l+i);
4026 if (Elt < 0) continue;
4027 Elt &= 0x3; // only 2-bits
4028 Mask |= Elt << (i * 2);
4035 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4036 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4037 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4038 EVT VT = SVOp->getValueType(0);
4039 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4041 unsigned NumElts = VT.getVectorNumElements();
4042 unsigned NumLanes = VT.getSizeInBits()/128;
4043 unsigned NumLaneElts = NumElts/NumLanes;
4047 for (i = 0; i != NumElts; ++i) {
4048 Val = SVOp->getMaskElt(i);
4052 if (Val >= (int)NumElts)
4053 Val -= NumElts - NumLaneElts;
4055 assert(Val - i > 0 && "PALIGNR imm should be positive");
4056 return (Val - i) * EltSize;
4059 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4060 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4062 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4063 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4064 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4067 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4069 EVT VecVT = N->getOperand(0).getValueType();
4070 EVT ElVT = VecVT.getVectorElementType();
4072 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4073 return Index / NumElemsPerChunk;
4076 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4077 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4079 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4080 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4081 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4084 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4086 EVT VecVT = N->getValueType(0);
4087 EVT ElVT = VecVT.getVectorElementType();
4089 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4090 return Index / NumElemsPerChunk;
4093 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4094 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4095 /// Handles 256-bit.
4096 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4097 EVT VT = N->getValueType(0);
4099 unsigned NumElts = VT.getVectorNumElements();
4101 assert((VT.is256BitVector() && NumElts == 4) &&
4102 "Unsupported vector type for VPERMQ/VPERMPD");
4105 for (unsigned i = 0; i != NumElts; ++i) {
4106 int Elt = N->getMaskElt(i);
4109 Mask |= Elt << (i*2);
4114 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4116 bool X86::isZeroNode(SDValue Elt) {
4117 return ((isa<ConstantSDNode>(Elt) &&
4118 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4119 (isa<ConstantFPSDNode>(Elt) &&
4120 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4123 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4124 /// their permute mask.
4125 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4126 SelectionDAG &DAG) {
4127 EVT VT = SVOp->getValueType(0);
4128 unsigned NumElems = VT.getVectorNumElements();
4129 SmallVector<int, 8> MaskVec;
4131 for (unsigned i = 0; i != NumElems; ++i) {
4132 int Idx = SVOp->getMaskElt(i);
4134 if (Idx < (int)NumElems)
4139 MaskVec.push_back(Idx);
4141 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4142 SVOp->getOperand(0), &MaskVec[0]);
4145 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4146 /// match movhlps. The lower half elements should come from upper half of
4147 /// V1 (and in order), and the upper half elements should come from the upper
4148 /// half of V2 (and in order).
4149 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4150 if (!VT.is128BitVector())
4152 if (VT.getVectorNumElements() != 4)
4154 for (unsigned i = 0, e = 2; i != e; ++i)
4155 if (!isUndefOrEqual(Mask[i], i+2))
4157 for (unsigned i = 2; i != 4; ++i)
4158 if (!isUndefOrEqual(Mask[i], i+4))
4163 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4164 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4166 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4167 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4169 N = N->getOperand(0).getNode();
4170 if (!ISD::isNON_EXTLoad(N))
4173 *LD = cast<LoadSDNode>(N);
4177 // Test whether the given value is a vector value which will be legalized
4179 static bool WillBeConstantPoolLoad(SDNode *N) {
4180 if (N->getOpcode() != ISD::BUILD_VECTOR)
4183 // Check for any non-constant elements.
4184 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4185 switch (N->getOperand(i).getNode()->getOpcode()) {
4187 case ISD::ConstantFP:
4194 // Vectors of all-zeros and all-ones are materialized with special
4195 // instructions rather than being loaded.
4196 return !ISD::isBuildVectorAllZeros(N) &&
4197 !ISD::isBuildVectorAllOnes(N);
4200 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4201 /// match movlp{s|d}. The lower half elements should come from lower half of
4202 /// V1 (and in order), and the upper half elements should come from the upper
4203 /// half of V2 (and in order). And since V1 will become the source of the
4204 /// MOVLP, it must be either a vector load or a scalar load to vector.
4205 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4206 ArrayRef<int> Mask, EVT VT) {
4207 if (!VT.is128BitVector())
4210 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4212 // Is V2 is a vector load, don't do this transformation. We will try to use
4213 // load folding shufps op.
4214 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4217 unsigned NumElems = VT.getVectorNumElements();
4219 if (NumElems != 2 && NumElems != 4)
4221 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4222 if (!isUndefOrEqual(Mask[i], i))
4224 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4225 if (!isUndefOrEqual(Mask[i], i+NumElems))
4230 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4232 static bool isSplatVector(SDNode *N) {
4233 if (N->getOpcode() != ISD::BUILD_VECTOR)
4236 SDValue SplatValue = N->getOperand(0);
4237 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4238 if (N->getOperand(i) != SplatValue)
4243 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4244 /// to an zero vector.
4245 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4246 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4247 SDValue V1 = N->getOperand(0);
4248 SDValue V2 = N->getOperand(1);
4249 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4250 for (unsigned i = 0; i != NumElems; ++i) {
4251 int Idx = N->getMaskElt(i);
4252 if (Idx >= (int)NumElems) {
4253 unsigned Opc = V2.getOpcode();
4254 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4256 if (Opc != ISD::BUILD_VECTOR ||
4257 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4259 } else if (Idx >= 0) {
4260 unsigned Opc = V1.getOpcode();
4261 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4263 if (Opc != ISD::BUILD_VECTOR ||
4264 !X86::isZeroNode(V1.getOperand(Idx)))
4271 /// getZeroVector - Returns a vector of specified type with all zero elements.
4273 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4274 SelectionDAG &DAG, DebugLoc dl) {
4275 assert(VT.isVector() && "Expected a vector type");
4276 unsigned Size = VT.getSizeInBits();
4278 // Always build SSE zero vectors as <4 x i32> bitcasted
4279 // to their dest type. This ensures they get CSE'd.
4281 if (Size == 128) { // SSE
4282 if (Subtarget->hasSSE2()) { // SSE2
4283 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4284 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4286 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4287 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4289 } else if (Size == 256) { // AVX
4290 if (Subtarget->hasAVX2()) { // AVX2
4291 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4292 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4293 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4295 // 256-bit logic and arithmetic instructions in AVX are all
4296 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4297 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4298 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4299 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4302 llvm_unreachable("Unexpected vector type");
4304 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4307 /// getOnesVector - Returns a vector of specified type with all bits set.
4308 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4309 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4310 /// Then bitcast to their original type, ensuring they get CSE'd.
4311 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4313 assert(VT.isVector() && "Expected a vector type");
4314 unsigned Size = VT.getSizeInBits();
4316 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4319 if (HasAVX2) { // AVX2
4320 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4321 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4323 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4324 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4326 } else if (Size == 128) {
4327 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4329 llvm_unreachable("Unexpected vector type");
4331 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4334 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4335 /// that point to V2 points to its first element.
4336 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4337 for (unsigned i = 0; i != NumElems; ++i) {
4338 if (Mask[i] > (int)NumElems) {
4344 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4345 /// operation of specified width.
4346 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4348 unsigned NumElems = VT.getVectorNumElements();
4349 SmallVector<int, 8> Mask;
4350 Mask.push_back(NumElems);
4351 for (unsigned i = 1; i != NumElems; ++i)
4353 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4356 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4357 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4359 unsigned NumElems = VT.getVectorNumElements();
4360 SmallVector<int, 8> Mask;
4361 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4363 Mask.push_back(i + NumElems);
4365 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4368 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4369 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4371 unsigned NumElems = VT.getVectorNumElements();
4372 SmallVector<int, 8> Mask;
4373 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4374 Mask.push_back(i + Half);
4375 Mask.push_back(i + NumElems + Half);
4377 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4380 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4381 // a generic shuffle instruction because the target has no such instructions.
4382 // Generate shuffles which repeat i16 and i8 several times until they can be
4383 // represented by v4f32 and then be manipulated by target suported shuffles.
4384 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4385 EVT VT = V.getValueType();
4386 int NumElems = VT.getVectorNumElements();
4387 DebugLoc dl = V.getDebugLoc();
4389 while (NumElems > 4) {
4390 if (EltNo < NumElems/2) {
4391 V = getUnpackl(DAG, dl, VT, V, V);
4393 V = getUnpackh(DAG, dl, VT, V, V);
4394 EltNo -= NumElems/2;
4401 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4402 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4403 EVT VT = V.getValueType();
4404 DebugLoc dl = V.getDebugLoc();
4405 unsigned Size = VT.getSizeInBits();
4408 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4409 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4410 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4412 } else if (Size == 256) {
4413 // To use VPERMILPS to splat scalars, the second half of indicies must
4414 // refer to the higher part, which is a duplication of the lower one,
4415 // because VPERMILPS can only handle in-lane permutations.
4416 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4417 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4419 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4420 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4423 llvm_unreachable("Vector size not supported");
4425 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4428 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4429 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4430 EVT SrcVT = SV->getValueType(0);
4431 SDValue V1 = SV->getOperand(0);
4432 DebugLoc dl = SV->getDebugLoc();
4434 int EltNo = SV->getSplatIndex();
4435 int NumElems = SrcVT.getVectorNumElements();
4436 unsigned Size = SrcVT.getSizeInBits();
4438 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4439 "Unknown how to promote splat for type");
4441 // Extract the 128-bit part containing the splat element and update
4442 // the splat element index when it refers to the higher register.
4444 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4445 if (EltNo >= NumElems/2)
4446 EltNo -= NumElems/2;
4449 // All i16 and i8 vector types can't be used directly by a generic shuffle
4450 // instruction because the target has no such instruction. Generate shuffles
4451 // which repeat i16 and i8 several times until they fit in i32, and then can
4452 // be manipulated by target suported shuffles.
4453 EVT EltVT = SrcVT.getVectorElementType();
4454 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4455 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4457 // Recreate the 256-bit vector and place the same 128-bit vector
4458 // into the low and high part. This is necessary because we want
4459 // to use VPERM* to shuffle the vectors
4461 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4464 return getLegalSplat(DAG, V1, EltNo);
4467 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4468 /// vector of zero or undef vector. This produces a shuffle where the low
4469 /// element of V2 is swizzled into the zero/undef vector, landing at element
4470 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4471 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4473 const X86Subtarget *Subtarget,
4474 SelectionDAG &DAG) {
4475 EVT VT = V2.getValueType();
4477 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4478 unsigned NumElems = VT.getVectorNumElements();
4479 SmallVector<int, 16> MaskVec;
4480 for (unsigned i = 0; i != NumElems; ++i)
4481 // If this is the insertion idx, put the low elt of V2 here.
4482 MaskVec.push_back(i == Idx ? NumElems : i);
4483 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4486 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4487 /// target specific opcode. Returns true if the Mask could be calculated.
4488 /// Sets IsUnary to true if only uses one source.
4489 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4490 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4491 unsigned NumElems = VT.getVectorNumElements();
4495 switch(N->getOpcode()) {
4497 ImmN = N->getOperand(N->getNumOperands()-1);
4498 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500 case X86ISD::UNPCKH:
4501 DecodeUNPCKHMask(VT, Mask);
4503 case X86ISD::UNPCKL:
4504 DecodeUNPCKLMask(VT, Mask);
4506 case X86ISD::MOVHLPS:
4507 DecodeMOVHLPSMask(NumElems, Mask);
4509 case X86ISD::MOVLHPS:
4510 DecodeMOVLHPSMask(NumElems, Mask);
4512 case X86ISD::PSHUFD:
4513 case X86ISD::VPERMILP:
4514 ImmN = N->getOperand(N->getNumOperands()-1);
4515 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4518 case X86ISD::PSHUFHW:
4519 ImmN = N->getOperand(N->getNumOperands()-1);
4520 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4523 case X86ISD::PSHUFLW:
4524 ImmN = N->getOperand(N->getNumOperands()-1);
4525 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4528 case X86ISD::VPERMI:
4529 ImmN = N->getOperand(N->getNumOperands()-1);
4530 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4534 case X86ISD::MOVSD: {
4535 // The index 0 always comes from the first element of the second source,
4536 // this is why MOVSS and MOVSD are used in the first place. The other
4537 // elements come from the other positions of the first source vector
4538 Mask.push_back(NumElems);
4539 for (unsigned i = 1; i != NumElems; ++i) {
4544 case X86ISD::VPERM2X128:
4545 ImmN = N->getOperand(N->getNumOperands()-1);
4546 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4547 if (Mask.empty()) return false;
4549 case X86ISD::MOVDDUP:
4550 case X86ISD::MOVLHPD:
4551 case X86ISD::MOVLPD:
4552 case X86ISD::MOVLPS:
4553 case X86ISD::MOVSHDUP:
4554 case X86ISD::MOVSLDUP:
4555 case X86ISD::PALIGN:
4556 // Not yet implemented
4558 default: llvm_unreachable("unknown target shuffle node");
4564 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4565 /// element of the result of the vector shuffle.
4566 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4569 return SDValue(); // Limit search depth.
4571 SDValue V = SDValue(N, 0);
4572 EVT VT = V.getValueType();
4573 unsigned Opcode = V.getOpcode();
4575 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4576 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4577 int Elt = SV->getMaskElt(Index);
4580 return DAG.getUNDEF(VT.getVectorElementType());
4582 unsigned NumElems = VT.getVectorNumElements();
4583 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4584 : SV->getOperand(1);
4585 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4588 // Recurse into target specific vector shuffles to find scalars.
4589 if (isTargetShuffle(Opcode)) {
4590 MVT ShufVT = V.getValueType().getSimpleVT();
4591 unsigned NumElems = ShufVT.getVectorNumElements();
4592 SmallVector<int, 16> ShuffleMask;
4596 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4599 int Elt = ShuffleMask[Index];
4601 return DAG.getUNDEF(ShufVT.getVectorElementType());
4603 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4605 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4609 // Actual nodes that may contain scalar elements
4610 if (Opcode == ISD::BITCAST) {
4611 V = V.getOperand(0);
4612 EVT SrcVT = V.getValueType();
4613 unsigned NumElems = VT.getVectorNumElements();
4615 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4619 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4620 return (Index == 0) ? V.getOperand(0)
4621 : DAG.getUNDEF(VT.getVectorElementType());
4623 if (V.getOpcode() == ISD::BUILD_VECTOR)
4624 return V.getOperand(Index);
4629 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4630 /// shuffle operation which come from a consecutively from a zero. The
4631 /// search can start in two different directions, from left or right.
4633 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4634 bool ZerosFromLeft, SelectionDAG &DAG) {
4636 for (i = 0; i != NumElems; ++i) {
4637 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4638 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4639 if (!(Elt.getNode() &&
4640 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4647 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4648 /// correspond consecutively to elements from one of the vector operands,
4649 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4651 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4652 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4653 unsigned NumElems, unsigned &OpNum) {
4654 bool SeenV1 = false;
4655 bool SeenV2 = false;
4657 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4658 int Idx = SVOp->getMaskElt(i);
4659 // Ignore undef indicies
4663 if (Idx < (int)NumElems)
4668 // Only accept consecutive elements from the same vector
4669 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4673 OpNum = SeenV1 ? 0 : 1;
4677 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4678 /// logical left shift of a vector.
4679 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4680 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4681 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4682 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4683 false /* check zeros from right */, DAG);
4689 // Considering the elements in the mask that are not consecutive zeros,
4690 // check if they consecutively come from only one of the source vectors.
4692 // V1 = {X, A, B, C} 0
4694 // vector_shuffle V1, V2 <1, 2, 3, X>
4696 if (!isShuffleMaskConsecutive(SVOp,
4697 0, // Mask Start Index
4698 NumElems-NumZeros, // Mask End Index(exclusive)
4699 NumZeros, // Where to start looking in the src vector
4700 NumElems, // Number of elements in vector
4701 OpSrc)) // Which source operand ?
4706 ShVal = SVOp->getOperand(OpSrc);
4710 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4711 /// logical left shift of a vector.
4712 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4713 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4714 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4715 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4716 true /* check zeros from left */, DAG);
4722 // Considering the elements in the mask that are not consecutive zeros,
4723 // check if they consecutively come from only one of the source vectors.
4725 // 0 { A, B, X, X } = V2
4727 // vector_shuffle V1, V2 <X, X, 4, 5>
4729 if (!isShuffleMaskConsecutive(SVOp,
4730 NumZeros, // Mask Start Index
4731 NumElems, // Mask End Index(exclusive)
4732 0, // Where to start looking in the src vector
4733 NumElems, // Number of elements in vector
4734 OpSrc)) // Which source operand ?
4739 ShVal = SVOp->getOperand(OpSrc);
4743 /// isVectorShift - Returns true if the shuffle can be implemented as a
4744 /// logical left or right shift of a vector.
4745 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4746 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4747 // Although the logic below support any bitwidth size, there are no
4748 // shift instructions which handle more than 128-bit vectors.
4749 if (!SVOp->getValueType(0).is128BitVector())
4752 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4753 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4759 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4761 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4762 unsigned NumNonZero, unsigned NumZero,
4764 const X86Subtarget* Subtarget,
4765 const TargetLowering &TLI) {
4769 DebugLoc dl = Op.getDebugLoc();
4772 for (unsigned i = 0; i < 16; ++i) {
4773 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4774 if (ThisIsNonZero && First) {
4776 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4778 V = DAG.getUNDEF(MVT::v8i16);
4783 SDValue ThisElt(0, 0), LastElt(0, 0);
4784 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4785 if (LastIsNonZero) {
4786 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4787 MVT::i16, Op.getOperand(i-1));
4789 if (ThisIsNonZero) {
4790 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4791 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4792 ThisElt, DAG.getConstant(8, MVT::i8));
4794 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4798 if (ThisElt.getNode())
4799 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4800 DAG.getIntPtrConstant(i/2));
4804 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4807 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4809 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4810 unsigned NumNonZero, unsigned NumZero,
4812 const X86Subtarget* Subtarget,
4813 const TargetLowering &TLI) {
4817 DebugLoc dl = Op.getDebugLoc();
4820 for (unsigned i = 0; i < 8; ++i) {
4821 bool isNonZero = (NonZeros & (1 << i)) != 0;
4825 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4827 V = DAG.getUNDEF(MVT::v8i16);
4830 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4831 MVT::v8i16, V, Op.getOperand(i),
4832 DAG.getIntPtrConstant(i));
4839 /// getVShift - Return a vector logical shift node.
4841 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4842 unsigned NumBits, SelectionDAG &DAG,
4843 const TargetLowering &TLI, DebugLoc dl) {
4844 assert(VT.is128BitVector() && "Unknown type for VShift");
4845 EVT ShVT = MVT::v2i64;
4846 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4847 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4848 return DAG.getNode(ISD::BITCAST, dl, VT,
4849 DAG.getNode(Opc, dl, ShVT, SrcOp,
4850 DAG.getConstant(NumBits,
4851 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4855 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4856 SelectionDAG &DAG) const {
4858 // Check if the scalar load can be widened into a vector load. And if
4859 // the address is "base + cst" see if the cst can be "absorbed" into
4860 // the shuffle mask.
4861 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4862 SDValue Ptr = LD->getBasePtr();
4863 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4865 EVT PVT = LD->getValueType(0);
4866 if (PVT != MVT::i32 && PVT != MVT::f32)
4871 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4872 FI = FINode->getIndex();
4874 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4875 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4876 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4877 Offset = Ptr.getConstantOperandVal(1);
4878 Ptr = Ptr.getOperand(0);
4883 // FIXME: 256-bit vector instructions don't require a strict alignment,
4884 // improve this code to support it better.
4885 unsigned RequiredAlign = VT.getSizeInBits()/8;
4886 SDValue Chain = LD->getChain();
4887 // Make sure the stack object alignment is at least 16 or 32.
4888 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4889 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4890 if (MFI->isFixedObjectIndex(FI)) {
4891 // Can't change the alignment. FIXME: It's possible to compute
4892 // the exact stack offset and reference FI + adjust offset instead.
4893 // If someone *really* cares about this. That's the way to implement it.
4896 MFI->setObjectAlignment(FI, RequiredAlign);
4900 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4901 // Ptr + (Offset & ~15).
4904 if ((Offset % RequiredAlign) & 3)
4906 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4908 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4909 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4911 int EltNo = (Offset - StartOffset) >> 2;
4912 unsigned NumElems = VT.getVectorNumElements();
4914 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4915 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4916 LD->getPointerInfo().getWithOffset(StartOffset),
4917 false, false, false, 0);
4919 SmallVector<int, 8> Mask;
4920 for (unsigned i = 0; i != NumElems; ++i)
4921 Mask.push_back(EltNo);
4923 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4929 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4930 /// vector of type 'VT', see if the elements can be replaced by a single large
4931 /// load which has the same value as a build_vector whose operands are 'elts'.
4933 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4935 /// FIXME: we'd also like to handle the case where the last elements are zero
4936 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4937 /// There's even a handy isZeroNode for that purpose.
4938 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4939 DebugLoc &DL, SelectionDAG &DAG) {
4940 EVT EltVT = VT.getVectorElementType();
4941 unsigned NumElems = Elts.size();
4943 LoadSDNode *LDBase = NULL;
4944 unsigned LastLoadedElt = -1U;
4946 // For each element in the initializer, see if we've found a load or an undef.
4947 // If we don't find an initial load element, or later load elements are
4948 // non-consecutive, bail out.
4949 for (unsigned i = 0; i < NumElems; ++i) {
4950 SDValue Elt = Elts[i];
4952 if (!Elt.getNode() ||
4953 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4956 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4958 LDBase = cast<LoadSDNode>(Elt.getNode());
4962 if (Elt.getOpcode() == ISD::UNDEF)
4965 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4966 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4971 // If we have found an entire vector of loads and undefs, then return a large
4972 // load of the entire vector width starting at the base pointer. If we found
4973 // consecutive loads for the low half, generate a vzext_load node.
4974 if (LastLoadedElt == NumElems - 1) {
4975 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4976 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4977 LDBase->getPointerInfo(),
4978 LDBase->isVolatile(), LDBase->isNonTemporal(),
4979 LDBase->isInvariant(), 0);
4980 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4981 LDBase->getPointerInfo(),
4982 LDBase->isVolatile(), LDBase->isNonTemporal(),
4983 LDBase->isInvariant(), LDBase->getAlignment());
4985 if (NumElems == 4 && LastLoadedElt == 1 &&
4986 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4987 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4988 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4990 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4991 LDBase->getPointerInfo(),
4992 LDBase->getAlignment(),
4993 false/*isVolatile*/, true/*ReadMem*/,
4996 // Make sure the newly-created LOAD is in the same position as LDBase in
4997 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4998 // update uses of LDBase's output chain to use the TokenFactor.
4999 if (LDBase->hasAnyUseOfValue(1)) {
5000 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5001 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5002 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5003 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5004 SDValue(ResNode.getNode(), 1));
5007 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5012 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5013 /// to generate a splat value for the following cases:
5014 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5015 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5016 /// a scalar load, or a constant.
5017 /// The VBROADCAST node is returned when a pattern is found,
5018 /// or SDValue() otherwise.
5020 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5021 if (!Subtarget->hasAVX())
5024 EVT VT = Op.getValueType();
5025 DebugLoc dl = Op.getDebugLoc();
5027 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5028 "Unsupported vector type for broadcast.");
5033 switch (Op.getOpcode()) {
5035 // Unknown pattern found.
5038 case ISD::BUILD_VECTOR: {
5039 // The BUILD_VECTOR node must be a splat.
5040 if (!isSplatVector(Op.getNode()))
5043 Ld = Op.getOperand(0);
5044 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5045 Ld.getOpcode() == ISD::ConstantFP);
5047 // The suspected load node has several users. Make sure that all
5048 // of its users are from the BUILD_VECTOR node.
5049 // Constants may have multiple users.
5050 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5055 case ISD::VECTOR_SHUFFLE: {
5056 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5058 // Shuffles must have a splat mask where the first element is
5060 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5063 SDValue Sc = Op.getOperand(0);
5064 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5065 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5067 if (!Subtarget->hasAVX2())
5070 // Use the register form of the broadcast instruction available on AVX2.
5071 if (VT.is256BitVector())
5072 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5073 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5076 Ld = Sc.getOperand(0);
5077 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5078 Ld.getOpcode() == ISD::ConstantFP);
5080 // The scalar_to_vector node and the suspected
5081 // load node must have exactly one user.
5082 // Constants may have multiple users.
5083 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5089 bool Is256 = VT.is256BitVector();
5091 // Handle the broadcasting a single constant scalar from the constant pool
5092 // into a vector. On Sandybridge it is still better to load a constant vector
5093 // from the constant pool and not to broadcast it from a scalar.
5094 if (ConstSplatVal && Subtarget->hasAVX2()) {
5095 EVT CVT = Ld.getValueType();
5096 assert(!CVT.isVector() && "Must not broadcast a vector type");
5097 unsigned ScalarSize = CVT.getSizeInBits();
5099 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5100 const Constant *C = 0;
5101 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5102 C = CI->getConstantIntValue();
5103 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5104 C = CF->getConstantFPValue();
5106 assert(C && "Invalid constant type");
5108 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5109 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5110 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5111 MachinePointerInfo::getConstantPool(),
5112 false, false, false, Alignment);
5114 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5118 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5119 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5121 // Handle AVX2 in-register broadcasts.
5122 if (!IsLoad && Subtarget->hasAVX2() &&
5123 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5124 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5126 // The scalar source must be a normal load.
5130 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5131 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5133 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5134 // double since there is no vbroadcastsd xmm
5135 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5136 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5137 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5140 // Unsupported broadcast.
5144 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5145 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5146 // constraint of matching input/output vector elements.
5148 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5149 DebugLoc DL = Op.getDebugLoc();
5150 SDNode *N = Op.getNode();
5151 EVT VT = Op.getValueType();
5152 unsigned NumElts = Op.getNumOperands();
5154 // Check supported types and sub-targets.
5156 // Only v2f32 -> v2f64 needs special handling.
5157 if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5162 SmallVector<int, 8> Mask;
5163 EVT SrcVT = MVT::Other;
5165 // Check the patterns could be translated into X86vfpext.
5166 for (unsigned i = 0; i < NumElts; ++i) {
5167 SDValue In = N->getOperand(i);
5168 unsigned Opcode = In.getOpcode();
5170 // Skip if the element is undefined.
5171 if (Opcode == ISD::UNDEF) {
5176 // Quit if one of the elements is not defined from 'fpext'.
5177 if (Opcode != ISD::FP_EXTEND)
5180 // Check how the source of 'fpext' is defined.
5181 SDValue L2In = In.getOperand(0);
5182 EVT L2InVT = L2In.getValueType();
5184 // Check the original type
5185 if (SrcVT == MVT::Other)
5187 else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5190 // Check whether the value being 'fpext'ed is extracted from the same
5192 Opcode = L2In.getOpcode();
5194 // Quit if it's not extracted with a constant index.
5195 if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5196 !isa<ConstantSDNode>(L2In.getOperand(1)))
5199 SDValue ExtractedFromVec = L2In.getOperand(0);
5201 if (VecIn.getNode() == 0) {
5202 VecIn = ExtractedFromVec;
5203 VecInVT = ExtractedFromVec.getValueType();
5204 } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5207 Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5210 // Quit if all operands of BUILD_VECTOR are undefined.
5211 if (!VecIn.getNode())
5214 // Fill the remaining mask as undef.
5215 for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5218 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5219 DAG.getVectorShuffle(VecInVT, DL,
5220 VecIn, DAG.getUNDEF(VecInVT),
5225 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5226 DebugLoc dl = Op.getDebugLoc();
5228 EVT VT = Op.getValueType();
5229 EVT ExtVT = VT.getVectorElementType();
5230 unsigned NumElems = Op.getNumOperands();
5232 // Vectors containing all zeros can be matched by pxor and xorps later
5233 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5234 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5235 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5236 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5239 return getZeroVector(VT, Subtarget, DAG, dl);
5242 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5243 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5244 // vpcmpeqd on 256-bit vectors.
5245 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5246 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5249 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5252 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5253 if (Broadcast.getNode())
5256 SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5257 if (FpExt.getNode())
5260 unsigned EVTBits = ExtVT.getSizeInBits();
5262 unsigned NumZero = 0;
5263 unsigned NumNonZero = 0;
5264 unsigned NonZeros = 0;
5265 bool IsAllConstants = true;
5266 SmallSet<SDValue, 8> Values;
5267 for (unsigned i = 0; i < NumElems; ++i) {
5268 SDValue Elt = Op.getOperand(i);
5269 if (Elt.getOpcode() == ISD::UNDEF)
5272 if (Elt.getOpcode() != ISD::Constant &&
5273 Elt.getOpcode() != ISD::ConstantFP)
5274 IsAllConstants = false;
5275 if (X86::isZeroNode(Elt))
5278 NonZeros |= (1 << i);
5283 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5284 if (NumNonZero == 0)
5285 return DAG.getUNDEF(VT);
5287 // Special case for single non-zero, non-undef, element.
5288 if (NumNonZero == 1) {
5289 unsigned Idx = CountTrailingZeros_32(NonZeros);
5290 SDValue Item = Op.getOperand(Idx);
5292 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5293 // the value are obviously zero, truncate the value to i32 and do the
5294 // insertion that way. Only do this if the value is non-constant or if the
5295 // value is a constant being inserted into element 0. It is cheaper to do
5296 // a constant pool load than it is to do a movd + shuffle.
5297 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5298 (!IsAllConstants || Idx == 0)) {
5299 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5301 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5302 EVT VecVT = MVT::v4i32;
5303 unsigned VecElts = 4;
5305 // Truncate the value (which may itself be a constant) to i32, and
5306 // convert it to a vector with movd (S2V+shuffle to zero extend).
5307 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5308 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5309 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5311 // Now we have our 32-bit value zero extended in the low element of
5312 // a vector. If Idx != 0, swizzle it into place.
5314 SmallVector<int, 4> Mask;
5315 Mask.push_back(Idx);
5316 for (unsigned i = 1; i != VecElts; ++i)
5318 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5321 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5325 // If we have a constant or non-constant insertion into the low element of
5326 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5327 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5328 // depending on what the source datatype is.
5331 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5333 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5334 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5335 if (VT.is256BitVector()) {
5336 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5337 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5338 Item, DAG.getIntPtrConstant(0));
5340 assert(VT.is128BitVector() && "Expected an SSE value type!");
5341 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5342 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5343 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5346 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5347 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5348 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5349 if (VT.is256BitVector()) {
5350 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5351 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5353 assert(VT.is128BitVector() && "Expected an SSE value type!");
5354 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5356 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5360 // Is it a vector logical left shift?
5361 if (NumElems == 2 && Idx == 1 &&
5362 X86::isZeroNode(Op.getOperand(0)) &&
5363 !X86::isZeroNode(Op.getOperand(1))) {
5364 unsigned NumBits = VT.getSizeInBits();
5365 return getVShift(true, VT,
5366 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5367 VT, Op.getOperand(1)),
5368 NumBits/2, DAG, *this, dl);
5371 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5374 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5375 // is a non-constant being inserted into an element other than the low one,
5376 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5377 // movd/movss) to move this into the low element, then shuffle it into
5379 if (EVTBits == 32) {
5380 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5382 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5383 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5384 SmallVector<int, 8> MaskVec;
5385 for (unsigned i = 0; i != NumElems; ++i)
5386 MaskVec.push_back(i == Idx ? 0 : 1);
5387 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5391 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5392 if (Values.size() == 1) {
5393 if (EVTBits == 32) {
5394 // Instead of a shuffle like this:
5395 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5396 // Check if it's possible to issue this instead.
5397 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5398 unsigned Idx = CountTrailingZeros_32(NonZeros);
5399 SDValue Item = Op.getOperand(Idx);
5400 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5401 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5406 // A vector full of immediates; various special cases are already
5407 // handled, so this is best done with a single constant-pool load.
5411 // For AVX-length vectors, build the individual 128-bit pieces and use
5412 // shuffles to put them in place.
5413 if (VT.is256BitVector()) {
5414 SmallVector<SDValue, 32> V;
5415 for (unsigned i = 0; i != NumElems; ++i)
5416 V.push_back(Op.getOperand(i));
5418 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5420 // Build both the lower and upper subvector.
5421 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5422 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5425 // Recreate the wider vector with the lower and upper part.
5426 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5429 // Let legalizer expand 2-wide build_vectors.
5430 if (EVTBits == 64) {
5431 if (NumNonZero == 1) {
5432 // One half is zero or undef.
5433 unsigned Idx = CountTrailingZeros_32(NonZeros);
5434 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5435 Op.getOperand(Idx));
5436 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5441 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5442 if (EVTBits == 8 && NumElems == 16) {
5443 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5445 if (V.getNode()) return V;
5448 if (EVTBits == 16 && NumElems == 8) {
5449 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5451 if (V.getNode()) return V;
5454 // If element VT is == 32 bits, turn it into a number of shuffles.
5455 SmallVector<SDValue, 8> V(NumElems);
5456 if (NumElems == 4 && NumZero > 0) {
5457 for (unsigned i = 0; i < 4; ++i) {
5458 bool isZero = !(NonZeros & (1 << i));
5460 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5462 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5465 for (unsigned i = 0; i < 2; ++i) {
5466 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5469 V[i] = V[i*2]; // Must be a zero vector.
5472 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5475 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5478 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5483 bool Reverse1 = (NonZeros & 0x3) == 2;
5484 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5488 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5489 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5491 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5494 if (Values.size() > 1 && VT.is128BitVector()) {
5495 // Check for a build vector of consecutive loads.
5496 for (unsigned i = 0; i < NumElems; ++i)
5497 V[i] = Op.getOperand(i);
5499 // Check for elements which are consecutive loads.
5500 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5504 // For SSE 4.1, use insertps to put the high elements into the low element.
5505 if (getSubtarget()->hasSSE41()) {
5507 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5508 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5510 Result = DAG.getUNDEF(VT);
5512 for (unsigned i = 1; i < NumElems; ++i) {
5513 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5514 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5515 Op.getOperand(i), DAG.getIntPtrConstant(i));
5520 // Otherwise, expand into a number of unpckl*, start by extending each of
5521 // our (non-undef) elements to the full vector width with the element in the
5522 // bottom slot of the vector (which generates no code for SSE).
5523 for (unsigned i = 0; i < NumElems; ++i) {
5524 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5525 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5527 V[i] = DAG.getUNDEF(VT);
5530 // Next, we iteratively mix elements, e.g. for v4f32:
5531 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5532 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5533 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5534 unsigned EltStride = NumElems >> 1;
5535 while (EltStride != 0) {
5536 for (unsigned i = 0; i < EltStride; ++i) {
5537 // If V[i+EltStride] is undef and this is the first round of mixing,
5538 // then it is safe to just drop this shuffle: V[i] is already in the
5539 // right place, the one element (since it's the first round) being
5540 // inserted as undef can be dropped. This isn't safe for successive
5541 // rounds because they will permute elements within both vectors.
5542 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5543 EltStride == NumElems/2)
5546 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5555 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5556 // to create 256-bit vectors from two other 128-bit ones.
5557 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5558 DebugLoc dl = Op.getDebugLoc();
5559 EVT ResVT = Op.getValueType();
5561 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5563 SDValue V1 = Op.getOperand(0);
5564 SDValue V2 = Op.getOperand(1);
5565 unsigned NumElems = ResVT.getVectorNumElements();
5567 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5571 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5572 assert(Op.getNumOperands() == 2);
5574 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5575 // from two other 128-bit ones.
5576 return LowerAVXCONCAT_VECTORS(Op, DAG);
5579 // Try to lower a shuffle node into a simple blend instruction.
5580 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5581 const X86Subtarget *Subtarget,
5582 SelectionDAG &DAG) {
5583 SDValue V1 = SVOp->getOperand(0);
5584 SDValue V2 = SVOp->getOperand(1);
5585 DebugLoc dl = SVOp->getDebugLoc();
5586 MVT VT = SVOp->getValueType(0).getSimpleVT();
5587 unsigned NumElems = VT.getVectorNumElements();
5589 if (!Subtarget->hasSSE41())
5595 switch (VT.SimpleTy) {
5596 default: return SDValue();
5598 ISDNo = X86ISD::BLENDPW;
5603 ISDNo = X86ISD::BLENDPS;
5608 ISDNo = X86ISD::BLENDPD;
5613 if (!Subtarget->hasAVX())
5615 ISDNo = X86ISD::BLENDPS;
5620 if (!Subtarget->hasAVX())
5622 ISDNo = X86ISD::BLENDPD;
5626 assert(ISDNo && "Invalid Op Number");
5628 unsigned MaskVals = 0;
5630 for (unsigned i = 0; i != NumElems; ++i) {
5631 int EltIdx = SVOp->getMaskElt(i);
5632 if (EltIdx == (int)i || EltIdx < 0)
5634 else if (EltIdx == (int)(i + NumElems))
5635 continue; // Bit is set to zero;
5640 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5641 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5642 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5643 DAG.getConstant(MaskVals, MVT::i32));
5644 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5647 // v8i16 shuffles - Prefer shuffles in the following order:
5648 // 1. [all] pshuflw, pshufhw, optional move
5649 // 2. [ssse3] 1 x pshufb
5650 // 3. [ssse3] 2 x pshufb + 1 x por
5651 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5653 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5654 SelectionDAG &DAG) const {
5655 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5656 SDValue V1 = SVOp->getOperand(0);
5657 SDValue V2 = SVOp->getOperand(1);
5658 DebugLoc dl = SVOp->getDebugLoc();
5659 SmallVector<int, 8> MaskVals;
5661 // Determine if more than 1 of the words in each of the low and high quadwords
5662 // of the result come from the same quadword of one of the two inputs. Undef
5663 // mask values count as coming from any quadword, for better codegen.
5664 unsigned LoQuad[] = { 0, 0, 0, 0 };
5665 unsigned HiQuad[] = { 0, 0, 0, 0 };
5666 std::bitset<4> InputQuads;
5667 for (unsigned i = 0; i < 8; ++i) {
5668 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5669 int EltIdx = SVOp->getMaskElt(i);
5670 MaskVals.push_back(EltIdx);
5679 InputQuads.set(EltIdx / 4);
5682 int BestLoQuad = -1;
5683 unsigned MaxQuad = 1;
5684 for (unsigned i = 0; i < 4; ++i) {
5685 if (LoQuad[i] > MaxQuad) {
5687 MaxQuad = LoQuad[i];
5691 int BestHiQuad = -1;
5693 for (unsigned i = 0; i < 4; ++i) {
5694 if (HiQuad[i] > MaxQuad) {
5696 MaxQuad = HiQuad[i];
5700 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5701 // of the two input vectors, shuffle them into one input vector so only a
5702 // single pshufb instruction is necessary. If There are more than 2 input
5703 // quads, disable the next transformation since it does not help SSSE3.
5704 bool V1Used = InputQuads[0] || InputQuads[1];
5705 bool V2Used = InputQuads[2] || InputQuads[3];
5706 if (Subtarget->hasSSSE3()) {
5707 if (InputQuads.count() == 2 && V1Used && V2Used) {
5708 BestLoQuad = InputQuads[0] ? 0 : 1;
5709 BestHiQuad = InputQuads[2] ? 2 : 3;
5711 if (InputQuads.count() > 2) {
5717 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5718 // the shuffle mask. If a quad is scored as -1, that means that it contains
5719 // words from all 4 input quadwords.
5721 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5723 BestLoQuad < 0 ? 0 : BestLoQuad,
5724 BestHiQuad < 0 ? 1 : BestHiQuad
5726 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5727 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5728 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5729 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5731 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5732 // source words for the shuffle, to aid later transformations.
5733 bool AllWordsInNewV = true;
5734 bool InOrder[2] = { true, true };
5735 for (unsigned i = 0; i != 8; ++i) {
5736 int idx = MaskVals[i];
5738 InOrder[i/4] = false;
5739 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5741 AllWordsInNewV = false;
5745 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5746 if (AllWordsInNewV) {
5747 for (int i = 0; i != 8; ++i) {
5748 int idx = MaskVals[i];
5751 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5752 if ((idx != i) && idx < 4)
5754 if ((idx != i) && idx > 3)
5763 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5764 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5765 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5766 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5767 unsigned TargetMask = 0;
5768 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5769 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5770 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5771 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5772 getShufflePSHUFLWImmediate(SVOp);
5773 V1 = NewV.getOperand(0);
5774 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5778 // If we have SSSE3, and all words of the result are from 1 input vector,
5779 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5780 // is present, fall back to case 4.
5781 if (Subtarget->hasSSSE3()) {
5782 SmallVector<SDValue,16> pshufbMask;
5784 // If we have elements from both input vectors, set the high bit of the
5785 // shuffle mask element to zero out elements that come from V2 in the V1
5786 // mask, and elements that come from V1 in the V2 mask, so that the two
5787 // results can be OR'd together.
5788 bool TwoInputs = V1Used && V2Used;
5789 for (unsigned i = 0; i != 8; ++i) {
5790 int EltIdx = MaskVals[i] * 2;
5791 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5792 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5793 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5794 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5796 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5797 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5798 DAG.getNode(ISD::BUILD_VECTOR, dl,
5799 MVT::v16i8, &pshufbMask[0], 16));
5801 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5803 // Calculate the shuffle mask for the second input, shuffle it, and
5804 // OR it with the first shuffled input.
5806 for (unsigned i = 0; i != 8; ++i) {
5807 int EltIdx = MaskVals[i] * 2;
5808 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5809 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5810 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5811 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5813 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5814 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5815 DAG.getNode(ISD::BUILD_VECTOR, dl,
5816 MVT::v16i8, &pshufbMask[0], 16));
5817 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5818 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5821 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5822 // and update MaskVals with new element order.
5823 std::bitset<8> InOrder;
5824 if (BestLoQuad >= 0) {
5825 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5826 for (int i = 0; i != 4; ++i) {
5827 int idx = MaskVals[i];
5830 } else if ((idx / 4) == BestLoQuad) {
5835 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5838 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5839 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5840 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5842 getShufflePSHUFLWImmediate(SVOp), DAG);
5846 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5847 // and update MaskVals with the new element order.
5848 if (BestHiQuad >= 0) {
5849 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5850 for (unsigned i = 4; i != 8; ++i) {
5851 int idx = MaskVals[i];
5854 } else if ((idx / 4) == BestHiQuad) {
5855 MaskV[i] = (idx & 3) + 4;
5859 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5862 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5863 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5864 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5866 getShufflePSHUFHWImmediate(SVOp), DAG);
5870 // In case BestHi & BestLo were both -1, which means each quadword has a word
5871 // from each of the four input quadwords, calculate the InOrder bitvector now
5872 // before falling through to the insert/extract cleanup.
5873 if (BestLoQuad == -1 && BestHiQuad == -1) {
5875 for (int i = 0; i != 8; ++i)
5876 if (MaskVals[i] < 0 || MaskVals[i] == i)
5880 // The other elements are put in the right place using pextrw and pinsrw.
5881 for (unsigned i = 0; i != 8; ++i) {
5884 int EltIdx = MaskVals[i];
5887 SDValue ExtOp = (EltIdx < 8) ?
5888 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5889 DAG.getIntPtrConstant(EltIdx)) :
5890 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5891 DAG.getIntPtrConstant(EltIdx - 8));
5892 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5893 DAG.getIntPtrConstant(i));
5898 // v16i8 shuffles - Prefer shuffles in the following order:
5899 // 1. [ssse3] 1 x pshufb
5900 // 2. [ssse3] 2 x pshufb + 1 x por
5901 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5903 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5905 const X86TargetLowering &TLI) {
5906 SDValue V1 = SVOp->getOperand(0);
5907 SDValue V2 = SVOp->getOperand(1);
5908 DebugLoc dl = SVOp->getDebugLoc();
5909 ArrayRef<int> MaskVals = SVOp->getMask();
5911 // If we have SSSE3, case 1 is generated when all result bytes come from
5912 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5913 // present, fall back to case 3.
5915 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5916 if (TLI.getSubtarget()->hasSSSE3()) {
5917 SmallVector<SDValue,16> pshufbMask;
5919 // If all result elements are from one input vector, then only translate
5920 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5922 // Otherwise, we have elements from both input vectors, and must zero out
5923 // elements that come from V2 in the first mask, and V1 in the second mask
5924 // so that we can OR them together.
5925 for (unsigned i = 0; i != 16; ++i) {
5926 int EltIdx = MaskVals[i];
5927 if (EltIdx < 0 || EltIdx >= 16)
5929 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5931 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5932 DAG.getNode(ISD::BUILD_VECTOR, dl,
5933 MVT::v16i8, &pshufbMask[0], 16));
5935 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5936 // the 2nd operand if it's undefined or zero.
5937 if (V2.getOpcode() == ISD::UNDEF ||
5938 ISD::isBuildVectorAllZeros(V2.getNode()))
5941 // Calculate the shuffle mask for the second input, shuffle it, and
5942 // OR it with the first shuffled input.
5944 for (unsigned i = 0; i != 16; ++i) {
5945 int EltIdx = MaskVals[i];
5946 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5947 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5949 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5950 DAG.getNode(ISD::BUILD_VECTOR, dl,
5951 MVT::v16i8, &pshufbMask[0], 16));
5952 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5955 // No SSSE3 - Calculate in place words and then fix all out of place words
5956 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5957 // the 16 different words that comprise the two doublequadword input vectors.
5958 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5959 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5961 for (int i = 0; i != 8; ++i) {
5962 int Elt0 = MaskVals[i*2];
5963 int Elt1 = MaskVals[i*2+1];
5965 // This word of the result is all undef, skip it.
5966 if (Elt0 < 0 && Elt1 < 0)
5969 // This word of the result is already in the correct place, skip it.
5970 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5973 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5974 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5977 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5978 // using a single extract together, load it and store it.
5979 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5980 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5981 DAG.getIntPtrConstant(Elt1 / 2));
5982 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5983 DAG.getIntPtrConstant(i));
5987 // If Elt1 is defined, extract it from the appropriate source. If the
5988 // source byte is not also odd, shift the extracted word left 8 bits
5989 // otherwise clear the bottom 8 bits if we need to do an or.
5991 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5992 DAG.getIntPtrConstant(Elt1 / 2));
5993 if ((Elt1 & 1) == 0)
5994 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5996 TLI.getShiftAmountTy(InsElt.getValueType())));
5998 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5999 DAG.getConstant(0xFF00, MVT::i16));
6001 // If Elt0 is defined, extract it from the appropriate source. If the
6002 // source byte is not also even, shift the extracted word right 8 bits. If
6003 // Elt1 was also defined, OR the extracted values together before
6004 // inserting them in the result.
6006 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6007 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6008 if ((Elt0 & 1) != 0)
6009 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6011 TLI.getShiftAmountTy(InsElt0.getValueType())));
6013 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6014 DAG.getConstant(0x00FF, MVT::i16));
6015 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6018 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6019 DAG.getIntPtrConstant(i));
6021 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6024 // v32i8 shuffles - Translate to VPSHUFB if possible.
6026 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6028 const X86TargetLowering &TLI) {
6029 EVT VT = SVOp->getValueType(0);
6030 SDValue V1 = SVOp->getOperand(0);
6031 SDValue V2 = SVOp->getOperand(1);
6032 DebugLoc dl = SVOp->getDebugLoc();
6033 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6035 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6036 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6037 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6039 // VPSHUFB may be generated if
6040 // (1) one of input vector is undefined or zeroinitializer.
6041 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6042 // And (2) the mask indexes don't cross the 128-bit lane.
6043 if (VT != MVT::v32i8 || !TLI.getSubtarget()->hasAVX2() ||
6044 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6047 if (V1IsAllZero && !V2IsAllZero) {
6048 CommuteVectorShuffleMask(MaskVals, 32);
6051 SmallVector<SDValue, 32> pshufbMask;
6052 for (unsigned i = 0; i != 32; i++) {
6053 int EltIdx = MaskVals[i];
6054 if (EltIdx < 0 || EltIdx >= 32)
6057 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6058 // Cross lane is not allowed.
6062 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6064 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6065 DAG.getNode(ISD::BUILD_VECTOR, dl,
6066 MVT::v32i8, &pshufbMask[0], 32));
6069 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6070 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6071 /// done when every pair / quad of shuffle mask elements point to elements in
6072 /// the right sequence. e.g.
6073 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6075 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6076 SelectionDAG &DAG, DebugLoc dl) {
6077 MVT VT = SVOp->getValueType(0).getSimpleVT();
6078 unsigned NumElems = VT.getVectorNumElements();
6081 switch (VT.SimpleTy) {
6082 default: llvm_unreachable("Unexpected!");
6083 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6084 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6085 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6086 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6087 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6088 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6091 SmallVector<int, 8> MaskVec;
6092 for (unsigned i = 0; i != NumElems; i += Scale) {
6094 for (unsigned j = 0; j != Scale; ++j) {
6095 int EltIdx = SVOp->getMaskElt(i+j);
6099 StartIdx = (EltIdx / Scale);
6100 if (EltIdx != (int)(StartIdx*Scale + j))
6103 MaskVec.push_back(StartIdx);
6106 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6107 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6108 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6111 /// getVZextMovL - Return a zero-extending vector move low node.
6113 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6114 SDValue SrcOp, SelectionDAG &DAG,
6115 const X86Subtarget *Subtarget, DebugLoc dl) {
6116 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6117 LoadSDNode *LD = NULL;
6118 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6119 LD = dyn_cast<LoadSDNode>(SrcOp);
6121 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6123 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6124 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6125 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6126 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6127 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6129 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6130 return DAG.getNode(ISD::BITCAST, dl, VT,
6131 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6132 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6140 return DAG.getNode(ISD::BITCAST, dl, VT,
6141 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6142 DAG.getNode(ISD::BITCAST, dl,
6146 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6147 /// which could not be matched by any known target speficic shuffle
6149 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6151 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6152 if (NewOp.getNode())
6155 EVT VT = SVOp->getValueType(0);
6157 unsigned NumElems = VT.getVectorNumElements();
6158 unsigned NumLaneElems = NumElems / 2;
6160 DebugLoc dl = SVOp->getDebugLoc();
6161 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6162 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6165 SmallVector<int, 16> Mask;
6166 for (unsigned l = 0; l < 2; ++l) {
6167 // Build a shuffle mask for the output, discovering on the fly which
6168 // input vectors to use as shuffle operands (recorded in InputUsed).
6169 // If building a suitable shuffle vector proves too hard, then bail
6170 // out with UseBuildVector set.
6171 bool UseBuildVector = false;
6172 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6173 unsigned LaneStart = l * NumLaneElems;
6174 for (unsigned i = 0; i != NumLaneElems; ++i) {
6175 // The mask element. This indexes into the input.
6176 int Idx = SVOp->getMaskElt(i+LaneStart);
6178 // the mask element does not index into any input vector.
6183 // The input vector this mask element indexes into.
6184 int Input = Idx / NumLaneElems;
6186 // Turn the index into an offset from the start of the input vector.
6187 Idx -= Input * NumLaneElems;
6189 // Find or create a shuffle vector operand to hold this input.
6191 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6192 if (InputUsed[OpNo] == Input)
6193 // This input vector is already an operand.
6195 if (InputUsed[OpNo] < 0) {
6196 // Create a new operand for this input vector.
6197 InputUsed[OpNo] = Input;
6202 if (OpNo >= array_lengthof(InputUsed)) {
6203 // More than two input vectors used! Give up on trying to create a
6204 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6205 UseBuildVector = true;
6209 // Add the mask index for the new shuffle vector.
6210 Mask.push_back(Idx + OpNo * NumLaneElems);
6213 if (UseBuildVector) {
6214 SmallVector<SDValue, 16> SVOps;
6215 for (unsigned i = 0; i != NumLaneElems; ++i) {
6216 // The mask element. This indexes into the input.
6217 int Idx = SVOp->getMaskElt(i+LaneStart);
6219 SVOps.push_back(DAG.getUNDEF(EltVT));
6223 // The input vector this mask element indexes into.
6224 int Input = Idx / NumElems;
6226 // Turn the index into an offset from the start of the input vector.
6227 Idx -= Input * NumElems;
6229 // Extract the vector element by hand.
6230 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6231 SVOp->getOperand(Input),
6232 DAG.getIntPtrConstant(Idx)));
6235 // Construct the output using a BUILD_VECTOR.
6236 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6238 } else if (InputUsed[0] < 0) {
6239 // No input vectors were used! The result is undefined.
6240 Output[l] = DAG.getUNDEF(NVT);
6242 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6243 (InputUsed[0] % 2) * NumLaneElems,
6245 // If only one input was used, use an undefined vector for the other.
6246 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6247 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6248 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6249 // At least one input vector was used. Create a new shuffle vector.
6250 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6256 // Concatenate the result back
6257 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6260 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6261 /// 4 elements, and match them with several different shuffle types.
6263 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6264 SDValue V1 = SVOp->getOperand(0);
6265 SDValue V2 = SVOp->getOperand(1);
6266 DebugLoc dl = SVOp->getDebugLoc();
6267 EVT VT = SVOp->getValueType(0);
6269 assert(VT.is128BitVector() && "Unsupported vector size");
6271 std::pair<int, int> Locs[4];
6272 int Mask1[] = { -1, -1, -1, -1 };
6273 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6277 for (unsigned i = 0; i != 4; ++i) {
6278 int Idx = PermMask[i];
6280 Locs[i] = std::make_pair(-1, -1);
6282 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6284 Locs[i] = std::make_pair(0, NumLo);
6288 Locs[i] = std::make_pair(1, NumHi);
6290 Mask1[2+NumHi] = Idx;
6296 if (NumLo <= 2 && NumHi <= 2) {
6297 // If no more than two elements come from either vector. This can be
6298 // implemented with two shuffles. First shuffle gather the elements.
6299 // The second shuffle, which takes the first shuffle as both of its
6300 // vector operands, put the elements into the right order.
6301 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6303 int Mask2[] = { -1, -1, -1, -1 };
6305 for (unsigned i = 0; i != 4; ++i)
6306 if (Locs[i].first != -1) {
6307 unsigned Idx = (i < 2) ? 0 : 4;
6308 Idx += Locs[i].first * 2 + Locs[i].second;
6312 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6315 if (NumLo == 3 || NumHi == 3) {
6316 // Otherwise, we must have three elements from one vector, call it X, and
6317 // one element from the other, call it Y. First, use a shufps to build an
6318 // intermediate vector with the one element from Y and the element from X
6319 // that will be in the same half in the final destination (the indexes don't
6320 // matter). Then, use a shufps to build the final vector, taking the half
6321 // containing the element from Y from the intermediate, and the other half
6324 // Normalize it so the 3 elements come from V1.
6325 CommuteVectorShuffleMask(PermMask, 4);
6329 // Find the element from V2.
6331 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6332 int Val = PermMask[HiIndex];
6339 Mask1[0] = PermMask[HiIndex];
6341 Mask1[2] = PermMask[HiIndex^1];
6343 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6346 Mask1[0] = PermMask[0];
6347 Mask1[1] = PermMask[1];
6348 Mask1[2] = HiIndex & 1 ? 6 : 4;
6349 Mask1[3] = HiIndex & 1 ? 4 : 6;
6350 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6353 Mask1[0] = HiIndex & 1 ? 2 : 0;
6354 Mask1[1] = HiIndex & 1 ? 0 : 2;
6355 Mask1[2] = PermMask[2];
6356 Mask1[3] = PermMask[3];
6361 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6364 // Break it into (shuffle shuffle_hi, shuffle_lo).
6365 int LoMask[] = { -1, -1, -1, -1 };
6366 int HiMask[] = { -1, -1, -1, -1 };
6368 int *MaskPtr = LoMask;
6369 unsigned MaskIdx = 0;
6372 for (unsigned i = 0; i != 4; ++i) {
6379 int Idx = PermMask[i];
6381 Locs[i] = std::make_pair(-1, -1);
6382 } else if (Idx < 4) {
6383 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6384 MaskPtr[LoIdx] = Idx;
6387 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6388 MaskPtr[HiIdx] = Idx;
6393 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6394 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6395 int MaskOps[] = { -1, -1, -1, -1 };
6396 for (unsigned i = 0; i != 4; ++i)
6397 if (Locs[i].first != -1)
6398 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6399 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6402 static bool MayFoldVectorLoad(SDValue V) {
6403 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6404 V = V.getOperand(0);
6405 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6406 V = V.getOperand(0);
6407 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6408 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6409 // BUILD_VECTOR (load), undef
6410 V = V.getOperand(0);
6416 // FIXME: the version above should always be used. Since there's
6417 // a bug where several vector shuffles can't be folded because the
6418 // DAG is not updated during lowering and a node claims to have two
6419 // uses while it only has one, use this version, and let isel match
6420 // another instruction if the load really happens to have more than
6421 // one use. Remove this version after this bug get fixed.
6422 // rdar://8434668, PR8156
6423 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6424 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6425 V = V.getOperand(0);
6426 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6427 V = V.getOperand(0);
6428 if (ISD::isNormalLoad(V.getNode()))
6434 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6435 EVT VT = Op.getValueType();
6437 // Canonizalize to v2f64.
6438 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6439 return DAG.getNode(ISD::BITCAST, dl, VT,
6440 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6445 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6447 SDValue V1 = Op.getOperand(0);
6448 SDValue V2 = Op.getOperand(1);
6449 EVT VT = Op.getValueType();
6451 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6453 if (HasSSE2 && VT == MVT::v2f64)
6454 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6456 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6457 return DAG.getNode(ISD::BITCAST, dl, VT,
6458 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6459 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6460 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6464 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6465 SDValue V1 = Op.getOperand(0);
6466 SDValue V2 = Op.getOperand(1);
6467 EVT VT = Op.getValueType();
6469 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6470 "unsupported shuffle type");
6472 if (V2.getOpcode() == ISD::UNDEF)
6476 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6480 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6481 SDValue V1 = Op.getOperand(0);
6482 SDValue V2 = Op.getOperand(1);
6483 EVT VT = Op.getValueType();
6484 unsigned NumElems = VT.getVectorNumElements();
6486 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6487 // operand of these instructions is only memory, so check if there's a
6488 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6490 bool CanFoldLoad = false;
6492 // Trivial case, when V2 comes from a load.
6493 if (MayFoldVectorLoad(V2))
6496 // When V1 is a load, it can be folded later into a store in isel, example:
6497 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6499 // (MOVLPSmr addr:$src1, VR128:$src2)
6500 // So, recognize this potential and also use MOVLPS or MOVLPD
6501 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6504 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6506 if (HasSSE2 && NumElems == 2)
6507 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6510 // If we don't care about the second element, proceed to use movss.
6511 if (SVOp->getMaskElt(1) != -1)
6512 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6515 // movl and movlp will both match v2i64, but v2i64 is never matched by
6516 // movl earlier because we make it strict to avoid messing with the movlp load
6517 // folding logic (see the code above getMOVLP call). Match it here then,
6518 // this is horrible, but will stay like this until we move all shuffle
6519 // matching to x86 specific nodes. Note that for the 1st condition all
6520 // types are matched with movsd.
6522 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6523 // as to remove this logic from here, as much as possible
6524 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6525 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6526 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6529 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6531 // Invert the operand order and use SHUFPS to match it.
6532 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6533 getShuffleSHUFImmediate(SVOp), DAG);
6537 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6538 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6539 EVT VT = Op.getValueType();
6540 DebugLoc dl = Op.getDebugLoc();
6541 SDValue V1 = Op.getOperand(0);
6542 SDValue V2 = Op.getOperand(1);
6544 if (isZeroShuffle(SVOp))
6545 return getZeroVector(VT, Subtarget, DAG, dl);
6547 // Handle splat operations
6548 if (SVOp->isSplat()) {
6549 unsigned NumElem = VT.getVectorNumElements();
6550 int Size = VT.getSizeInBits();
6552 // Use vbroadcast whenever the splat comes from a foldable load
6553 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6554 if (Broadcast.getNode())
6557 // Handle splats by matching through known shuffle masks
6558 if ((Size == 128 && NumElem <= 4) ||
6559 (Size == 256 && NumElem < 8))
6562 // All remaning splats are promoted to target supported vector shuffles.
6563 return PromoteSplat(SVOp, DAG);
6566 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6568 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6569 VT == MVT::v16i16 || VT == MVT::v32i8) {
6570 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6571 if (NewOp.getNode())
6572 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6573 } else if ((VT == MVT::v4i32 ||
6574 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6575 // FIXME: Figure out a cleaner way to do this.
6576 // Try to make use of movq to zero out the top part.
6577 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6578 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6579 if (NewOp.getNode()) {
6580 EVT NewVT = NewOp.getValueType();
6581 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6582 NewVT, true, false))
6583 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6584 DAG, Subtarget, dl);
6586 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6587 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6588 if (NewOp.getNode()) {
6589 EVT NewVT = NewOp.getValueType();
6590 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6591 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6592 DAG, Subtarget, dl);
6600 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6601 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6602 SDValue V1 = Op.getOperand(0);
6603 SDValue V2 = Op.getOperand(1);
6604 EVT VT = Op.getValueType();
6605 DebugLoc dl = Op.getDebugLoc();
6606 unsigned NumElems = VT.getVectorNumElements();
6607 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6608 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6609 bool V1IsSplat = false;
6610 bool V2IsSplat = false;
6611 bool HasSSE2 = Subtarget->hasSSE2();
6612 bool HasAVX = Subtarget->hasAVX();
6613 bool HasAVX2 = Subtarget->hasAVX2();
6614 MachineFunction &MF = DAG.getMachineFunction();
6615 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6617 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6619 if (V1IsUndef && V2IsUndef)
6620 return DAG.getUNDEF(VT);
6622 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6624 // Vector shuffle lowering takes 3 steps:
6626 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6627 // narrowing and commutation of operands should be handled.
6628 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6630 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6631 // so the shuffle can be broken into other shuffles and the legalizer can
6632 // try the lowering again.
6634 // The general idea is that no vector_shuffle operation should be left to
6635 // be matched during isel, all of them must be converted to a target specific
6638 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6639 // narrowing and commutation of operands should be handled. The actual code
6640 // doesn't include all of those, work in progress...
6641 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6642 if (NewOp.getNode())
6645 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6647 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6648 // unpckh_undef). Only use pshufd if speed is more important than size.
6649 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6650 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6651 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6652 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6654 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6655 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6656 return getMOVDDup(Op, dl, V1, DAG);
6658 if (isMOVHLPS_v_undef_Mask(M, VT))
6659 return getMOVHighToLow(Op, dl, DAG);
6661 // Use to match splats
6662 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6663 (VT == MVT::v2f64 || VT == MVT::v2i64))
6664 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6666 if (isPSHUFDMask(M, VT)) {
6667 // The actual implementation will match the mask in the if above and then
6668 // during isel it can match several different instructions, not only pshufd
6669 // as its name says, sad but true, emulate the behavior for now...
6670 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6671 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6673 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6675 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6676 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6678 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6679 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6681 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6685 // Check if this can be converted into a logical shift.
6686 bool isLeft = false;
6689 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6690 if (isShift && ShVal.hasOneUse()) {
6691 // If the shifted value has multiple uses, it may be cheaper to use
6692 // v_set0 + movlhps or movhlps, etc.
6693 EVT EltVT = VT.getVectorElementType();
6694 ShAmt *= EltVT.getSizeInBits();
6695 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6698 if (isMOVLMask(M, VT)) {
6699 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6700 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6701 if (!isMOVLPMask(M, VT)) {
6702 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6703 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6705 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6706 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6710 // FIXME: fold these into legal mask.
6711 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6712 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6714 if (isMOVHLPSMask(M, VT))
6715 return getMOVHighToLow(Op, dl, DAG);
6717 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6718 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6720 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6721 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6723 if (isMOVLPMask(M, VT))
6724 return getMOVLP(Op, dl, DAG, HasSSE2);
6726 if (ShouldXformToMOVHLPS(M, VT) ||
6727 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6728 return CommuteVectorShuffle(SVOp, DAG);
6731 // No better options. Use a vshldq / vsrldq.
6732 EVT EltVT = VT.getVectorElementType();
6733 ShAmt *= EltVT.getSizeInBits();
6734 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6737 bool Commuted = false;
6738 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6739 // 1,1,1,1 -> v8i16 though.
6740 V1IsSplat = isSplatVector(V1.getNode());
6741 V2IsSplat = isSplatVector(V2.getNode());
6743 // Canonicalize the splat or undef, if present, to be on the RHS.
6744 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6745 CommuteVectorShuffleMask(M, NumElems);
6747 std::swap(V1IsSplat, V2IsSplat);
6751 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6752 // Shuffling low element of v1 into undef, just return v1.
6755 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6756 // the instruction selector will not match, so get a canonical MOVL with
6757 // swapped operands to undo the commute.
6758 return getMOVL(DAG, dl, VT, V2, V1);
6761 if (isUNPCKLMask(M, VT, HasAVX2))
6762 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6764 if (isUNPCKHMask(M, VT, HasAVX2))
6765 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6768 // Normalize mask so all entries that point to V2 points to its first
6769 // element then try to match unpck{h|l} again. If match, return a
6770 // new vector_shuffle with the corrected mask.p
6771 SmallVector<int, 8> NewMask(M.begin(), M.end());
6772 NormalizeMask(NewMask, NumElems);
6773 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6774 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6775 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6776 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6780 // Commute is back and try unpck* again.
6781 // FIXME: this seems wrong.
6782 CommuteVectorShuffleMask(M, NumElems);
6784 std::swap(V1IsSplat, V2IsSplat);
6787 if (isUNPCKLMask(M, VT, HasAVX2))
6788 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6790 if (isUNPCKHMask(M, VT, HasAVX2))
6791 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6794 // Normalize the node to match x86 shuffle ops if needed
6795 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6796 return CommuteVectorShuffle(SVOp, DAG);
6798 // The checks below are all present in isShuffleMaskLegal, but they are
6799 // inlined here right now to enable us to directly emit target specific
6800 // nodes, and remove one by one until they don't return Op anymore.
6802 if (isPALIGNRMask(M, VT, Subtarget))
6803 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6804 getShufflePALIGNRImmediate(SVOp),
6807 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6808 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6809 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6810 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6813 if (isPSHUFHWMask(M, VT, HasAVX2))
6814 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6815 getShufflePSHUFHWImmediate(SVOp),
6818 if (isPSHUFLWMask(M, VT, HasAVX2))
6819 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6820 getShufflePSHUFLWImmediate(SVOp),
6823 if (isSHUFPMask(M, VT, HasAVX))
6824 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6825 getShuffleSHUFImmediate(SVOp), DAG);
6827 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6828 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6829 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6830 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6832 //===--------------------------------------------------------------------===//
6833 // Generate target specific nodes for 128 or 256-bit shuffles only
6834 // supported in the AVX instruction set.
6837 // Handle VMOVDDUPY permutations
6838 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6839 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6841 // Handle VPERMILPS/D* permutations
6842 if (isVPERMILPMask(M, VT, HasAVX)) {
6843 if (HasAVX2 && VT == MVT::v8i32)
6844 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6845 getShuffleSHUFImmediate(SVOp), DAG);
6846 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6847 getShuffleSHUFImmediate(SVOp), DAG);
6850 // Handle VPERM2F128/VPERM2I128 permutations
6851 if (isVPERM2X128Mask(M, VT, HasAVX))
6852 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6853 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6855 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6856 if (BlendOp.getNode())
6859 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6860 SmallVector<SDValue, 8> permclMask;
6861 for (unsigned i = 0; i != 8; ++i) {
6862 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6864 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6866 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6867 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6868 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6871 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6872 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6873 getShuffleCLImmediate(SVOp), DAG);
6876 //===--------------------------------------------------------------------===//
6877 // Since no target specific shuffle was selected for this generic one,
6878 // lower it into other known shuffles. FIXME: this isn't true yet, but
6879 // this is the plan.
6882 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6883 if (VT == MVT::v8i16) {
6884 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6885 if (NewOp.getNode())
6889 if (VT == MVT::v16i8) {
6890 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6891 if (NewOp.getNode())
6895 if (VT == MVT::v32i8) {
6896 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, DAG, *this);
6897 if (NewOp.getNode())
6901 // Handle all 128-bit wide vectors with 4 elements, and match them with
6902 // several different shuffle types.
6903 if (NumElems == 4 && VT.is128BitVector())
6904 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6906 // Handle general 256-bit shuffles
6907 if (VT.is256BitVector())
6908 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6914 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6915 SelectionDAG &DAG) const {
6916 EVT VT = Op.getValueType();
6917 DebugLoc dl = Op.getDebugLoc();
6919 if (!Op.getOperand(0).getValueType().is128BitVector())
6922 if (VT.getSizeInBits() == 8) {
6923 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6924 Op.getOperand(0), Op.getOperand(1));
6925 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6926 DAG.getValueType(VT));
6927 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6930 if (VT.getSizeInBits() == 16) {
6931 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6932 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6934 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6935 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6936 DAG.getNode(ISD::BITCAST, dl,
6940 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6941 Op.getOperand(0), Op.getOperand(1));
6942 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6943 DAG.getValueType(VT));
6944 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6947 if (VT == MVT::f32) {
6948 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6949 // the result back to FR32 register. It's only worth matching if the
6950 // result has a single use which is a store or a bitcast to i32. And in
6951 // the case of a store, it's not worth it if the index is a constant 0,
6952 // because a MOVSSmr can be used instead, which is smaller and faster.
6953 if (!Op.hasOneUse())
6955 SDNode *User = *Op.getNode()->use_begin();
6956 if ((User->getOpcode() != ISD::STORE ||
6957 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6958 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6959 (User->getOpcode() != ISD::BITCAST ||
6960 User->getValueType(0) != MVT::i32))
6962 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6963 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6966 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6969 if (VT == MVT::i32 || VT == MVT::i64) {
6970 // ExtractPS/pextrq works with constant index.
6971 if (isa<ConstantSDNode>(Op.getOperand(1)))
6979 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6980 SelectionDAG &DAG) const {
6981 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6984 SDValue Vec = Op.getOperand(0);
6985 EVT VecVT = Vec.getValueType();
6987 // If this is a 256-bit vector result, first extract the 128-bit vector and
6988 // then extract the element from the 128-bit vector.
6989 if (VecVT.is256BitVector()) {
6990 DebugLoc dl = Op.getNode()->getDebugLoc();
6991 unsigned NumElems = VecVT.getVectorNumElements();
6992 SDValue Idx = Op.getOperand(1);
6993 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6995 // Get the 128-bit vector.
6996 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6998 if (IdxVal >= NumElems/2)
6999 IdxVal -= NumElems/2;
7000 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7001 DAG.getConstant(IdxVal, MVT::i32));
7004 assert(VecVT.is128BitVector() && "Unexpected vector length");
7006 if (Subtarget->hasSSE41()) {
7007 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7012 EVT VT = Op.getValueType();
7013 DebugLoc dl = Op.getDebugLoc();
7014 // TODO: handle v16i8.
7015 if (VT.getSizeInBits() == 16) {
7016 SDValue Vec = Op.getOperand(0);
7017 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7019 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7020 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7021 DAG.getNode(ISD::BITCAST, dl,
7024 // Transform it so it match pextrw which produces a 32-bit result.
7025 EVT EltVT = MVT::i32;
7026 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7027 Op.getOperand(0), Op.getOperand(1));
7028 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7029 DAG.getValueType(VT));
7030 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7033 if (VT.getSizeInBits() == 32) {
7034 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7038 // SHUFPS the element to the lowest double word, then movss.
7039 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7040 EVT VVT = Op.getOperand(0).getValueType();
7041 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7042 DAG.getUNDEF(VVT), Mask);
7043 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7044 DAG.getIntPtrConstant(0));
7047 if (VT.getSizeInBits() == 64) {
7048 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7049 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7050 // to match extract_elt for f64.
7051 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7055 // UNPCKHPD the element to the lowest double word, then movsd.
7056 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7057 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7058 int Mask[2] = { 1, -1 };
7059 EVT VVT = Op.getOperand(0).getValueType();
7060 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7061 DAG.getUNDEF(VVT), Mask);
7062 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7063 DAG.getIntPtrConstant(0));
7070 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7071 SelectionDAG &DAG) const {
7072 EVT VT = Op.getValueType();
7073 EVT EltVT = VT.getVectorElementType();
7074 DebugLoc dl = Op.getDebugLoc();
7076 SDValue N0 = Op.getOperand(0);
7077 SDValue N1 = Op.getOperand(1);
7078 SDValue N2 = Op.getOperand(2);
7080 if (!VT.is128BitVector())
7083 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7084 isa<ConstantSDNode>(N2)) {
7086 if (VT == MVT::v8i16)
7087 Opc = X86ISD::PINSRW;
7088 else if (VT == MVT::v16i8)
7089 Opc = X86ISD::PINSRB;
7091 Opc = X86ISD::PINSRB;
7093 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7095 if (N1.getValueType() != MVT::i32)
7096 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7097 if (N2.getValueType() != MVT::i32)
7098 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7099 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7102 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7103 // Bits [7:6] of the constant are the source select. This will always be
7104 // zero here. The DAG Combiner may combine an extract_elt index into these
7105 // bits. For example (insert (extract, 3), 2) could be matched by putting
7106 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7107 // Bits [5:4] of the constant are the destination select. This is the
7108 // value of the incoming immediate.
7109 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7110 // combine either bitwise AND or insert of float 0.0 to set these bits.
7111 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7112 // Create this as a scalar to vector..
7113 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7114 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7117 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7118 // PINSR* works with constant index.
7125 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7126 EVT VT = Op.getValueType();
7127 EVT EltVT = VT.getVectorElementType();
7129 DebugLoc dl = Op.getDebugLoc();
7130 SDValue N0 = Op.getOperand(0);
7131 SDValue N1 = Op.getOperand(1);
7132 SDValue N2 = Op.getOperand(2);
7134 // If this is a 256-bit vector result, first extract the 128-bit vector,
7135 // insert the element into the extracted half and then place it back.
7136 if (VT.is256BitVector()) {
7137 if (!isa<ConstantSDNode>(N2))
7140 // Get the desired 128-bit vector half.
7141 unsigned NumElems = VT.getVectorNumElements();
7142 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7143 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7145 // Insert the element into the desired half.
7146 bool Upper = IdxVal >= NumElems/2;
7147 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7148 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7150 // Insert the changed part back to the 256-bit vector
7151 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7154 if (Subtarget->hasSSE41())
7155 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7157 if (EltVT == MVT::i8)
7160 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7161 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7162 // as its second argument.
7163 if (N1.getValueType() != MVT::i32)
7164 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7165 if (N2.getValueType() != MVT::i32)
7166 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7167 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7173 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7174 LLVMContext *Context = DAG.getContext();
7175 DebugLoc dl = Op.getDebugLoc();
7176 EVT OpVT = Op.getValueType();
7178 // If this is a 256-bit vector result, first insert into a 128-bit
7179 // vector and then insert into the 256-bit vector.
7180 if (!OpVT.is128BitVector()) {
7181 // Insert into a 128-bit vector.
7182 EVT VT128 = EVT::getVectorVT(*Context,
7183 OpVT.getVectorElementType(),
7184 OpVT.getVectorNumElements() / 2);
7186 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7188 // Insert the 128-bit vector.
7189 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7192 if (OpVT == MVT::v1i64 &&
7193 Op.getOperand(0).getValueType() == MVT::i64)
7194 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7196 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7197 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7198 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7199 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7202 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7203 // a simple subregister reference or explicit instructions to grab
7204 // upper bits of a vector.
7206 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7207 if (Subtarget->hasAVX()) {
7208 DebugLoc dl = Op.getNode()->getDebugLoc();
7209 SDValue Vec = Op.getNode()->getOperand(0);
7210 SDValue Idx = Op.getNode()->getOperand(1);
7212 if (Op.getNode()->getValueType(0).is128BitVector() &&
7213 Vec.getNode()->getValueType(0).is256BitVector() &&
7214 isa<ConstantSDNode>(Idx)) {
7215 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7216 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7222 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7223 // simple superregister reference or explicit instructions to insert
7224 // the upper bits of a vector.
7226 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7227 if (Subtarget->hasAVX()) {
7228 DebugLoc dl = Op.getNode()->getDebugLoc();
7229 SDValue Vec = Op.getNode()->getOperand(0);
7230 SDValue SubVec = Op.getNode()->getOperand(1);
7231 SDValue Idx = Op.getNode()->getOperand(2);
7233 if (Op.getNode()->getValueType(0).is256BitVector() &&
7234 SubVec.getNode()->getValueType(0).is128BitVector() &&
7235 isa<ConstantSDNode>(Idx)) {
7236 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7237 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7243 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7244 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7245 // one of the above mentioned nodes. It has to be wrapped because otherwise
7246 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7247 // be used to form addressing mode. These wrapped nodes will be selected
7250 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7251 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7253 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7255 unsigned char OpFlag = 0;
7256 unsigned WrapperKind = X86ISD::Wrapper;
7257 CodeModel::Model M = getTargetMachine().getCodeModel();
7259 if (Subtarget->isPICStyleRIPRel() &&
7260 (M == CodeModel::Small || M == CodeModel::Kernel))
7261 WrapperKind = X86ISD::WrapperRIP;
7262 else if (Subtarget->isPICStyleGOT())
7263 OpFlag = X86II::MO_GOTOFF;
7264 else if (Subtarget->isPICStyleStubPIC())
7265 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7267 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7269 CP->getOffset(), OpFlag);
7270 DebugLoc DL = CP->getDebugLoc();
7271 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7272 // With PIC, the address is actually $g + Offset.
7274 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7275 DAG.getNode(X86ISD::GlobalBaseReg,
7276 DebugLoc(), getPointerTy()),
7283 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7284 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7286 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7288 unsigned char OpFlag = 0;
7289 unsigned WrapperKind = X86ISD::Wrapper;
7290 CodeModel::Model M = getTargetMachine().getCodeModel();
7292 if (Subtarget->isPICStyleRIPRel() &&
7293 (M == CodeModel::Small || M == CodeModel::Kernel))
7294 WrapperKind = X86ISD::WrapperRIP;
7295 else if (Subtarget->isPICStyleGOT())
7296 OpFlag = X86II::MO_GOTOFF;
7297 else if (Subtarget->isPICStyleStubPIC())
7298 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7300 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7302 DebugLoc DL = JT->getDebugLoc();
7303 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7305 // With PIC, the address is actually $g + Offset.
7307 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7308 DAG.getNode(X86ISD::GlobalBaseReg,
7309 DebugLoc(), getPointerTy()),
7316 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7317 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7319 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7321 unsigned char OpFlag = 0;
7322 unsigned WrapperKind = X86ISD::Wrapper;
7323 CodeModel::Model M = getTargetMachine().getCodeModel();
7325 if (Subtarget->isPICStyleRIPRel() &&
7326 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7327 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7328 OpFlag = X86II::MO_GOTPCREL;
7329 WrapperKind = X86ISD::WrapperRIP;
7330 } else if (Subtarget->isPICStyleGOT()) {
7331 OpFlag = X86II::MO_GOT;
7332 } else if (Subtarget->isPICStyleStubPIC()) {
7333 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7334 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7335 OpFlag = X86II::MO_DARWIN_NONLAZY;
7338 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7340 DebugLoc DL = Op.getDebugLoc();
7341 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7344 // With PIC, the address is actually $g + Offset.
7345 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7346 !Subtarget->is64Bit()) {
7347 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7348 DAG.getNode(X86ISD::GlobalBaseReg,
7349 DebugLoc(), getPointerTy()),
7353 // For symbols that require a load from a stub to get the address, emit the
7355 if (isGlobalStubReference(OpFlag))
7356 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7357 MachinePointerInfo::getGOT(), false, false, false, 0);
7363 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7364 // Create the TargetBlockAddressAddress node.
7365 unsigned char OpFlags =
7366 Subtarget->ClassifyBlockAddressReference();
7367 CodeModel::Model M = getTargetMachine().getCodeModel();
7368 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7369 DebugLoc dl = Op.getDebugLoc();
7370 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7371 /*isTarget=*/true, OpFlags);
7373 if (Subtarget->isPICStyleRIPRel() &&
7374 (M == CodeModel::Small || M == CodeModel::Kernel))
7375 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7377 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7379 // With PIC, the address is actually $g + Offset.
7380 if (isGlobalRelativeToPICBase(OpFlags)) {
7381 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7382 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7390 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7392 SelectionDAG &DAG) const {
7393 // Create the TargetGlobalAddress node, folding in the constant
7394 // offset if it is legal.
7395 unsigned char OpFlags =
7396 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7397 CodeModel::Model M = getTargetMachine().getCodeModel();
7399 if (OpFlags == X86II::MO_NO_FLAG &&
7400 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7401 // A direct static reference to a global.
7402 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7405 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7408 if (Subtarget->isPICStyleRIPRel() &&
7409 (M == CodeModel::Small || M == CodeModel::Kernel))
7410 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7412 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7414 // With PIC, the address is actually $g + Offset.
7415 if (isGlobalRelativeToPICBase(OpFlags)) {
7416 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7417 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7421 // For globals that require a load from a stub to get the address, emit the
7423 if (isGlobalStubReference(OpFlags))
7424 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7425 MachinePointerInfo::getGOT(), false, false, false, 0);
7427 // If there was a non-zero offset that we didn't fold, create an explicit
7430 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7431 DAG.getConstant(Offset, getPointerTy()));
7437 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7438 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7439 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7440 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7444 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7445 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7446 unsigned char OperandFlags, bool LocalDynamic = false) {
7447 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7448 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7449 DebugLoc dl = GA->getDebugLoc();
7450 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7451 GA->getValueType(0),
7455 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7459 SDValue Ops[] = { Chain, TGA, *InFlag };
7460 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7462 SDValue Ops[] = { Chain, TGA };
7463 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7466 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7467 MFI->setAdjustsStack(true);
7469 SDValue Flag = Chain.getValue(1);
7470 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7473 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7475 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7478 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7479 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7480 DAG.getNode(X86ISD::GlobalBaseReg,
7481 DebugLoc(), PtrVT), InFlag);
7482 InFlag = Chain.getValue(1);
7484 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7487 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7489 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7491 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7492 X86::RAX, X86II::MO_TLSGD);
7495 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7499 DebugLoc dl = GA->getDebugLoc();
7501 // Get the start address of the TLS block for this module.
7502 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7503 .getInfo<X86MachineFunctionInfo>();
7504 MFI->incNumLocalDynamicTLSAccesses();
7508 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7509 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7512 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7513 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7514 InFlag = Chain.getValue(1);
7515 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7516 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7519 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7523 unsigned char OperandFlags = X86II::MO_DTPOFF;
7524 unsigned WrapperKind = X86ISD::Wrapper;
7525 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7526 GA->getValueType(0),
7527 GA->getOffset(), OperandFlags);
7528 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7530 // Add x@dtpoff with the base.
7531 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7534 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7535 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7536 const EVT PtrVT, TLSModel::Model model,
7537 bool is64Bit, bool isPIC) {
7538 DebugLoc dl = GA->getDebugLoc();
7540 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7541 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7542 is64Bit ? 257 : 256));
7544 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7545 DAG.getIntPtrConstant(0),
7546 MachinePointerInfo(Ptr),
7547 false, false, false, 0);
7549 unsigned char OperandFlags = 0;
7550 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7552 unsigned WrapperKind = X86ISD::Wrapper;
7553 if (model == TLSModel::LocalExec) {
7554 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7555 } else if (model == TLSModel::InitialExec) {
7557 OperandFlags = X86II::MO_GOTTPOFF;
7558 WrapperKind = X86ISD::WrapperRIP;
7560 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7563 llvm_unreachable("Unexpected model");
7566 // emit "addl x@ntpoff,%eax" (local exec)
7567 // or "addl x@indntpoff,%eax" (initial exec)
7568 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7569 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7570 GA->getValueType(0),
7571 GA->getOffset(), OperandFlags);
7572 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7574 if (model == TLSModel::InitialExec) {
7575 if (isPIC && !is64Bit) {
7576 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7577 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7581 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7582 MachinePointerInfo::getGOT(), false, false, false,
7586 // The address of the thread local variable is the add of the thread
7587 // pointer with the offset of the variable.
7588 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7592 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7594 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7595 const GlobalValue *GV = GA->getGlobal();
7597 if (Subtarget->isTargetELF()) {
7598 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7601 case TLSModel::GeneralDynamic:
7602 if (Subtarget->is64Bit())
7603 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7604 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7605 case TLSModel::LocalDynamic:
7606 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7607 Subtarget->is64Bit());
7608 case TLSModel::InitialExec:
7609 case TLSModel::LocalExec:
7610 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7611 Subtarget->is64Bit(),
7612 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7614 llvm_unreachable("Unknown TLS model.");
7617 if (Subtarget->isTargetDarwin()) {
7618 // Darwin only has one model of TLS. Lower to that.
7619 unsigned char OpFlag = 0;
7620 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7621 X86ISD::WrapperRIP : X86ISD::Wrapper;
7623 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7625 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7626 !Subtarget->is64Bit();
7628 OpFlag = X86II::MO_TLVP_PIC_BASE;
7630 OpFlag = X86II::MO_TLVP;
7631 DebugLoc DL = Op.getDebugLoc();
7632 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7633 GA->getValueType(0),
7634 GA->getOffset(), OpFlag);
7635 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7637 // With PIC32, the address is actually $g + Offset.
7639 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7640 DAG.getNode(X86ISD::GlobalBaseReg,
7641 DebugLoc(), getPointerTy()),
7644 // Lowering the machine isd will make sure everything is in the right
7646 SDValue Chain = DAG.getEntryNode();
7647 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7648 SDValue Args[] = { Chain, Offset };
7649 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7651 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7652 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7653 MFI->setAdjustsStack(true);
7655 // And our return value (tls address) is in the standard call return value
7657 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7658 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7662 if (Subtarget->isTargetWindows()) {
7663 // Just use the implicit TLS architecture
7664 // Need to generate someting similar to:
7665 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7667 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7668 // mov rcx, qword [rdx+rcx*8]
7669 // mov eax, .tls$:tlsvar
7670 // [rax+rcx] contains the address
7671 // Windows 64bit: gs:0x58
7672 // Windows 32bit: fs:__tls_array
7674 // If GV is an alias then use the aliasee for determining
7675 // thread-localness.
7676 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7677 GV = GA->resolveAliasedGlobal(false);
7678 DebugLoc dl = GA->getDebugLoc();
7679 SDValue Chain = DAG.getEntryNode();
7681 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7682 // %gs:0x58 (64-bit).
7683 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7684 ? Type::getInt8PtrTy(*DAG.getContext(),
7686 : Type::getInt32PtrTy(*DAG.getContext(),
7689 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7690 Subtarget->is64Bit()
7691 ? DAG.getIntPtrConstant(0x58)
7692 : DAG.getExternalSymbol("_tls_array",
7694 MachinePointerInfo(Ptr),
7695 false, false, false, 0);
7697 // Load the _tls_index variable
7698 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7699 if (Subtarget->is64Bit())
7700 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7701 IDX, MachinePointerInfo(), MVT::i32,
7704 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7705 false, false, false, 0);
7707 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7709 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7711 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7712 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7713 false, false, false, 0);
7715 // Get the offset of start of .tls section
7716 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7717 GA->getValueType(0),
7718 GA->getOffset(), X86II::MO_SECREL);
7719 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7721 // The address of the thread local variable is the add of the thread
7722 // pointer with the offset of the variable.
7723 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7726 llvm_unreachable("TLS not implemented for this target.");
7730 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7731 /// and take a 2 x i32 value to shift plus a shift amount.
7732 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7733 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7734 EVT VT = Op.getValueType();
7735 unsigned VTBits = VT.getSizeInBits();
7736 DebugLoc dl = Op.getDebugLoc();
7737 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7738 SDValue ShOpLo = Op.getOperand(0);
7739 SDValue ShOpHi = Op.getOperand(1);
7740 SDValue ShAmt = Op.getOperand(2);
7741 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7742 DAG.getConstant(VTBits - 1, MVT::i8))
7743 : DAG.getConstant(0, VT);
7746 if (Op.getOpcode() == ISD::SHL_PARTS) {
7747 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7748 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7750 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7751 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7754 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7755 DAG.getConstant(VTBits, MVT::i8));
7756 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7757 AndNode, DAG.getConstant(0, MVT::i8));
7760 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7761 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7762 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7764 if (Op.getOpcode() == ISD::SHL_PARTS) {
7765 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7766 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7768 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7769 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7772 SDValue Ops[2] = { Lo, Hi };
7773 return DAG.getMergeValues(Ops, 2, dl);
7776 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7777 SelectionDAG &DAG) const {
7778 EVT SrcVT = Op.getOperand(0).getValueType();
7780 if (SrcVT.isVector())
7783 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7784 "Unknown SINT_TO_FP to lower!");
7786 // These are really Legal; return the operand so the caller accepts it as
7788 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7790 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7791 Subtarget->is64Bit()) {
7795 DebugLoc dl = Op.getDebugLoc();
7796 unsigned Size = SrcVT.getSizeInBits()/8;
7797 MachineFunction &MF = DAG.getMachineFunction();
7798 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7799 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7800 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7802 MachinePointerInfo::getFixedStack(SSFI),
7804 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7807 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7809 SelectionDAG &DAG) const {
7811 DebugLoc DL = Op.getDebugLoc();
7813 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7815 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7817 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7819 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7821 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7822 MachineMemOperand *MMO;
7824 int SSFI = FI->getIndex();
7826 DAG.getMachineFunction()
7827 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7828 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7830 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7831 StackSlot = StackSlot.getOperand(1);
7833 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7834 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7836 Tys, Ops, array_lengthof(Ops),
7840 Chain = Result.getValue(1);
7841 SDValue InFlag = Result.getValue(2);
7843 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7844 // shouldn't be necessary except that RFP cannot be live across
7845 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7846 MachineFunction &MF = DAG.getMachineFunction();
7847 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7848 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7849 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7850 Tys = DAG.getVTList(MVT::Other);
7852 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7854 MachineMemOperand *MMO =
7855 DAG.getMachineFunction()
7856 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7857 MachineMemOperand::MOStore, SSFISize, SSFISize);
7859 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7860 Ops, array_lengthof(Ops),
7861 Op.getValueType(), MMO);
7862 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7863 MachinePointerInfo::getFixedStack(SSFI),
7864 false, false, false, 0);
7870 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7871 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7872 SelectionDAG &DAG) const {
7873 // This algorithm is not obvious. Here it is what we're trying to output:
7876 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7877 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7881 pshufd $0x4e, %xmm0, %xmm1
7886 DebugLoc dl = Op.getDebugLoc();
7887 LLVMContext *Context = DAG.getContext();
7889 // Build some magic constants.
7890 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7891 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7892 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7894 SmallVector<Constant*,2> CV1;
7896 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7898 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7899 Constant *C1 = ConstantVector::get(CV1);
7900 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7902 // Load the 64-bit value into an XMM register.
7903 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7905 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7906 MachinePointerInfo::getConstantPool(),
7907 false, false, false, 16);
7908 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7909 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7912 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7913 MachinePointerInfo::getConstantPool(),
7914 false, false, false, 16);
7915 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7916 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7919 if (Subtarget->hasSSE3()) {
7920 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7921 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7923 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7924 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7926 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7927 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7931 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7932 DAG.getIntPtrConstant(0));
7935 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7936 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7937 SelectionDAG &DAG) const {
7938 DebugLoc dl = Op.getDebugLoc();
7939 // FP constant to bias correct the final result.
7940 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7943 // Load the 32-bit value into an XMM register.
7944 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7947 // Zero out the upper parts of the register.
7948 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7950 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7951 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7952 DAG.getIntPtrConstant(0));
7954 // Or the load with the bias.
7955 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7956 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7957 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7959 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7960 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7961 MVT::v2f64, Bias)));
7962 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7963 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7964 DAG.getIntPtrConstant(0));
7966 // Subtract the bias.
7967 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7969 // Handle final rounding.
7970 EVT DestVT = Op.getValueType();
7972 if (DestVT.bitsLT(MVT::f64))
7973 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7974 DAG.getIntPtrConstant(0));
7975 if (DestVT.bitsGT(MVT::f64))
7976 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7978 // Handle final rounding.
7982 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7983 SelectionDAG &DAG) const {
7984 SDValue N0 = Op.getOperand(0);
7985 DebugLoc dl = Op.getDebugLoc();
7987 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7988 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7989 // the optimization here.
7990 if (DAG.SignBitIsZero(N0))
7991 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7993 EVT SrcVT = N0.getValueType();
7994 EVT DstVT = Op.getValueType();
7995 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7996 return LowerUINT_TO_FP_i64(Op, DAG);
7997 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7998 return LowerUINT_TO_FP_i32(Op, DAG);
7999 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8002 // Make a 64-bit buffer, and use it to build an FILD.
8003 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8004 if (SrcVT == MVT::i32) {
8005 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8006 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8007 getPointerTy(), StackSlot, WordOff);
8008 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8009 StackSlot, MachinePointerInfo(),
8011 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8012 OffsetSlot, MachinePointerInfo(),
8014 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8018 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8019 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8020 StackSlot, MachinePointerInfo(),
8022 // For i64 source, we need to add the appropriate power of 2 if the input
8023 // was negative. This is the same as the optimization in
8024 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8025 // we must be careful to do the computation in x87 extended precision, not
8026 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8027 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8028 MachineMemOperand *MMO =
8029 DAG.getMachineFunction()
8030 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8031 MachineMemOperand::MOLoad, 8, 8);
8033 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8034 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8035 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8038 APInt FF(32, 0x5F800000ULL);
8040 // Check whether the sign bit is set.
8041 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8042 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8045 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8046 SDValue FudgePtr = DAG.getConstantPool(
8047 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8050 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8051 SDValue Zero = DAG.getIntPtrConstant(0);
8052 SDValue Four = DAG.getIntPtrConstant(4);
8053 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8055 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8057 // Load the value out, extending it from f32 to f80.
8058 // FIXME: Avoid the extend by constructing the right constant pool?
8059 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8060 FudgePtr, MachinePointerInfo::getConstantPool(),
8061 MVT::f32, false, false, 4);
8062 // Extend everything to 80 bits to force it to be done on x87.
8063 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8064 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8067 std::pair<SDValue,SDValue> X86TargetLowering::
8068 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8069 DebugLoc DL = Op.getDebugLoc();
8071 EVT DstTy = Op.getValueType();
8073 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8074 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8078 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8079 DstTy.getSimpleVT() >= MVT::i16 &&
8080 "Unknown FP_TO_INT to lower!");
8082 // These are really Legal.
8083 if (DstTy == MVT::i32 &&
8084 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8085 return std::make_pair(SDValue(), SDValue());
8086 if (Subtarget->is64Bit() &&
8087 DstTy == MVT::i64 &&
8088 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8089 return std::make_pair(SDValue(), SDValue());
8091 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8092 // stack slot, or into the FTOL runtime function.
8093 MachineFunction &MF = DAG.getMachineFunction();
8094 unsigned MemSize = DstTy.getSizeInBits()/8;
8095 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8096 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8099 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8100 Opc = X86ISD::WIN_FTOL;
8102 switch (DstTy.getSimpleVT().SimpleTy) {
8103 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8104 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8105 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8106 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8109 SDValue Chain = DAG.getEntryNode();
8110 SDValue Value = Op.getOperand(0);
8111 EVT TheVT = Op.getOperand(0).getValueType();
8112 // FIXME This causes a redundant load/store if the SSE-class value is already
8113 // in memory, such as if it is on the callstack.
8114 if (isScalarFPTypeInSSEReg(TheVT)) {
8115 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8116 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8117 MachinePointerInfo::getFixedStack(SSFI),
8119 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8121 Chain, StackSlot, DAG.getValueType(TheVT)
8124 MachineMemOperand *MMO =
8125 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8126 MachineMemOperand::MOLoad, MemSize, MemSize);
8127 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8129 Chain = Value.getValue(1);
8130 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8131 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8134 MachineMemOperand *MMO =
8135 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8136 MachineMemOperand::MOStore, MemSize, MemSize);
8138 if (Opc != X86ISD::WIN_FTOL) {
8139 // Build the FP_TO_INT*_IN_MEM
8140 SDValue Ops[] = { Chain, Value, StackSlot };
8141 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8142 Ops, 3, DstTy, MMO);
8143 return std::make_pair(FIST, StackSlot);
8145 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8146 DAG.getVTList(MVT::Other, MVT::Glue),
8148 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8149 MVT::i32, ftol.getValue(1));
8150 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8151 MVT::i32, eax.getValue(2));
8152 SDValue Ops[] = { eax, edx };
8153 SDValue pair = IsReplace
8154 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8155 : DAG.getMergeValues(Ops, 2, DL);
8156 return std::make_pair(pair, SDValue());
8160 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8161 SelectionDAG &DAG) const {
8162 if (Op.getValueType().isVector())
8165 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8166 /*IsSigned=*/ true, /*IsReplace=*/ false);
8167 SDValue FIST = Vals.first, StackSlot = Vals.second;
8168 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8169 if (FIST.getNode() == 0) return Op;
8171 if (StackSlot.getNode())
8173 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8174 FIST, StackSlot, MachinePointerInfo(),
8175 false, false, false, 0);
8177 // The node is the result.
8181 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8182 SelectionDAG &DAG) const {
8183 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8184 /*IsSigned=*/ false, /*IsReplace=*/ false);
8185 SDValue FIST = Vals.first, StackSlot = Vals.second;
8186 assert(FIST.getNode() && "Unexpected failure");
8188 if (StackSlot.getNode())
8190 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8191 FIST, StackSlot, MachinePointerInfo(),
8192 false, false, false, 0);
8194 // The node is the result.
8198 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8199 LLVMContext *Context = DAG.getContext();
8200 DebugLoc dl = Op.getDebugLoc();
8201 EVT VT = Op.getValueType();
8203 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8204 if (VT.isVector()) {
8205 EltVT = VT.getVectorElementType();
8206 NumElts = VT.getVectorNumElements();
8209 if (EltVT == MVT::f64)
8210 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8212 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8213 C = ConstantVector::getSplat(NumElts, C);
8214 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8215 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8216 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8217 MachinePointerInfo::getConstantPool(),
8218 false, false, false, Alignment);
8219 if (VT.isVector()) {
8220 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8221 return DAG.getNode(ISD::BITCAST, dl, VT,
8222 DAG.getNode(ISD::AND, dl, ANDVT,
8223 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8225 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8227 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8230 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8231 LLVMContext *Context = DAG.getContext();
8232 DebugLoc dl = Op.getDebugLoc();
8233 EVT VT = Op.getValueType();
8235 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8236 if (VT.isVector()) {
8237 EltVT = VT.getVectorElementType();
8238 NumElts = VT.getVectorNumElements();
8241 if (EltVT == MVT::f64)
8242 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8244 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8245 C = ConstantVector::getSplat(NumElts, C);
8246 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8247 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8248 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8249 MachinePointerInfo::getConstantPool(),
8250 false, false, false, Alignment);
8251 if (VT.isVector()) {
8252 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8253 return DAG.getNode(ISD::BITCAST, dl, VT,
8254 DAG.getNode(ISD::XOR, dl, XORVT,
8255 DAG.getNode(ISD::BITCAST, dl, XORVT,
8257 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8260 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8263 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8264 LLVMContext *Context = DAG.getContext();
8265 SDValue Op0 = Op.getOperand(0);
8266 SDValue Op1 = Op.getOperand(1);
8267 DebugLoc dl = Op.getDebugLoc();
8268 EVT VT = Op.getValueType();
8269 EVT SrcVT = Op1.getValueType();
8271 // If second operand is smaller, extend it first.
8272 if (SrcVT.bitsLT(VT)) {
8273 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8276 // And if it is bigger, shrink it first.
8277 if (SrcVT.bitsGT(VT)) {
8278 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8282 // At this point the operands and the result should have the same
8283 // type, and that won't be f80 since that is not custom lowered.
8285 // First get the sign bit of second operand.
8286 SmallVector<Constant*,4> CV;
8287 if (SrcVT == MVT::f64) {
8288 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8289 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8291 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8292 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8293 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8294 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8296 Constant *C = ConstantVector::get(CV);
8297 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8298 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8299 MachinePointerInfo::getConstantPool(),
8300 false, false, false, 16);
8301 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8303 // Shift sign bit right or left if the two operands have different types.
8304 if (SrcVT.bitsGT(VT)) {
8305 // Op0 is MVT::f32, Op1 is MVT::f64.
8306 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8307 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8308 DAG.getConstant(32, MVT::i32));
8309 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8310 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8311 DAG.getIntPtrConstant(0));
8314 // Clear first operand sign bit.
8316 if (VT == MVT::f64) {
8317 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8318 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8320 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8321 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8322 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8323 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8325 C = ConstantVector::get(CV);
8326 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8327 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8328 MachinePointerInfo::getConstantPool(),
8329 false, false, false, 16);
8330 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8332 // Or the value with the sign bit.
8333 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8336 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8337 SDValue N0 = Op.getOperand(0);
8338 DebugLoc dl = Op.getDebugLoc();
8339 EVT VT = Op.getValueType();
8341 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8342 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8343 DAG.getConstant(1, VT));
8344 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8347 /// Emit nodes that will be selected as "test Op0,Op0", or something
8349 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8350 SelectionDAG &DAG) const {
8351 DebugLoc dl = Op.getDebugLoc();
8353 // CF and OF aren't always set the way we want. Determine which
8354 // of these we need.
8355 bool NeedCF = false;
8356 bool NeedOF = false;
8359 case X86::COND_A: case X86::COND_AE:
8360 case X86::COND_B: case X86::COND_BE:
8363 case X86::COND_G: case X86::COND_GE:
8364 case X86::COND_L: case X86::COND_LE:
8365 case X86::COND_O: case X86::COND_NO:
8370 // See if we can use the EFLAGS value from the operand instead of
8371 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8372 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8373 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8374 // Emit a CMP with 0, which is the TEST pattern.
8375 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8376 DAG.getConstant(0, Op.getValueType()));
8378 unsigned Opcode = 0;
8379 unsigned NumOperands = 0;
8381 // Truncate operations may prevent the merge of the SETCC instruction
8382 // and the arithmetic intruction before it. Attempt to truncate the operands
8383 // of the arithmetic instruction and use a reduced bit-width instruction.
8384 bool NeedTruncation = false;
8385 SDValue ArithOp = Op;
8386 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8387 SDValue Arith = Op->getOperand(0);
8388 // Both the trunc and the arithmetic op need to have one user each.
8389 if (Arith->hasOneUse())
8390 switch (Arith.getOpcode()) {
8397 NeedTruncation = true;
8403 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8404 // which may be the result of a CAST. We use the variable 'Op', which is the
8405 // non-casted variable when we check for possible users.
8406 switch (ArithOp.getOpcode()) {
8408 // Due to an isel shortcoming, be conservative if this add is likely to be
8409 // selected as part of a load-modify-store instruction. When the root node
8410 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8411 // uses of other nodes in the match, such as the ADD in this case. This
8412 // leads to the ADD being left around and reselected, with the result being
8413 // two adds in the output. Alas, even if none our users are stores, that
8414 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8415 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8416 // climbing the DAG back to the root, and it doesn't seem to be worth the
8418 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8419 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8420 if (UI->getOpcode() != ISD::CopyToReg &&
8421 UI->getOpcode() != ISD::SETCC &&
8422 UI->getOpcode() != ISD::STORE)
8425 if (ConstantSDNode *C =
8426 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8427 // An add of one will be selected as an INC.
8428 if (C->getAPIntValue() == 1) {
8429 Opcode = X86ISD::INC;
8434 // An add of negative one (subtract of one) will be selected as a DEC.
8435 if (C->getAPIntValue().isAllOnesValue()) {
8436 Opcode = X86ISD::DEC;
8442 // Otherwise use a regular EFLAGS-setting add.
8443 Opcode = X86ISD::ADD;
8447 // If the primary and result isn't used, don't bother using X86ISD::AND,
8448 // because a TEST instruction will be better.
8449 bool NonFlagUse = false;
8450 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8451 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8453 unsigned UOpNo = UI.getOperandNo();
8454 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8455 // Look pass truncate.
8456 UOpNo = User->use_begin().getOperandNo();
8457 User = *User->use_begin();
8460 if (User->getOpcode() != ISD::BRCOND &&
8461 User->getOpcode() != ISD::SETCC &&
8462 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8475 // Due to the ISEL shortcoming noted above, be conservative if this op is
8476 // likely to be selected as part of a load-modify-store instruction.
8477 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8478 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8479 if (UI->getOpcode() == ISD::STORE)
8482 // Otherwise use a regular EFLAGS-setting instruction.
8483 switch (ArithOp.getOpcode()) {
8484 default: llvm_unreachable("unexpected operator!");
8485 case ISD::SUB: Opcode = X86ISD::SUB; break;
8486 case ISD::OR: Opcode = X86ISD::OR; break;
8487 case ISD::XOR: Opcode = X86ISD::XOR; break;
8488 case ISD::AND: Opcode = X86ISD::AND; break;
8500 return SDValue(Op.getNode(), 1);
8506 // If we found that truncation is beneficial, perform the truncation and
8508 if (NeedTruncation) {
8509 EVT VT = Op.getValueType();
8510 SDValue WideVal = Op->getOperand(0);
8511 EVT WideVT = WideVal.getValueType();
8512 unsigned ConvertedOp = 0;
8513 // Use a target machine opcode to prevent further DAGCombine
8514 // optimizations that may separate the arithmetic operations
8515 // from the setcc node.
8516 switch (WideVal.getOpcode()) {
8518 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8519 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8520 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8521 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8522 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8527 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8528 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8529 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8530 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8536 // Emit a CMP with 0, which is the TEST pattern.
8537 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8538 DAG.getConstant(0, Op.getValueType()));
8540 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8541 SmallVector<SDValue, 4> Ops;
8542 for (unsigned i = 0; i != NumOperands; ++i)
8543 Ops.push_back(Op.getOperand(i));
8545 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8546 DAG.ReplaceAllUsesWith(Op, New);
8547 return SDValue(New.getNode(), 1);
8550 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8552 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8553 SelectionDAG &DAG) const {
8554 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8555 if (C->getAPIntValue() == 0)
8556 return EmitTest(Op0, X86CC, DAG);
8558 DebugLoc dl = Op0.getDebugLoc();
8559 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8560 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8561 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8562 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8563 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8565 return SDValue(Sub.getNode(), 1);
8567 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8570 /// Convert a comparison if required by the subtarget.
8571 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8572 SelectionDAG &DAG) const {
8573 // If the subtarget does not support the FUCOMI instruction, floating-point
8574 // comparisons have to be converted.
8575 if (Subtarget->hasCMov() ||
8576 Cmp.getOpcode() != X86ISD::CMP ||
8577 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8578 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8581 // The instruction selector will select an FUCOM instruction instead of
8582 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8583 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8584 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8585 DebugLoc dl = Cmp.getDebugLoc();
8586 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8587 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8588 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8589 DAG.getConstant(8, MVT::i8));
8590 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8591 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8594 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8595 /// if it's possible.
8596 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8597 DebugLoc dl, SelectionDAG &DAG) const {
8598 SDValue Op0 = And.getOperand(0);
8599 SDValue Op1 = And.getOperand(1);
8600 if (Op0.getOpcode() == ISD::TRUNCATE)
8601 Op0 = Op0.getOperand(0);
8602 if (Op1.getOpcode() == ISD::TRUNCATE)
8603 Op1 = Op1.getOperand(0);
8606 if (Op1.getOpcode() == ISD::SHL)
8607 std::swap(Op0, Op1);
8608 if (Op0.getOpcode() == ISD::SHL) {
8609 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8610 if (And00C->getZExtValue() == 1) {
8611 // If we looked past a truncate, check that it's only truncating away
8613 unsigned BitWidth = Op0.getValueSizeInBits();
8614 unsigned AndBitWidth = And.getValueSizeInBits();
8615 if (BitWidth > AndBitWidth) {
8617 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8618 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8622 RHS = Op0.getOperand(1);
8624 } else if (Op1.getOpcode() == ISD::Constant) {
8625 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8626 uint64_t AndRHSVal = AndRHS->getZExtValue();
8627 SDValue AndLHS = Op0;
8629 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8630 LHS = AndLHS.getOperand(0);
8631 RHS = AndLHS.getOperand(1);
8634 // Use BT if the immediate can't be encoded in a TEST instruction.
8635 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8637 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8641 if (LHS.getNode()) {
8642 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8643 // instruction. Since the shift amount is in-range-or-undefined, we know
8644 // that doing a bittest on the i32 value is ok. We extend to i32 because
8645 // the encoding for the i16 version is larger than the i32 version.
8646 // Also promote i16 to i32 for performance / code size reason.
8647 if (LHS.getValueType() == MVT::i8 ||
8648 LHS.getValueType() == MVT::i16)
8649 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8651 // If the operand types disagree, extend the shift amount to match. Since
8652 // BT ignores high bits (like shifts) we can use anyextend.
8653 if (LHS.getValueType() != RHS.getValueType())
8654 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8656 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8657 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8658 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8659 DAG.getConstant(Cond, MVT::i8), BT);
8665 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8667 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8669 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8670 SDValue Op0 = Op.getOperand(0);
8671 SDValue Op1 = Op.getOperand(1);
8672 DebugLoc dl = Op.getDebugLoc();
8673 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8675 // Optimize to BT if possible.
8676 // Lower (X & (1 << N)) == 0 to BT(X, N).
8677 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8678 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8679 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8680 Op1.getOpcode() == ISD::Constant &&
8681 cast<ConstantSDNode>(Op1)->isNullValue() &&
8682 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8683 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8684 if (NewSetCC.getNode())
8688 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8690 if (Op1.getOpcode() == ISD::Constant &&
8691 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8692 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8693 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8695 // If the input is a setcc, then reuse the input setcc or use a new one with
8696 // the inverted condition.
8697 if (Op0.getOpcode() == X86ISD::SETCC) {
8698 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8699 bool Invert = (CC == ISD::SETNE) ^
8700 cast<ConstantSDNode>(Op1)->isNullValue();
8701 if (!Invert) return Op0;
8703 CCode = X86::GetOppositeBranchCondition(CCode);
8704 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8705 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8709 bool isFP = Op1.getValueType().isFloatingPoint();
8710 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8711 if (X86CC == X86::COND_INVALID)
8714 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8715 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8716 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8717 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8720 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8721 // ones, and then concatenate the result back.
8722 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8723 EVT VT = Op.getValueType();
8725 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8726 "Unsupported value type for operation");
8728 unsigned NumElems = VT.getVectorNumElements();
8729 DebugLoc dl = Op.getDebugLoc();
8730 SDValue CC = Op.getOperand(2);
8732 // Extract the LHS vectors
8733 SDValue LHS = Op.getOperand(0);
8734 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8735 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8737 // Extract the RHS vectors
8738 SDValue RHS = Op.getOperand(1);
8739 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8740 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8742 // Issue the operation on the smaller types and concatenate the result back
8743 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8744 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8745 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8746 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8747 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8751 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8753 SDValue Op0 = Op.getOperand(0);
8754 SDValue Op1 = Op.getOperand(1);
8755 SDValue CC = Op.getOperand(2);
8756 EVT VT = Op.getValueType();
8757 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8758 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8759 DebugLoc dl = Op.getDebugLoc();
8763 EVT EltVT = Op0.getValueType().getVectorElementType();
8764 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8770 // SSE Condition code mapping:
8779 switch (SetCCOpcode) {
8780 default: llvm_unreachable("Unexpected SETCC condition");
8782 case ISD::SETEQ: SSECC = 0; break;
8784 case ISD::SETGT: Swap = true; // Fallthrough
8786 case ISD::SETOLT: SSECC = 1; break;
8788 case ISD::SETGE: Swap = true; // Fallthrough
8790 case ISD::SETOLE: SSECC = 2; break;
8791 case ISD::SETUO: SSECC = 3; break;
8793 case ISD::SETNE: SSECC = 4; break;
8794 case ISD::SETULE: Swap = true; // Fallthrough
8795 case ISD::SETUGE: SSECC = 5; break;
8796 case ISD::SETULT: Swap = true; // Fallthrough
8797 case ISD::SETUGT: SSECC = 6; break;
8798 case ISD::SETO: SSECC = 7; break;
8800 case ISD::SETONE: SSECC = 8; break;
8803 std::swap(Op0, Op1);
8805 // In the two special cases we can't handle, emit two comparisons.
8808 unsigned CombineOpc;
8809 if (SetCCOpcode == ISD::SETUEQ) {
8810 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8812 assert(SetCCOpcode == ISD::SETONE);
8813 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8816 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8817 DAG.getConstant(CC0, MVT::i8));
8818 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8819 DAG.getConstant(CC1, MVT::i8));
8820 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8822 // Handle all other FP comparisons here.
8823 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8824 DAG.getConstant(SSECC, MVT::i8));
8827 // Break 256-bit integer vector compare into smaller ones.
8828 if (VT.is256BitVector() && !Subtarget->hasAVX2())
8829 return Lower256IntVSETCC(Op, DAG);
8831 // We are handling one of the integer comparisons here. Since SSE only has
8832 // GT and EQ comparisons for integer, swapping operands and multiple
8833 // operations may be required for some comparisons.
8835 bool Swap = false, Invert = false, FlipSigns = false;
8837 switch (SetCCOpcode) {
8838 default: llvm_unreachable("Unexpected SETCC condition");
8839 case ISD::SETNE: Invert = true;
8840 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8841 case ISD::SETLT: Swap = true;
8842 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8843 case ISD::SETGE: Swap = true;
8844 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8845 case ISD::SETULT: Swap = true;
8846 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8847 case ISD::SETUGE: Swap = true;
8848 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8851 std::swap(Op0, Op1);
8853 // Check that the operation in question is available (most are plain SSE2,
8854 // but PCMPGTQ and PCMPEQQ have different requirements).
8855 if (VT == MVT::v2i64) {
8856 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8858 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8862 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8863 // bits of the inputs before performing those operations.
8865 EVT EltVT = VT.getVectorElementType();
8866 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8868 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8869 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8871 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8872 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8875 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8877 // If the logical-not of the result is required, perform that now.
8879 Result = DAG.getNOT(dl, Result, VT);
8884 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8885 static bool isX86LogicalCmp(SDValue Op) {
8886 unsigned Opc = Op.getNode()->getOpcode();
8887 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8888 Opc == X86ISD::SAHF)
8890 if (Op.getResNo() == 1 &&
8891 (Opc == X86ISD::ADD ||
8892 Opc == X86ISD::SUB ||
8893 Opc == X86ISD::ADC ||
8894 Opc == X86ISD::SBB ||
8895 Opc == X86ISD::SMUL ||
8896 Opc == X86ISD::UMUL ||
8897 Opc == X86ISD::INC ||
8898 Opc == X86ISD::DEC ||
8899 Opc == X86ISD::OR ||
8900 Opc == X86ISD::XOR ||
8901 Opc == X86ISD::AND))
8904 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8910 static bool isZero(SDValue V) {
8911 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8912 return C && C->isNullValue();
8915 static bool isAllOnes(SDValue V) {
8916 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8917 return C && C->isAllOnesValue();
8920 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8921 if (V.getOpcode() != ISD::TRUNCATE)
8924 SDValue VOp0 = V.getOperand(0);
8925 unsigned InBits = VOp0.getValueSizeInBits();
8926 unsigned Bits = V.getValueSizeInBits();
8927 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8930 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8931 bool addTest = true;
8932 SDValue Cond = Op.getOperand(0);
8933 SDValue Op1 = Op.getOperand(1);
8934 SDValue Op2 = Op.getOperand(2);
8935 DebugLoc DL = Op.getDebugLoc();
8938 if (Cond.getOpcode() == ISD::SETCC) {
8939 SDValue NewCond = LowerSETCC(Cond, DAG);
8940 if (NewCond.getNode())
8944 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8945 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8946 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8947 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8948 if (Cond.getOpcode() == X86ISD::SETCC &&
8949 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8950 isZero(Cond.getOperand(1).getOperand(1))) {
8951 SDValue Cmp = Cond.getOperand(1);
8953 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8955 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8956 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8957 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8959 SDValue CmpOp0 = Cmp.getOperand(0);
8960 // Apply further optimizations for special cases
8961 // (select (x != 0), -1, 0) -> neg & sbb
8962 // (select (x == 0), 0, -1) -> neg & sbb
8963 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8964 if (YC->isNullValue() &&
8965 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8966 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8967 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8968 DAG.getConstant(0, CmpOp0.getValueType()),
8970 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8971 DAG.getConstant(X86::COND_B, MVT::i8),
8972 SDValue(Neg.getNode(), 1));
8976 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8977 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8978 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8980 SDValue Res = // Res = 0 or -1.
8981 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8982 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8984 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8985 Res = DAG.getNOT(DL, Res, Res.getValueType());
8987 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8988 if (N2C == 0 || !N2C->isNullValue())
8989 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8994 // Look past (and (setcc_carry (cmp ...)), 1).
8995 if (Cond.getOpcode() == ISD::AND &&
8996 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8997 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8998 if (C && C->getAPIntValue() == 1)
8999 Cond = Cond.getOperand(0);
9002 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9003 // setting operand in place of the X86ISD::SETCC.
9004 unsigned CondOpcode = Cond.getOpcode();
9005 if (CondOpcode == X86ISD::SETCC ||
9006 CondOpcode == X86ISD::SETCC_CARRY) {
9007 CC = Cond.getOperand(0);
9009 SDValue Cmp = Cond.getOperand(1);
9010 unsigned Opc = Cmp.getOpcode();
9011 EVT VT = Op.getValueType();
9013 bool IllegalFPCMov = false;
9014 if (VT.isFloatingPoint() && !VT.isVector() &&
9015 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9016 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9018 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9019 Opc == X86ISD::BT) { // FIXME
9023 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9024 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9025 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9026 Cond.getOperand(0).getValueType() != MVT::i8)) {
9027 SDValue LHS = Cond.getOperand(0);
9028 SDValue RHS = Cond.getOperand(1);
9032 switch (CondOpcode) {
9033 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9034 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9035 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9036 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9037 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9038 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9039 default: llvm_unreachable("unexpected overflowing operator");
9041 if (CondOpcode == ISD::UMULO)
9042 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9045 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9047 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9049 if (CondOpcode == ISD::UMULO)
9050 Cond = X86Op.getValue(2);
9052 Cond = X86Op.getValue(1);
9054 CC = DAG.getConstant(X86Cond, MVT::i8);
9059 // Look pass the truncate if the high bits are known zero.
9060 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9061 Cond = Cond.getOperand(0);
9063 // We know the result of AND is compared against zero. Try to match
9065 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9066 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9067 if (NewSetCC.getNode()) {
9068 CC = NewSetCC.getOperand(0);
9069 Cond = NewSetCC.getOperand(1);
9076 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9077 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9080 // a < b ? -1 : 0 -> RES = ~setcc_carry
9081 // a < b ? 0 : -1 -> RES = setcc_carry
9082 // a >= b ? -1 : 0 -> RES = setcc_carry
9083 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9084 if (Cond.getOpcode() == X86ISD::SUB) {
9085 Cond = ConvertCmpIfNecessary(Cond, DAG);
9086 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9088 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9089 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9090 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9091 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9092 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9093 return DAG.getNOT(DL, Res, Res.getValueType());
9098 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9099 // condition is true.
9100 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9101 SDValue Ops[] = { Op2, Op1, CC, Cond };
9102 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9105 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9106 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9107 // from the AND / OR.
9108 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9109 Opc = Op.getOpcode();
9110 if (Opc != ISD::OR && Opc != ISD::AND)
9112 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9113 Op.getOperand(0).hasOneUse() &&
9114 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9115 Op.getOperand(1).hasOneUse());
9118 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9119 // 1 and that the SETCC node has a single use.
9120 static bool isXor1OfSetCC(SDValue Op) {
9121 if (Op.getOpcode() != ISD::XOR)
9123 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9124 if (N1C && N1C->getAPIntValue() == 1) {
9125 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9126 Op.getOperand(0).hasOneUse();
9131 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9132 bool addTest = true;
9133 SDValue Chain = Op.getOperand(0);
9134 SDValue Cond = Op.getOperand(1);
9135 SDValue Dest = Op.getOperand(2);
9136 DebugLoc dl = Op.getDebugLoc();
9138 bool Inverted = false;
9140 if (Cond.getOpcode() == ISD::SETCC) {
9141 // Check for setcc([su]{add,sub,mul}o == 0).
9142 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9143 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9144 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9145 Cond.getOperand(0).getResNo() == 1 &&
9146 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9147 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9148 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9149 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9150 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9151 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9153 Cond = Cond.getOperand(0);
9155 SDValue NewCond = LowerSETCC(Cond, DAG);
9156 if (NewCond.getNode())
9161 // FIXME: LowerXALUO doesn't handle these!!
9162 else if (Cond.getOpcode() == X86ISD::ADD ||
9163 Cond.getOpcode() == X86ISD::SUB ||
9164 Cond.getOpcode() == X86ISD::SMUL ||
9165 Cond.getOpcode() == X86ISD::UMUL)
9166 Cond = LowerXALUO(Cond, DAG);
9169 // Look pass (and (setcc_carry (cmp ...)), 1).
9170 if (Cond.getOpcode() == ISD::AND &&
9171 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9172 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9173 if (C && C->getAPIntValue() == 1)
9174 Cond = Cond.getOperand(0);
9177 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9178 // setting operand in place of the X86ISD::SETCC.
9179 unsigned CondOpcode = Cond.getOpcode();
9180 if (CondOpcode == X86ISD::SETCC ||
9181 CondOpcode == X86ISD::SETCC_CARRY) {
9182 CC = Cond.getOperand(0);
9184 SDValue Cmp = Cond.getOperand(1);
9185 unsigned Opc = Cmp.getOpcode();
9186 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9187 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9191 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9195 // These can only come from an arithmetic instruction with overflow,
9196 // e.g. SADDO, UADDO.
9197 Cond = Cond.getNode()->getOperand(1);
9203 CondOpcode = Cond.getOpcode();
9204 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9205 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9206 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9207 Cond.getOperand(0).getValueType() != MVT::i8)) {
9208 SDValue LHS = Cond.getOperand(0);
9209 SDValue RHS = Cond.getOperand(1);
9213 switch (CondOpcode) {
9214 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9215 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9216 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9217 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9218 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9219 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9220 default: llvm_unreachable("unexpected overflowing operator");
9223 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9224 if (CondOpcode == ISD::UMULO)
9225 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9228 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9230 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9232 if (CondOpcode == ISD::UMULO)
9233 Cond = X86Op.getValue(2);
9235 Cond = X86Op.getValue(1);
9237 CC = DAG.getConstant(X86Cond, MVT::i8);
9241 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9242 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9243 if (CondOpc == ISD::OR) {
9244 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9245 // two branches instead of an explicit OR instruction with a
9247 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9248 isX86LogicalCmp(Cmp)) {
9249 CC = Cond.getOperand(0).getOperand(0);
9250 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9251 Chain, Dest, CC, Cmp);
9252 CC = Cond.getOperand(1).getOperand(0);
9256 } else { // ISD::AND
9257 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9258 // two branches instead of an explicit AND instruction with a
9259 // separate test. However, we only do this if this block doesn't
9260 // have a fall-through edge, because this requires an explicit
9261 // jmp when the condition is false.
9262 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9263 isX86LogicalCmp(Cmp) &&
9264 Op.getNode()->hasOneUse()) {
9265 X86::CondCode CCode =
9266 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9267 CCode = X86::GetOppositeBranchCondition(CCode);
9268 CC = DAG.getConstant(CCode, MVT::i8);
9269 SDNode *User = *Op.getNode()->use_begin();
9270 // Look for an unconditional branch following this conditional branch.
9271 // We need this because we need to reverse the successors in order
9272 // to implement FCMP_OEQ.
9273 if (User->getOpcode() == ISD::BR) {
9274 SDValue FalseBB = User->getOperand(1);
9276 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9277 assert(NewBR == User);
9281 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9282 Chain, Dest, CC, Cmp);
9283 X86::CondCode CCode =
9284 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9285 CCode = X86::GetOppositeBranchCondition(CCode);
9286 CC = DAG.getConstant(CCode, MVT::i8);
9292 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9293 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9294 // It should be transformed during dag combiner except when the condition
9295 // is set by a arithmetics with overflow node.
9296 X86::CondCode CCode =
9297 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9298 CCode = X86::GetOppositeBranchCondition(CCode);
9299 CC = DAG.getConstant(CCode, MVT::i8);
9300 Cond = Cond.getOperand(0).getOperand(1);
9302 } else if (Cond.getOpcode() == ISD::SETCC &&
9303 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9304 // For FCMP_OEQ, we can emit
9305 // two branches instead of an explicit AND instruction with a
9306 // separate test. However, we only do this if this block doesn't
9307 // have a fall-through edge, because this requires an explicit
9308 // jmp when the condition is false.
9309 if (Op.getNode()->hasOneUse()) {
9310 SDNode *User = *Op.getNode()->use_begin();
9311 // Look for an unconditional branch following this conditional branch.
9312 // We need this because we need to reverse the successors in order
9313 // to implement FCMP_OEQ.
9314 if (User->getOpcode() == ISD::BR) {
9315 SDValue FalseBB = User->getOperand(1);
9317 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9318 assert(NewBR == User);
9322 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9323 Cond.getOperand(0), Cond.getOperand(1));
9324 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9325 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9326 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9327 Chain, Dest, CC, Cmp);
9328 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9333 } else if (Cond.getOpcode() == ISD::SETCC &&
9334 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9335 // For FCMP_UNE, we can emit
9336 // two branches instead of an explicit AND instruction with a
9337 // separate test. However, we only do this if this block doesn't
9338 // have a fall-through edge, because this requires an explicit
9339 // jmp when the condition is false.
9340 if (Op.getNode()->hasOneUse()) {
9341 SDNode *User = *Op.getNode()->use_begin();
9342 // Look for an unconditional branch following this conditional branch.
9343 // We need this because we need to reverse the successors in order
9344 // to implement FCMP_UNE.
9345 if (User->getOpcode() == ISD::BR) {
9346 SDValue FalseBB = User->getOperand(1);
9348 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9349 assert(NewBR == User);
9352 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9353 Cond.getOperand(0), Cond.getOperand(1));
9354 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9355 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9356 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9357 Chain, Dest, CC, Cmp);
9358 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9368 // Look pass the truncate if the high bits are known zero.
9369 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9370 Cond = Cond.getOperand(0);
9372 // We know the result of AND is compared against zero. Try to match
9374 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9375 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9376 if (NewSetCC.getNode()) {
9377 CC = NewSetCC.getOperand(0);
9378 Cond = NewSetCC.getOperand(1);
9385 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9386 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9388 Cond = ConvertCmpIfNecessary(Cond, DAG);
9389 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9390 Chain, Dest, CC, Cond);
9394 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9395 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9396 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9397 // that the guard pages used by the OS virtual memory manager are allocated in
9398 // correct sequence.
9400 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9401 SelectionDAG &DAG) const {
9402 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9403 getTargetMachine().Options.EnableSegmentedStacks) &&
9404 "This should be used only on Windows targets or when segmented stacks "
9406 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9407 DebugLoc dl = Op.getDebugLoc();
9410 SDValue Chain = Op.getOperand(0);
9411 SDValue Size = Op.getOperand(1);
9412 // FIXME: Ensure alignment here
9414 bool Is64Bit = Subtarget->is64Bit();
9415 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9417 if (getTargetMachine().Options.EnableSegmentedStacks) {
9418 MachineFunction &MF = DAG.getMachineFunction();
9419 MachineRegisterInfo &MRI = MF.getRegInfo();
9422 // The 64 bit implementation of segmented stacks needs to clobber both r10
9423 // r11. This makes it impossible to use it along with nested parameters.
9424 const Function *F = MF.getFunction();
9426 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9428 if (I->hasNestAttr())
9429 report_fatal_error("Cannot use segmented stacks with functions that "
9430 "have nested arguments.");
9433 const TargetRegisterClass *AddrRegClass =
9434 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9435 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9436 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9437 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9438 DAG.getRegister(Vreg, SPTy));
9439 SDValue Ops1[2] = { Value, Chain };
9440 return DAG.getMergeValues(Ops1, 2, dl);
9443 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9445 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9446 Flag = Chain.getValue(1);
9447 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9449 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9450 Flag = Chain.getValue(1);
9452 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9454 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9455 return DAG.getMergeValues(Ops1, 2, dl);
9459 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9460 MachineFunction &MF = DAG.getMachineFunction();
9461 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9463 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9464 DebugLoc DL = Op.getDebugLoc();
9466 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9467 // vastart just stores the address of the VarArgsFrameIndex slot into the
9468 // memory location argument.
9469 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9471 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9472 MachinePointerInfo(SV), false, false, 0);
9476 // gp_offset (0 - 6 * 8)
9477 // fp_offset (48 - 48 + 8 * 16)
9478 // overflow_arg_area (point to parameters coming in memory).
9480 SmallVector<SDValue, 8> MemOps;
9481 SDValue FIN = Op.getOperand(1);
9483 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9484 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9486 FIN, MachinePointerInfo(SV), false, false, 0);
9487 MemOps.push_back(Store);
9490 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9491 FIN, DAG.getIntPtrConstant(4));
9492 Store = DAG.getStore(Op.getOperand(0), DL,
9493 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9495 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9496 MemOps.push_back(Store);
9498 // Store ptr to overflow_arg_area
9499 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9500 FIN, DAG.getIntPtrConstant(4));
9501 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9503 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9504 MachinePointerInfo(SV, 8),
9506 MemOps.push_back(Store);
9508 // Store ptr to reg_save_area.
9509 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9510 FIN, DAG.getIntPtrConstant(8));
9511 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9513 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9514 MachinePointerInfo(SV, 16), false, false, 0);
9515 MemOps.push_back(Store);
9516 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9517 &MemOps[0], MemOps.size());
9520 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9521 assert(Subtarget->is64Bit() &&
9522 "LowerVAARG only handles 64-bit va_arg!");
9523 assert((Subtarget->isTargetLinux() ||
9524 Subtarget->isTargetDarwin()) &&
9525 "Unhandled target in LowerVAARG");
9526 assert(Op.getNode()->getNumOperands() == 4);
9527 SDValue Chain = Op.getOperand(0);
9528 SDValue SrcPtr = Op.getOperand(1);
9529 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9530 unsigned Align = Op.getConstantOperandVal(3);
9531 DebugLoc dl = Op.getDebugLoc();
9533 EVT ArgVT = Op.getNode()->getValueType(0);
9534 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9535 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9538 // Decide which area this value should be read from.
9539 // TODO: Implement the AMD64 ABI in its entirety. This simple
9540 // selection mechanism works only for the basic types.
9541 if (ArgVT == MVT::f80) {
9542 llvm_unreachable("va_arg for f80 not yet implemented");
9543 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9544 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9545 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9546 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9548 llvm_unreachable("Unhandled argument type in LowerVAARG");
9552 // Sanity Check: Make sure using fp_offset makes sense.
9553 assert(!getTargetMachine().Options.UseSoftFloat &&
9554 !(DAG.getMachineFunction()
9555 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9556 Subtarget->hasSSE1());
9559 // Insert VAARG_64 node into the DAG
9560 // VAARG_64 returns two values: Variable Argument Address, Chain
9561 SmallVector<SDValue, 11> InstOps;
9562 InstOps.push_back(Chain);
9563 InstOps.push_back(SrcPtr);
9564 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9565 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9566 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9567 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9568 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9569 VTs, &InstOps[0], InstOps.size(),
9571 MachinePointerInfo(SV),
9576 Chain = VAARG.getValue(1);
9578 // Load the next argument and return it
9579 return DAG.getLoad(ArgVT, dl,
9582 MachinePointerInfo(),
9583 false, false, false, 0);
9586 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9587 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9588 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9589 SDValue Chain = Op.getOperand(0);
9590 SDValue DstPtr = Op.getOperand(1);
9591 SDValue SrcPtr = Op.getOperand(2);
9592 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9593 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9594 DebugLoc DL = Op.getDebugLoc();
9596 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9597 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9599 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9602 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9603 // may or may not be a constant. Takes immediate version of shift as input.
9604 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9605 SDValue SrcOp, SDValue ShAmt,
9606 SelectionDAG &DAG) {
9607 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9609 if (isa<ConstantSDNode>(ShAmt)) {
9610 // Constant may be a TargetConstant. Use a regular constant.
9611 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9613 default: llvm_unreachable("Unknown target vector shift node");
9617 return DAG.getNode(Opc, dl, VT, SrcOp,
9618 DAG.getConstant(ShiftAmt, MVT::i32));
9622 // Change opcode to non-immediate version
9624 default: llvm_unreachable("Unknown target vector shift node");
9625 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9626 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9627 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9630 // Need to build a vector containing shift amount
9631 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9634 ShOps[1] = DAG.getConstant(0, MVT::i32);
9635 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9636 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9638 // The return type has to be a 128-bit type with the same element
9639 // type as the input type.
9640 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9641 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9643 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9644 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9648 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9649 DebugLoc dl = Op.getDebugLoc();
9650 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9652 default: return SDValue(); // Don't custom lower most intrinsics.
9653 // Comparison intrinsics.
9654 case Intrinsic::x86_sse_comieq_ss:
9655 case Intrinsic::x86_sse_comilt_ss:
9656 case Intrinsic::x86_sse_comile_ss:
9657 case Intrinsic::x86_sse_comigt_ss:
9658 case Intrinsic::x86_sse_comige_ss:
9659 case Intrinsic::x86_sse_comineq_ss:
9660 case Intrinsic::x86_sse_ucomieq_ss:
9661 case Intrinsic::x86_sse_ucomilt_ss:
9662 case Intrinsic::x86_sse_ucomile_ss:
9663 case Intrinsic::x86_sse_ucomigt_ss:
9664 case Intrinsic::x86_sse_ucomige_ss:
9665 case Intrinsic::x86_sse_ucomineq_ss:
9666 case Intrinsic::x86_sse2_comieq_sd:
9667 case Intrinsic::x86_sse2_comilt_sd:
9668 case Intrinsic::x86_sse2_comile_sd:
9669 case Intrinsic::x86_sse2_comigt_sd:
9670 case Intrinsic::x86_sse2_comige_sd:
9671 case Intrinsic::x86_sse2_comineq_sd:
9672 case Intrinsic::x86_sse2_ucomieq_sd:
9673 case Intrinsic::x86_sse2_ucomilt_sd:
9674 case Intrinsic::x86_sse2_ucomile_sd:
9675 case Intrinsic::x86_sse2_ucomigt_sd:
9676 case Intrinsic::x86_sse2_ucomige_sd:
9677 case Intrinsic::x86_sse2_ucomineq_sd: {
9681 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9682 case Intrinsic::x86_sse_comieq_ss:
9683 case Intrinsic::x86_sse2_comieq_sd:
9687 case Intrinsic::x86_sse_comilt_ss:
9688 case Intrinsic::x86_sse2_comilt_sd:
9692 case Intrinsic::x86_sse_comile_ss:
9693 case Intrinsic::x86_sse2_comile_sd:
9697 case Intrinsic::x86_sse_comigt_ss:
9698 case Intrinsic::x86_sse2_comigt_sd:
9702 case Intrinsic::x86_sse_comige_ss:
9703 case Intrinsic::x86_sse2_comige_sd:
9707 case Intrinsic::x86_sse_comineq_ss:
9708 case Intrinsic::x86_sse2_comineq_sd:
9712 case Intrinsic::x86_sse_ucomieq_ss:
9713 case Intrinsic::x86_sse2_ucomieq_sd:
9714 Opc = X86ISD::UCOMI;
9717 case Intrinsic::x86_sse_ucomilt_ss:
9718 case Intrinsic::x86_sse2_ucomilt_sd:
9719 Opc = X86ISD::UCOMI;
9722 case Intrinsic::x86_sse_ucomile_ss:
9723 case Intrinsic::x86_sse2_ucomile_sd:
9724 Opc = X86ISD::UCOMI;
9727 case Intrinsic::x86_sse_ucomigt_ss:
9728 case Intrinsic::x86_sse2_ucomigt_sd:
9729 Opc = X86ISD::UCOMI;
9732 case Intrinsic::x86_sse_ucomige_ss:
9733 case Intrinsic::x86_sse2_ucomige_sd:
9734 Opc = X86ISD::UCOMI;
9737 case Intrinsic::x86_sse_ucomineq_ss:
9738 case Intrinsic::x86_sse2_ucomineq_sd:
9739 Opc = X86ISD::UCOMI;
9744 SDValue LHS = Op.getOperand(1);
9745 SDValue RHS = Op.getOperand(2);
9746 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9747 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9748 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9749 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9750 DAG.getConstant(X86CC, MVT::i8), Cond);
9751 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9754 // Arithmetic intrinsics.
9755 case Intrinsic::x86_sse2_pmulu_dq:
9756 case Intrinsic::x86_avx2_pmulu_dq:
9757 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9758 Op.getOperand(1), Op.getOperand(2));
9760 // SSE3/AVX horizontal add/sub intrinsics
9761 case Intrinsic::x86_sse3_hadd_ps:
9762 case Intrinsic::x86_sse3_hadd_pd:
9763 case Intrinsic::x86_avx_hadd_ps_256:
9764 case Intrinsic::x86_avx_hadd_pd_256:
9765 case Intrinsic::x86_sse3_hsub_ps:
9766 case Intrinsic::x86_sse3_hsub_pd:
9767 case Intrinsic::x86_avx_hsub_ps_256:
9768 case Intrinsic::x86_avx_hsub_pd_256:
9769 case Intrinsic::x86_ssse3_phadd_w_128:
9770 case Intrinsic::x86_ssse3_phadd_d_128:
9771 case Intrinsic::x86_avx2_phadd_w:
9772 case Intrinsic::x86_avx2_phadd_d:
9773 case Intrinsic::x86_ssse3_phsub_w_128:
9774 case Intrinsic::x86_ssse3_phsub_d_128:
9775 case Intrinsic::x86_avx2_phsub_w:
9776 case Intrinsic::x86_avx2_phsub_d: {
9779 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9780 case Intrinsic::x86_sse3_hadd_ps:
9781 case Intrinsic::x86_sse3_hadd_pd:
9782 case Intrinsic::x86_avx_hadd_ps_256:
9783 case Intrinsic::x86_avx_hadd_pd_256:
9784 Opcode = X86ISD::FHADD;
9786 case Intrinsic::x86_sse3_hsub_ps:
9787 case Intrinsic::x86_sse3_hsub_pd:
9788 case Intrinsic::x86_avx_hsub_ps_256:
9789 case Intrinsic::x86_avx_hsub_pd_256:
9790 Opcode = X86ISD::FHSUB;
9792 case Intrinsic::x86_ssse3_phadd_w_128:
9793 case Intrinsic::x86_ssse3_phadd_d_128:
9794 case Intrinsic::x86_avx2_phadd_w:
9795 case Intrinsic::x86_avx2_phadd_d:
9796 Opcode = X86ISD::HADD;
9798 case Intrinsic::x86_ssse3_phsub_w_128:
9799 case Intrinsic::x86_ssse3_phsub_d_128:
9800 case Intrinsic::x86_avx2_phsub_w:
9801 case Intrinsic::x86_avx2_phsub_d:
9802 Opcode = X86ISD::HSUB;
9805 return DAG.getNode(Opcode, dl, Op.getValueType(),
9806 Op.getOperand(1), Op.getOperand(2));
9809 // AVX2 variable shift intrinsics
9810 case Intrinsic::x86_avx2_psllv_d:
9811 case Intrinsic::x86_avx2_psllv_q:
9812 case Intrinsic::x86_avx2_psllv_d_256:
9813 case Intrinsic::x86_avx2_psllv_q_256:
9814 case Intrinsic::x86_avx2_psrlv_d:
9815 case Intrinsic::x86_avx2_psrlv_q:
9816 case Intrinsic::x86_avx2_psrlv_d_256:
9817 case Intrinsic::x86_avx2_psrlv_q_256:
9818 case Intrinsic::x86_avx2_psrav_d:
9819 case Intrinsic::x86_avx2_psrav_d_256: {
9822 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9823 case Intrinsic::x86_avx2_psllv_d:
9824 case Intrinsic::x86_avx2_psllv_q:
9825 case Intrinsic::x86_avx2_psllv_d_256:
9826 case Intrinsic::x86_avx2_psllv_q_256:
9829 case Intrinsic::x86_avx2_psrlv_d:
9830 case Intrinsic::x86_avx2_psrlv_q:
9831 case Intrinsic::x86_avx2_psrlv_d_256:
9832 case Intrinsic::x86_avx2_psrlv_q_256:
9835 case Intrinsic::x86_avx2_psrav_d:
9836 case Intrinsic::x86_avx2_psrav_d_256:
9840 return DAG.getNode(Opcode, dl, Op.getValueType(),
9841 Op.getOperand(1), Op.getOperand(2));
9844 case Intrinsic::x86_ssse3_pshuf_b_128:
9845 case Intrinsic::x86_avx2_pshuf_b:
9846 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9847 Op.getOperand(1), Op.getOperand(2));
9849 case Intrinsic::x86_ssse3_psign_b_128:
9850 case Intrinsic::x86_ssse3_psign_w_128:
9851 case Intrinsic::x86_ssse3_psign_d_128:
9852 case Intrinsic::x86_avx2_psign_b:
9853 case Intrinsic::x86_avx2_psign_w:
9854 case Intrinsic::x86_avx2_psign_d:
9855 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9856 Op.getOperand(1), Op.getOperand(2));
9858 case Intrinsic::x86_sse41_insertps:
9859 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9860 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9862 case Intrinsic::x86_avx_vperm2f128_ps_256:
9863 case Intrinsic::x86_avx_vperm2f128_pd_256:
9864 case Intrinsic::x86_avx_vperm2f128_si_256:
9865 case Intrinsic::x86_avx2_vperm2i128:
9866 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9867 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9869 case Intrinsic::x86_avx2_permd:
9870 case Intrinsic::x86_avx2_permps:
9871 // Operands intentionally swapped. Mask is last operand to intrinsic,
9872 // but second operand for node/intruction.
9873 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9874 Op.getOperand(2), Op.getOperand(1));
9876 // ptest and testp intrinsics. The intrinsic these come from are designed to
9877 // return an integer value, not just an instruction so lower it to the ptest
9878 // or testp pattern and a setcc for the result.
9879 case Intrinsic::x86_sse41_ptestz:
9880 case Intrinsic::x86_sse41_ptestc:
9881 case Intrinsic::x86_sse41_ptestnzc:
9882 case Intrinsic::x86_avx_ptestz_256:
9883 case Intrinsic::x86_avx_ptestc_256:
9884 case Intrinsic::x86_avx_ptestnzc_256:
9885 case Intrinsic::x86_avx_vtestz_ps:
9886 case Intrinsic::x86_avx_vtestc_ps:
9887 case Intrinsic::x86_avx_vtestnzc_ps:
9888 case Intrinsic::x86_avx_vtestz_pd:
9889 case Intrinsic::x86_avx_vtestc_pd:
9890 case Intrinsic::x86_avx_vtestnzc_pd:
9891 case Intrinsic::x86_avx_vtestz_ps_256:
9892 case Intrinsic::x86_avx_vtestc_ps_256:
9893 case Intrinsic::x86_avx_vtestnzc_ps_256:
9894 case Intrinsic::x86_avx_vtestz_pd_256:
9895 case Intrinsic::x86_avx_vtestc_pd_256:
9896 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9897 bool IsTestPacked = false;
9900 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9901 case Intrinsic::x86_avx_vtestz_ps:
9902 case Intrinsic::x86_avx_vtestz_pd:
9903 case Intrinsic::x86_avx_vtestz_ps_256:
9904 case Intrinsic::x86_avx_vtestz_pd_256:
9905 IsTestPacked = true; // Fallthrough
9906 case Intrinsic::x86_sse41_ptestz:
9907 case Intrinsic::x86_avx_ptestz_256:
9909 X86CC = X86::COND_E;
9911 case Intrinsic::x86_avx_vtestc_ps:
9912 case Intrinsic::x86_avx_vtestc_pd:
9913 case Intrinsic::x86_avx_vtestc_ps_256:
9914 case Intrinsic::x86_avx_vtestc_pd_256:
9915 IsTestPacked = true; // Fallthrough
9916 case Intrinsic::x86_sse41_ptestc:
9917 case Intrinsic::x86_avx_ptestc_256:
9919 X86CC = X86::COND_B;
9921 case Intrinsic::x86_avx_vtestnzc_ps:
9922 case Intrinsic::x86_avx_vtestnzc_pd:
9923 case Intrinsic::x86_avx_vtestnzc_ps_256:
9924 case Intrinsic::x86_avx_vtestnzc_pd_256:
9925 IsTestPacked = true; // Fallthrough
9926 case Intrinsic::x86_sse41_ptestnzc:
9927 case Intrinsic::x86_avx_ptestnzc_256:
9929 X86CC = X86::COND_A;
9933 SDValue LHS = Op.getOperand(1);
9934 SDValue RHS = Op.getOperand(2);
9935 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9936 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9937 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9938 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9939 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9942 // SSE/AVX shift intrinsics
9943 case Intrinsic::x86_sse2_psll_w:
9944 case Intrinsic::x86_sse2_psll_d:
9945 case Intrinsic::x86_sse2_psll_q:
9946 case Intrinsic::x86_avx2_psll_w:
9947 case Intrinsic::x86_avx2_psll_d:
9948 case Intrinsic::x86_avx2_psll_q:
9949 case Intrinsic::x86_sse2_psrl_w:
9950 case Intrinsic::x86_sse2_psrl_d:
9951 case Intrinsic::x86_sse2_psrl_q:
9952 case Intrinsic::x86_avx2_psrl_w:
9953 case Intrinsic::x86_avx2_psrl_d:
9954 case Intrinsic::x86_avx2_psrl_q:
9955 case Intrinsic::x86_sse2_psra_w:
9956 case Intrinsic::x86_sse2_psra_d:
9957 case Intrinsic::x86_avx2_psra_w:
9958 case Intrinsic::x86_avx2_psra_d: {
9961 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9962 case Intrinsic::x86_sse2_psll_w:
9963 case Intrinsic::x86_sse2_psll_d:
9964 case Intrinsic::x86_sse2_psll_q:
9965 case Intrinsic::x86_avx2_psll_w:
9966 case Intrinsic::x86_avx2_psll_d:
9967 case Intrinsic::x86_avx2_psll_q:
9968 Opcode = X86ISD::VSHL;
9970 case Intrinsic::x86_sse2_psrl_w:
9971 case Intrinsic::x86_sse2_psrl_d:
9972 case Intrinsic::x86_sse2_psrl_q:
9973 case Intrinsic::x86_avx2_psrl_w:
9974 case Intrinsic::x86_avx2_psrl_d:
9975 case Intrinsic::x86_avx2_psrl_q:
9976 Opcode = X86ISD::VSRL;
9978 case Intrinsic::x86_sse2_psra_w:
9979 case Intrinsic::x86_sse2_psra_d:
9980 case Intrinsic::x86_avx2_psra_w:
9981 case Intrinsic::x86_avx2_psra_d:
9982 Opcode = X86ISD::VSRA;
9985 return DAG.getNode(Opcode, dl, Op.getValueType(),
9986 Op.getOperand(1), Op.getOperand(2));
9989 // SSE/AVX immediate shift intrinsics
9990 case Intrinsic::x86_sse2_pslli_w:
9991 case Intrinsic::x86_sse2_pslli_d:
9992 case Intrinsic::x86_sse2_pslli_q:
9993 case Intrinsic::x86_avx2_pslli_w:
9994 case Intrinsic::x86_avx2_pslli_d:
9995 case Intrinsic::x86_avx2_pslli_q:
9996 case Intrinsic::x86_sse2_psrli_w:
9997 case Intrinsic::x86_sse2_psrli_d:
9998 case Intrinsic::x86_sse2_psrli_q:
9999 case Intrinsic::x86_avx2_psrli_w:
10000 case Intrinsic::x86_avx2_psrli_d:
10001 case Intrinsic::x86_avx2_psrli_q:
10002 case Intrinsic::x86_sse2_psrai_w:
10003 case Intrinsic::x86_sse2_psrai_d:
10004 case Intrinsic::x86_avx2_psrai_w:
10005 case Intrinsic::x86_avx2_psrai_d: {
10008 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10009 case Intrinsic::x86_sse2_pslli_w:
10010 case Intrinsic::x86_sse2_pslli_d:
10011 case Intrinsic::x86_sse2_pslli_q:
10012 case Intrinsic::x86_avx2_pslli_w:
10013 case Intrinsic::x86_avx2_pslli_d:
10014 case Intrinsic::x86_avx2_pslli_q:
10015 Opcode = X86ISD::VSHLI;
10017 case Intrinsic::x86_sse2_psrli_w:
10018 case Intrinsic::x86_sse2_psrli_d:
10019 case Intrinsic::x86_sse2_psrli_q:
10020 case Intrinsic::x86_avx2_psrli_w:
10021 case Intrinsic::x86_avx2_psrli_d:
10022 case Intrinsic::x86_avx2_psrli_q:
10023 Opcode = X86ISD::VSRLI;
10025 case Intrinsic::x86_sse2_psrai_w:
10026 case Intrinsic::x86_sse2_psrai_d:
10027 case Intrinsic::x86_avx2_psrai_w:
10028 case Intrinsic::x86_avx2_psrai_d:
10029 Opcode = X86ISD::VSRAI;
10032 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10033 Op.getOperand(1), Op.getOperand(2), DAG);
10036 case Intrinsic::x86_sse42_pcmpistria128:
10037 case Intrinsic::x86_sse42_pcmpestria128:
10038 case Intrinsic::x86_sse42_pcmpistric128:
10039 case Intrinsic::x86_sse42_pcmpestric128:
10040 case Intrinsic::x86_sse42_pcmpistrio128:
10041 case Intrinsic::x86_sse42_pcmpestrio128:
10042 case Intrinsic::x86_sse42_pcmpistris128:
10043 case Intrinsic::x86_sse42_pcmpestris128:
10044 case Intrinsic::x86_sse42_pcmpistriz128:
10045 case Intrinsic::x86_sse42_pcmpestriz128: {
10049 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10050 case Intrinsic::x86_sse42_pcmpistria128:
10051 Opcode = X86ISD::PCMPISTRI;
10052 X86CC = X86::COND_A;
10054 case Intrinsic::x86_sse42_pcmpestria128:
10055 Opcode = X86ISD::PCMPESTRI;
10056 X86CC = X86::COND_A;
10058 case Intrinsic::x86_sse42_pcmpistric128:
10059 Opcode = X86ISD::PCMPISTRI;
10060 X86CC = X86::COND_B;
10062 case Intrinsic::x86_sse42_pcmpestric128:
10063 Opcode = X86ISD::PCMPESTRI;
10064 X86CC = X86::COND_B;
10066 case Intrinsic::x86_sse42_pcmpistrio128:
10067 Opcode = X86ISD::PCMPISTRI;
10068 X86CC = X86::COND_O;
10070 case Intrinsic::x86_sse42_pcmpestrio128:
10071 Opcode = X86ISD::PCMPESTRI;
10072 X86CC = X86::COND_O;
10074 case Intrinsic::x86_sse42_pcmpistris128:
10075 Opcode = X86ISD::PCMPISTRI;
10076 X86CC = X86::COND_S;
10078 case Intrinsic::x86_sse42_pcmpestris128:
10079 Opcode = X86ISD::PCMPESTRI;
10080 X86CC = X86::COND_S;
10082 case Intrinsic::x86_sse42_pcmpistriz128:
10083 Opcode = X86ISD::PCMPISTRI;
10084 X86CC = X86::COND_E;
10086 case Intrinsic::x86_sse42_pcmpestriz128:
10087 Opcode = X86ISD::PCMPESTRI;
10088 X86CC = X86::COND_E;
10091 SmallVector<SDValue, 5> NewOps;
10092 NewOps.append(Op->op_begin()+1, Op->op_end());
10093 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10094 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10095 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10096 DAG.getConstant(X86CC, MVT::i8),
10097 SDValue(PCMP.getNode(), 1));
10098 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10101 case Intrinsic::x86_sse42_pcmpistri128:
10102 case Intrinsic::x86_sse42_pcmpestri128: {
10104 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10105 Opcode = X86ISD::PCMPISTRI;
10107 Opcode = X86ISD::PCMPESTRI;
10109 SmallVector<SDValue, 5> NewOps;
10110 NewOps.append(Op->op_begin()+1, Op->op_end());
10111 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10112 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10114 case Intrinsic::x86_fma_vfmadd_ps:
10115 case Intrinsic::x86_fma_vfmadd_pd:
10116 case Intrinsic::x86_fma_vfmsub_ps:
10117 case Intrinsic::x86_fma_vfmsub_pd:
10118 case Intrinsic::x86_fma_vfnmadd_ps:
10119 case Intrinsic::x86_fma_vfnmadd_pd:
10120 case Intrinsic::x86_fma_vfnmsub_ps:
10121 case Intrinsic::x86_fma_vfnmsub_pd:
10122 case Intrinsic::x86_fma_vfmaddsub_ps:
10123 case Intrinsic::x86_fma_vfmaddsub_pd:
10124 case Intrinsic::x86_fma_vfmsubadd_ps:
10125 case Intrinsic::x86_fma_vfmsubadd_pd:
10126 case Intrinsic::x86_fma_vfmadd_ps_256:
10127 case Intrinsic::x86_fma_vfmadd_pd_256:
10128 case Intrinsic::x86_fma_vfmsub_ps_256:
10129 case Intrinsic::x86_fma_vfmsub_pd_256:
10130 case Intrinsic::x86_fma_vfnmadd_ps_256:
10131 case Intrinsic::x86_fma_vfnmadd_pd_256:
10132 case Intrinsic::x86_fma_vfnmsub_ps_256:
10133 case Intrinsic::x86_fma_vfnmsub_pd_256:
10134 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10135 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10136 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10137 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10140 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10141 case Intrinsic::x86_fma_vfmadd_ps:
10142 case Intrinsic::x86_fma_vfmadd_pd:
10143 case Intrinsic::x86_fma_vfmadd_ps_256:
10144 case Intrinsic::x86_fma_vfmadd_pd_256:
10145 Opc = X86ISD::FMADD;
10147 case Intrinsic::x86_fma_vfmsub_ps:
10148 case Intrinsic::x86_fma_vfmsub_pd:
10149 case Intrinsic::x86_fma_vfmsub_ps_256:
10150 case Intrinsic::x86_fma_vfmsub_pd_256:
10151 Opc = X86ISD::FMSUB;
10153 case Intrinsic::x86_fma_vfnmadd_ps:
10154 case Intrinsic::x86_fma_vfnmadd_pd:
10155 case Intrinsic::x86_fma_vfnmadd_ps_256:
10156 case Intrinsic::x86_fma_vfnmadd_pd_256:
10157 Opc = X86ISD::FNMADD;
10159 case Intrinsic::x86_fma_vfnmsub_ps:
10160 case Intrinsic::x86_fma_vfnmsub_pd:
10161 case Intrinsic::x86_fma_vfnmsub_ps_256:
10162 case Intrinsic::x86_fma_vfnmsub_pd_256:
10163 Opc = X86ISD::FNMSUB;
10165 case Intrinsic::x86_fma_vfmaddsub_ps:
10166 case Intrinsic::x86_fma_vfmaddsub_pd:
10167 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10168 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10169 Opc = X86ISD::FMADDSUB;
10171 case Intrinsic::x86_fma_vfmsubadd_ps:
10172 case Intrinsic::x86_fma_vfmsubadd_pd:
10173 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10174 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10175 Opc = X86ISD::FMSUBADD;
10179 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10180 Op.getOperand(2), Op.getOperand(3));
10186 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10187 DebugLoc dl = Op.getDebugLoc();
10188 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10190 default: return SDValue(); // Don't custom lower most intrinsics.
10192 // RDRAND intrinsics.
10193 case Intrinsic::x86_rdrand_16:
10194 case Intrinsic::x86_rdrand_32:
10195 case Intrinsic::x86_rdrand_64: {
10196 // Emit the node with the right value type.
10197 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10198 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10200 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10201 // return the value from Rand, which is always 0, casted to i32.
10202 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10203 DAG.getConstant(1, Op->getValueType(1)),
10204 DAG.getConstant(X86::COND_B, MVT::i32),
10205 SDValue(Result.getNode(), 1) };
10206 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10207 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10210 // Return { result, isValid, chain }.
10211 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10212 SDValue(Result.getNode(), 2));
10217 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10218 SelectionDAG &DAG) const {
10219 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10220 MFI->setReturnAddressIsTaken(true);
10222 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10223 DebugLoc dl = Op.getDebugLoc();
10226 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10228 DAG.getConstant(TD->getPointerSize(),
10229 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10230 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10231 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10232 FrameAddr, Offset),
10233 MachinePointerInfo(), false, false, false, 0);
10236 // Just load the return address.
10237 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10238 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10239 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10242 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10243 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10244 MFI->setFrameAddressIsTaken(true);
10246 EVT VT = Op.getValueType();
10247 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10248 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10249 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10250 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10252 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10253 MachinePointerInfo(),
10254 false, false, false, 0);
10258 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10259 SelectionDAG &DAG) const {
10260 return DAG.getIntPtrConstant(2*TD->getPointerSize());
10263 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10264 SDValue Chain = Op.getOperand(0);
10265 SDValue Offset = Op.getOperand(1);
10266 SDValue Handler = Op.getOperand(2);
10267 DebugLoc dl = Op.getDebugLoc();
10269 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10270 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10272 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10274 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10275 DAG.getIntPtrConstant(TD->getPointerSize()));
10276 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10277 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10279 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10281 return DAG.getNode(X86ISD::EH_RETURN, dl,
10283 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10286 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10287 SelectionDAG &DAG) const {
10288 return Op.getOperand(0);
10291 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10292 SelectionDAG &DAG) const {
10293 SDValue Root = Op.getOperand(0);
10294 SDValue Trmp = Op.getOperand(1); // trampoline
10295 SDValue FPtr = Op.getOperand(2); // nested function
10296 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10297 DebugLoc dl = Op.getDebugLoc();
10299 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10301 if (Subtarget->is64Bit()) {
10302 SDValue OutChains[6];
10304 // Large code-model.
10305 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10306 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10308 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10309 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10311 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10313 // Load the pointer to the nested function into R11.
10314 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10315 SDValue Addr = Trmp;
10316 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10317 Addr, MachinePointerInfo(TrmpAddr),
10320 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10321 DAG.getConstant(2, MVT::i64));
10322 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10323 MachinePointerInfo(TrmpAddr, 2),
10326 // Load the 'nest' parameter value into R10.
10327 // R10 is specified in X86CallingConv.td
10328 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10329 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10330 DAG.getConstant(10, MVT::i64));
10331 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10332 Addr, MachinePointerInfo(TrmpAddr, 10),
10335 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10336 DAG.getConstant(12, MVT::i64));
10337 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10338 MachinePointerInfo(TrmpAddr, 12),
10341 // Jump to the nested function.
10342 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10343 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10344 DAG.getConstant(20, MVT::i64));
10345 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10346 Addr, MachinePointerInfo(TrmpAddr, 20),
10349 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10350 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10351 DAG.getConstant(22, MVT::i64));
10352 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10353 MachinePointerInfo(TrmpAddr, 22),
10356 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10358 const Function *Func =
10359 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10360 CallingConv::ID CC = Func->getCallingConv();
10365 llvm_unreachable("Unsupported calling convention");
10366 case CallingConv::C:
10367 case CallingConv::X86_StdCall: {
10368 // Pass 'nest' parameter in ECX.
10369 // Must be kept in sync with X86CallingConv.td
10370 NestReg = X86::ECX;
10372 // Check that ECX wasn't needed by an 'inreg' parameter.
10373 FunctionType *FTy = Func->getFunctionType();
10374 const AttrListPtr &Attrs = Func->getAttributes();
10376 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10377 unsigned InRegCount = 0;
10380 for (FunctionType::param_iterator I = FTy->param_begin(),
10381 E = FTy->param_end(); I != E; ++I, ++Idx)
10382 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10383 // FIXME: should only count parameters that are lowered to integers.
10384 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10386 if (InRegCount > 2) {
10387 report_fatal_error("Nest register in use - reduce number of inreg"
10393 case CallingConv::X86_FastCall:
10394 case CallingConv::X86_ThisCall:
10395 case CallingConv::Fast:
10396 // Pass 'nest' parameter in EAX.
10397 // Must be kept in sync with X86CallingConv.td
10398 NestReg = X86::EAX;
10402 SDValue OutChains[4];
10403 SDValue Addr, Disp;
10405 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10406 DAG.getConstant(10, MVT::i32));
10407 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10409 // This is storing the opcode for MOV32ri.
10410 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10411 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10412 OutChains[0] = DAG.getStore(Root, dl,
10413 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10414 Trmp, MachinePointerInfo(TrmpAddr),
10417 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10418 DAG.getConstant(1, MVT::i32));
10419 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10420 MachinePointerInfo(TrmpAddr, 1),
10423 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10424 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10425 DAG.getConstant(5, MVT::i32));
10426 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10427 MachinePointerInfo(TrmpAddr, 5),
10430 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10431 DAG.getConstant(6, MVT::i32));
10432 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10433 MachinePointerInfo(TrmpAddr, 6),
10436 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10440 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10441 SelectionDAG &DAG) const {
10443 The rounding mode is in bits 11:10 of FPSR, and has the following
10445 00 Round to nearest
10450 FLT_ROUNDS, on the other hand, expects the following:
10457 To perform the conversion, we do:
10458 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10461 MachineFunction &MF = DAG.getMachineFunction();
10462 const TargetMachine &TM = MF.getTarget();
10463 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10464 unsigned StackAlignment = TFI.getStackAlignment();
10465 EVT VT = Op.getValueType();
10466 DebugLoc DL = Op.getDebugLoc();
10468 // Save FP Control Word to stack slot
10469 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10470 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10473 MachineMemOperand *MMO =
10474 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10475 MachineMemOperand::MOStore, 2, 2);
10477 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10478 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10479 DAG.getVTList(MVT::Other),
10480 Ops, 2, MVT::i16, MMO);
10482 // Load FP Control Word from stack slot
10483 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10484 MachinePointerInfo(), false, false, false, 0);
10486 // Transform as necessary
10488 DAG.getNode(ISD::SRL, DL, MVT::i16,
10489 DAG.getNode(ISD::AND, DL, MVT::i16,
10490 CWD, DAG.getConstant(0x800, MVT::i16)),
10491 DAG.getConstant(11, MVT::i8));
10493 DAG.getNode(ISD::SRL, DL, MVT::i16,
10494 DAG.getNode(ISD::AND, DL, MVT::i16,
10495 CWD, DAG.getConstant(0x400, MVT::i16)),
10496 DAG.getConstant(9, MVT::i8));
10499 DAG.getNode(ISD::AND, DL, MVT::i16,
10500 DAG.getNode(ISD::ADD, DL, MVT::i16,
10501 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10502 DAG.getConstant(1, MVT::i16)),
10503 DAG.getConstant(3, MVT::i16));
10506 return DAG.getNode((VT.getSizeInBits() < 16 ?
10507 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10510 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10511 EVT VT = Op.getValueType();
10513 unsigned NumBits = VT.getSizeInBits();
10514 DebugLoc dl = Op.getDebugLoc();
10516 Op = Op.getOperand(0);
10517 if (VT == MVT::i8) {
10518 // Zero extend to i32 since there is not an i8 bsr.
10520 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10523 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10524 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10525 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10527 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10530 DAG.getConstant(NumBits+NumBits-1, OpVT),
10531 DAG.getConstant(X86::COND_E, MVT::i8),
10534 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10536 // Finally xor with NumBits-1.
10537 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10540 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10544 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10545 SelectionDAG &DAG) const {
10546 EVT VT = Op.getValueType();
10548 unsigned NumBits = VT.getSizeInBits();
10549 DebugLoc dl = Op.getDebugLoc();
10551 Op = Op.getOperand(0);
10552 if (VT == MVT::i8) {
10553 // Zero extend to i32 since there is not an i8 bsr.
10555 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10558 // Issue a bsr (scan bits in reverse).
10559 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10560 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10562 // And xor with NumBits-1.
10563 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10566 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10570 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10571 EVT VT = Op.getValueType();
10572 unsigned NumBits = VT.getSizeInBits();
10573 DebugLoc dl = Op.getDebugLoc();
10574 Op = Op.getOperand(0);
10576 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10577 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10578 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10580 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10583 DAG.getConstant(NumBits, VT),
10584 DAG.getConstant(X86::COND_E, MVT::i8),
10587 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10590 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10591 // ones, and then concatenate the result back.
10592 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10593 EVT VT = Op.getValueType();
10595 assert(VT.is256BitVector() && VT.isInteger() &&
10596 "Unsupported value type for operation");
10598 unsigned NumElems = VT.getVectorNumElements();
10599 DebugLoc dl = Op.getDebugLoc();
10601 // Extract the LHS vectors
10602 SDValue LHS = Op.getOperand(0);
10603 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10604 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10606 // Extract the RHS vectors
10607 SDValue RHS = Op.getOperand(1);
10608 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10609 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10611 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10612 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10614 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10615 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10616 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10619 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10620 assert(Op.getValueType().is256BitVector() &&
10621 Op.getValueType().isInteger() &&
10622 "Only handle AVX 256-bit vector integer operation");
10623 return Lower256IntArith(Op, DAG);
10626 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10627 assert(Op.getValueType().is256BitVector() &&
10628 Op.getValueType().isInteger() &&
10629 "Only handle AVX 256-bit vector integer operation");
10630 return Lower256IntArith(Op, DAG);
10633 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10634 EVT VT = Op.getValueType();
10636 // Decompose 256-bit ops into smaller 128-bit ops.
10637 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10638 return Lower256IntArith(Op, DAG);
10640 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10641 "Only know how to lower V2I64/V4I64 multiply");
10643 DebugLoc dl = Op.getDebugLoc();
10645 // Ahi = psrlqi(a, 32);
10646 // Bhi = psrlqi(b, 32);
10648 // AloBlo = pmuludq(a, b);
10649 // AloBhi = pmuludq(a, Bhi);
10650 // AhiBlo = pmuludq(Ahi, b);
10652 // AloBhi = psllqi(AloBhi, 32);
10653 // AhiBlo = psllqi(AhiBlo, 32);
10654 // return AloBlo + AloBhi + AhiBlo;
10656 SDValue A = Op.getOperand(0);
10657 SDValue B = Op.getOperand(1);
10659 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10661 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10662 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10664 // Bit cast to 32-bit vectors for MULUDQ
10665 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10666 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10667 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10668 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10669 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10671 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10672 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10673 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10675 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10676 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10678 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10679 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10682 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10684 EVT VT = Op.getValueType();
10685 DebugLoc dl = Op.getDebugLoc();
10686 SDValue R = Op.getOperand(0);
10687 SDValue Amt = Op.getOperand(1);
10688 LLVMContext *Context = DAG.getContext();
10690 if (!Subtarget->hasSSE2())
10693 // Optimize shl/srl/sra with constant shift amount.
10694 if (isSplatVector(Amt.getNode())) {
10695 SDValue SclrAmt = Amt->getOperand(0);
10696 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10697 uint64_t ShiftAmt = C->getZExtValue();
10699 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10700 (Subtarget->hasAVX2() &&
10701 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10702 if (Op.getOpcode() == ISD::SHL)
10703 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10704 DAG.getConstant(ShiftAmt, MVT::i32));
10705 if (Op.getOpcode() == ISD::SRL)
10706 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10707 DAG.getConstant(ShiftAmt, MVT::i32));
10708 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10709 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10710 DAG.getConstant(ShiftAmt, MVT::i32));
10713 if (VT == MVT::v16i8) {
10714 if (Op.getOpcode() == ISD::SHL) {
10715 // Make a large shift.
10716 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10717 DAG.getConstant(ShiftAmt, MVT::i32));
10718 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10719 // Zero out the rightmost bits.
10720 SmallVector<SDValue, 16> V(16,
10721 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10723 return DAG.getNode(ISD::AND, dl, VT, SHL,
10724 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10726 if (Op.getOpcode() == ISD::SRL) {
10727 // Make a large shift.
10728 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10729 DAG.getConstant(ShiftAmt, MVT::i32));
10730 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10731 // Zero out the leftmost bits.
10732 SmallVector<SDValue, 16> V(16,
10733 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10735 return DAG.getNode(ISD::AND, dl, VT, SRL,
10736 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10738 if (Op.getOpcode() == ISD::SRA) {
10739 if (ShiftAmt == 7) {
10740 // R s>> 7 === R s< 0
10741 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10742 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10745 // R s>> a === ((R u>> a) ^ m) - m
10746 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10747 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10749 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10750 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10751 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10754 llvm_unreachable("Unknown shift opcode.");
10757 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10758 if (Op.getOpcode() == ISD::SHL) {
10759 // Make a large shift.
10760 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10761 DAG.getConstant(ShiftAmt, MVT::i32));
10762 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10763 // Zero out the rightmost bits.
10764 SmallVector<SDValue, 32> V(32,
10765 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10767 return DAG.getNode(ISD::AND, dl, VT, SHL,
10768 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10770 if (Op.getOpcode() == ISD::SRL) {
10771 // Make a large shift.
10772 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10773 DAG.getConstant(ShiftAmt, MVT::i32));
10774 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10775 // Zero out the leftmost bits.
10776 SmallVector<SDValue, 32> V(32,
10777 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10779 return DAG.getNode(ISD::AND, dl, VT, SRL,
10780 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10782 if (Op.getOpcode() == ISD::SRA) {
10783 if (ShiftAmt == 7) {
10784 // R s>> 7 === R s< 0
10785 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10786 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10789 // R s>> a === ((R u>> a) ^ m) - m
10790 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10791 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10793 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10794 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10795 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10798 llvm_unreachable("Unknown shift opcode.");
10803 // Lower SHL with variable shift amount.
10804 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10805 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10806 DAG.getConstant(23, MVT::i32));
10808 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10809 Constant *C = ConstantDataVector::get(*Context, CV);
10810 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10811 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10812 MachinePointerInfo::getConstantPool(),
10813 false, false, false, 16);
10815 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10816 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10817 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10818 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10820 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10821 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10824 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10825 DAG.getConstant(5, MVT::i32));
10826 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10828 // Turn 'a' into a mask suitable for VSELECT
10829 SDValue VSelM = DAG.getConstant(0x80, VT);
10830 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10831 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10833 SDValue CM1 = DAG.getConstant(0x0f, VT);
10834 SDValue CM2 = DAG.getConstant(0x3f, VT);
10836 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10837 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10838 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10839 DAG.getConstant(4, MVT::i32), DAG);
10840 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10841 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10844 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10845 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10846 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10848 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10849 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10850 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10851 DAG.getConstant(2, MVT::i32), DAG);
10852 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10853 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10856 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10857 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10858 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10860 // return VSELECT(r, r+r, a);
10861 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10862 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10866 // Decompose 256-bit shifts into smaller 128-bit shifts.
10867 if (VT.is256BitVector()) {
10868 unsigned NumElems = VT.getVectorNumElements();
10869 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10870 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10872 // Extract the two vectors
10873 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10874 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10876 // Recreate the shift amount vectors
10877 SDValue Amt1, Amt2;
10878 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10879 // Constant shift amount
10880 SmallVector<SDValue, 4> Amt1Csts;
10881 SmallVector<SDValue, 4> Amt2Csts;
10882 for (unsigned i = 0; i != NumElems/2; ++i)
10883 Amt1Csts.push_back(Amt->getOperand(i));
10884 for (unsigned i = NumElems/2; i != NumElems; ++i)
10885 Amt2Csts.push_back(Amt->getOperand(i));
10887 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10888 &Amt1Csts[0], NumElems/2);
10889 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10890 &Amt2Csts[0], NumElems/2);
10892 // Variable shift amount
10893 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10894 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10897 // Issue new vector shifts for the smaller types
10898 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10899 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10901 // Concatenate the result back
10902 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10908 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10909 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10910 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10911 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10912 // has only one use.
10913 SDNode *N = Op.getNode();
10914 SDValue LHS = N->getOperand(0);
10915 SDValue RHS = N->getOperand(1);
10916 unsigned BaseOp = 0;
10918 DebugLoc DL = Op.getDebugLoc();
10919 switch (Op.getOpcode()) {
10920 default: llvm_unreachable("Unknown ovf instruction!");
10922 // A subtract of one will be selected as a INC. Note that INC doesn't
10923 // set CF, so we can't do this for UADDO.
10924 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10926 BaseOp = X86ISD::INC;
10927 Cond = X86::COND_O;
10930 BaseOp = X86ISD::ADD;
10931 Cond = X86::COND_O;
10934 BaseOp = X86ISD::ADD;
10935 Cond = X86::COND_B;
10938 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10939 // set CF, so we can't do this for USUBO.
10940 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10942 BaseOp = X86ISD::DEC;
10943 Cond = X86::COND_O;
10946 BaseOp = X86ISD::SUB;
10947 Cond = X86::COND_O;
10950 BaseOp = X86ISD::SUB;
10951 Cond = X86::COND_B;
10954 BaseOp = X86ISD::SMUL;
10955 Cond = X86::COND_O;
10957 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10958 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10960 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10963 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10964 DAG.getConstant(X86::COND_O, MVT::i32),
10965 SDValue(Sum.getNode(), 2));
10967 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10971 // Also sets EFLAGS.
10972 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10973 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10976 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10977 DAG.getConstant(Cond, MVT::i32),
10978 SDValue(Sum.getNode(), 1));
10980 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10983 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10984 SelectionDAG &DAG) const {
10985 DebugLoc dl = Op.getDebugLoc();
10986 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10987 EVT VT = Op.getValueType();
10989 if (!Subtarget->hasSSE2() || !VT.isVector())
10992 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10993 ExtraVT.getScalarType().getSizeInBits();
10994 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10996 switch (VT.getSimpleVT().SimpleTy) {
10997 default: return SDValue();
11000 if (!Subtarget->hasAVX())
11002 if (!Subtarget->hasAVX2()) {
11003 // needs to be split
11004 unsigned NumElems = VT.getVectorNumElements();
11006 // Extract the LHS vectors
11007 SDValue LHS = Op.getOperand(0);
11008 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11009 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11011 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11012 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11014 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11015 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11016 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11018 SDValue Extra = DAG.getValueType(ExtraVT);
11020 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11021 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11023 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
11028 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11029 Op.getOperand(0), ShAmt, DAG);
11030 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11036 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
11037 DebugLoc dl = Op.getDebugLoc();
11039 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11040 // There isn't any reason to disable it if the target processor supports it.
11041 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11042 SDValue Chain = Op.getOperand(0);
11043 SDValue Zero = DAG.getConstant(0, MVT::i32);
11045 DAG.getRegister(X86::ESP, MVT::i32), // Base
11046 DAG.getTargetConstant(1, MVT::i8), // Scale
11047 DAG.getRegister(0, MVT::i32), // Index
11048 DAG.getTargetConstant(0, MVT::i32), // Disp
11049 DAG.getRegister(0, MVT::i32), // Segment.
11054 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11055 array_lengthof(Ops));
11056 return SDValue(Res, 0);
11059 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11061 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11063 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11064 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11065 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11066 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11068 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11069 if (!Op1 && !Op2 && !Op3 && Op4)
11070 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11072 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11073 if (Op1 && !Op2 && !Op3 && !Op4)
11074 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11076 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11078 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11081 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11082 SelectionDAG &DAG) const {
11083 DebugLoc dl = Op.getDebugLoc();
11084 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11085 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11086 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11087 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11089 // The only fence that needs an instruction is a sequentially-consistent
11090 // cross-thread fence.
11091 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11092 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11093 // no-sse2). There isn't any reason to disable it if the target processor
11095 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11096 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11098 SDValue Chain = Op.getOperand(0);
11099 SDValue Zero = DAG.getConstant(0, MVT::i32);
11101 DAG.getRegister(X86::ESP, MVT::i32), // Base
11102 DAG.getTargetConstant(1, MVT::i8), // Scale
11103 DAG.getRegister(0, MVT::i32), // Index
11104 DAG.getTargetConstant(0, MVT::i32), // Disp
11105 DAG.getRegister(0, MVT::i32), // Segment.
11110 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11111 array_lengthof(Ops));
11112 return SDValue(Res, 0);
11115 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11116 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11120 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11121 EVT T = Op.getValueType();
11122 DebugLoc DL = Op.getDebugLoc();
11125 switch(T.getSimpleVT().SimpleTy) {
11126 default: llvm_unreachable("Invalid value type!");
11127 case MVT::i8: Reg = X86::AL; size = 1; break;
11128 case MVT::i16: Reg = X86::AX; size = 2; break;
11129 case MVT::i32: Reg = X86::EAX; size = 4; break;
11131 assert(Subtarget->is64Bit() && "Node not type legal!");
11132 Reg = X86::RAX; size = 8;
11135 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11136 Op.getOperand(2), SDValue());
11137 SDValue Ops[] = { cpIn.getValue(0),
11140 DAG.getTargetConstant(size, MVT::i8),
11141 cpIn.getValue(1) };
11142 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11143 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11144 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11147 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11151 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11152 SelectionDAG &DAG) const {
11153 assert(Subtarget->is64Bit() && "Result not type legalized?");
11154 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11155 SDValue TheChain = Op.getOperand(0);
11156 DebugLoc dl = Op.getDebugLoc();
11157 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11158 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11159 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11161 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11162 DAG.getConstant(32, MVT::i8));
11164 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11167 return DAG.getMergeValues(Ops, 2, dl);
11170 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11171 SelectionDAG &DAG) const {
11172 EVT SrcVT = Op.getOperand(0).getValueType();
11173 EVT DstVT = Op.getValueType();
11174 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11175 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11176 assert((DstVT == MVT::i64 ||
11177 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11178 "Unexpected custom BITCAST");
11179 // i64 <=> MMX conversions are Legal.
11180 if (SrcVT==MVT::i64 && DstVT.isVector())
11182 if (DstVT==MVT::i64 && SrcVT.isVector())
11184 // MMX <=> MMX conversions are Legal.
11185 if (SrcVT.isVector() && DstVT.isVector())
11187 // All other conversions need to be expanded.
11191 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11192 SDNode *Node = Op.getNode();
11193 DebugLoc dl = Node->getDebugLoc();
11194 EVT T = Node->getValueType(0);
11195 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11196 DAG.getConstant(0, T), Node->getOperand(2));
11197 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11198 cast<AtomicSDNode>(Node)->getMemoryVT(),
11199 Node->getOperand(0),
11200 Node->getOperand(1), negOp,
11201 cast<AtomicSDNode>(Node)->getSrcValue(),
11202 cast<AtomicSDNode>(Node)->getAlignment(),
11203 cast<AtomicSDNode>(Node)->getOrdering(),
11204 cast<AtomicSDNode>(Node)->getSynchScope());
11207 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11208 SDNode *Node = Op.getNode();
11209 DebugLoc dl = Node->getDebugLoc();
11210 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11212 // Convert seq_cst store -> xchg
11213 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11214 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11215 // (The only way to get a 16-byte store is cmpxchg16b)
11216 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11217 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11218 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11219 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11220 cast<AtomicSDNode>(Node)->getMemoryVT(),
11221 Node->getOperand(0),
11222 Node->getOperand(1), Node->getOperand(2),
11223 cast<AtomicSDNode>(Node)->getMemOperand(),
11224 cast<AtomicSDNode>(Node)->getOrdering(),
11225 cast<AtomicSDNode>(Node)->getSynchScope());
11226 return Swap.getValue(1);
11228 // Other atomic stores have a simple pattern.
11232 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11233 EVT VT = Op.getNode()->getValueType(0);
11235 // Let legalize expand this if it isn't a legal type yet.
11236 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11239 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11242 bool ExtraOp = false;
11243 switch (Op.getOpcode()) {
11244 default: llvm_unreachable("Invalid code");
11245 case ISD::ADDC: Opc = X86ISD::ADD; break;
11246 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11247 case ISD::SUBC: Opc = X86ISD::SUB; break;
11248 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11252 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11254 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11255 Op.getOperand(1), Op.getOperand(2));
11258 /// LowerOperation - Provide custom lowering hooks for some operations.
11260 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11261 switch (Op.getOpcode()) {
11262 default: llvm_unreachable("Should not custom lower this!");
11263 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11264 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
11265 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
11266 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
11267 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11268 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11269 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11270 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11271 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11272 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11273 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11274 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
11275 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
11276 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11277 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11278 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11279 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11280 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11281 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11282 case ISD::SHL_PARTS:
11283 case ISD::SRA_PARTS:
11284 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11285 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11286 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11287 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11288 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11289 case ISD::FABS: return LowerFABS(Op, DAG);
11290 case ISD::FNEG: return LowerFNEG(Op, DAG);
11291 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11292 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11293 case ISD::SETCC: return LowerSETCC(Op, DAG);
11294 case ISD::SELECT: return LowerSELECT(Op, DAG);
11295 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11296 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11297 case ISD::VASTART: return LowerVASTART(Op, DAG);
11298 case ISD::VAARG: return LowerVAARG(Op, DAG);
11299 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
11300 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11301 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11302 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11303 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11304 case ISD::FRAME_TO_ARGS_OFFSET:
11305 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11306 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11307 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11308 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11309 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11310 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11311 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11312 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11313 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11314 case ISD::MUL: return LowerMUL(Op, DAG);
11317 case ISD::SHL: return LowerShift(Op, DAG);
11323 case ISD::UMULO: return LowerXALUO(Op, DAG);
11324 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
11325 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11329 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11330 case ISD::ADD: return LowerADD(Op, DAG);
11331 case ISD::SUB: return LowerSUB(Op, DAG);
11335 static void ReplaceATOMIC_LOAD(SDNode *Node,
11336 SmallVectorImpl<SDValue> &Results,
11337 SelectionDAG &DAG) {
11338 DebugLoc dl = Node->getDebugLoc();
11339 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11341 // Convert wide load -> cmpxchg8b/cmpxchg16b
11342 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11343 // (The only way to get a 16-byte load is cmpxchg16b)
11344 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11345 SDValue Zero = DAG.getConstant(0, VT);
11346 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11347 Node->getOperand(0),
11348 Node->getOperand(1), Zero, Zero,
11349 cast<AtomicSDNode>(Node)->getMemOperand(),
11350 cast<AtomicSDNode>(Node)->getOrdering(),
11351 cast<AtomicSDNode>(Node)->getSynchScope());
11352 Results.push_back(Swap.getValue(0));
11353 Results.push_back(Swap.getValue(1));
11357 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11358 SelectionDAG &DAG, unsigned NewOp) {
11359 DebugLoc dl = Node->getDebugLoc();
11360 assert (Node->getValueType(0) == MVT::i64 &&
11361 "Only know how to expand i64 atomics");
11363 SDValue Chain = Node->getOperand(0);
11364 SDValue In1 = Node->getOperand(1);
11365 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11366 Node->getOperand(2), DAG.getIntPtrConstant(0));
11367 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11368 Node->getOperand(2), DAG.getIntPtrConstant(1));
11369 SDValue Ops[] = { Chain, In1, In2L, In2H };
11370 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11372 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11373 cast<MemSDNode>(Node)->getMemOperand());
11374 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11375 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11376 Results.push_back(Result.getValue(2));
11379 /// ReplaceNodeResults - Replace a node with an illegal result type
11380 /// with a new node built out of custom code.
11381 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11382 SmallVectorImpl<SDValue>&Results,
11383 SelectionDAG &DAG) const {
11384 DebugLoc dl = N->getDebugLoc();
11385 switch (N->getOpcode()) {
11387 llvm_unreachable("Do not know how to custom type legalize this operation!");
11388 case ISD::SIGN_EXTEND_INREG:
11393 // We don't want to expand or promote these.
11395 case ISD::FP_TO_SINT:
11396 case ISD::FP_TO_UINT: {
11397 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11399 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11402 std::pair<SDValue,SDValue> Vals =
11403 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11404 SDValue FIST = Vals.first, StackSlot = Vals.second;
11405 if (FIST.getNode() != 0) {
11406 EVT VT = N->getValueType(0);
11407 // Return a load from the stack slot.
11408 if (StackSlot.getNode() != 0)
11409 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11410 MachinePointerInfo(),
11411 false, false, false, 0));
11413 Results.push_back(FIST);
11417 case ISD::READCYCLECOUNTER: {
11418 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11419 SDValue TheChain = N->getOperand(0);
11420 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11421 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11423 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11425 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11426 SDValue Ops[] = { eax, edx };
11427 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11428 Results.push_back(edx.getValue(1));
11431 case ISD::ATOMIC_CMP_SWAP: {
11432 EVT T = N->getValueType(0);
11433 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11434 bool Regs64bit = T == MVT::i128;
11435 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11436 SDValue cpInL, cpInH;
11437 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11438 DAG.getConstant(0, HalfT));
11439 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11440 DAG.getConstant(1, HalfT));
11441 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11442 Regs64bit ? X86::RAX : X86::EAX,
11444 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11445 Regs64bit ? X86::RDX : X86::EDX,
11446 cpInH, cpInL.getValue(1));
11447 SDValue swapInL, swapInH;
11448 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11449 DAG.getConstant(0, HalfT));
11450 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11451 DAG.getConstant(1, HalfT));
11452 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11453 Regs64bit ? X86::RBX : X86::EBX,
11454 swapInL, cpInH.getValue(1));
11455 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11456 Regs64bit ? X86::RCX : X86::ECX,
11457 swapInH, swapInL.getValue(1));
11458 SDValue Ops[] = { swapInH.getValue(0),
11460 swapInH.getValue(1) };
11461 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11462 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11463 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11464 X86ISD::LCMPXCHG8_DAG;
11465 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11467 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11468 Regs64bit ? X86::RAX : X86::EAX,
11469 HalfT, Result.getValue(1));
11470 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11471 Regs64bit ? X86::RDX : X86::EDX,
11472 HalfT, cpOutL.getValue(2));
11473 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11474 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11475 Results.push_back(cpOutH.getValue(1));
11478 case ISD::ATOMIC_LOAD_ADD:
11479 case ISD::ATOMIC_LOAD_AND:
11480 case ISD::ATOMIC_LOAD_NAND:
11481 case ISD::ATOMIC_LOAD_OR:
11482 case ISD::ATOMIC_LOAD_SUB:
11483 case ISD::ATOMIC_LOAD_XOR:
11484 case ISD::ATOMIC_SWAP: {
11486 switch (N->getOpcode()) {
11487 default: llvm_unreachable("Unexpected opcode");
11488 case ISD::ATOMIC_LOAD_ADD:
11489 Opc = X86ISD::ATOMADD64_DAG;
11491 case ISD::ATOMIC_LOAD_AND:
11492 Opc = X86ISD::ATOMAND64_DAG;
11494 case ISD::ATOMIC_LOAD_NAND:
11495 Opc = X86ISD::ATOMNAND64_DAG;
11497 case ISD::ATOMIC_LOAD_OR:
11498 Opc = X86ISD::ATOMOR64_DAG;
11500 case ISD::ATOMIC_LOAD_SUB:
11501 Opc = X86ISD::ATOMSUB64_DAG;
11503 case ISD::ATOMIC_LOAD_XOR:
11504 Opc = X86ISD::ATOMXOR64_DAG;
11506 case ISD::ATOMIC_SWAP:
11507 Opc = X86ISD::ATOMSWAP64_DAG;
11510 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11513 case ISD::ATOMIC_LOAD:
11514 ReplaceATOMIC_LOAD(N, Results, DAG);
11518 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11520 default: return NULL;
11521 case X86ISD::BSF: return "X86ISD::BSF";
11522 case X86ISD::BSR: return "X86ISD::BSR";
11523 case X86ISD::SHLD: return "X86ISD::SHLD";
11524 case X86ISD::SHRD: return "X86ISD::SHRD";
11525 case X86ISD::FAND: return "X86ISD::FAND";
11526 case X86ISD::FOR: return "X86ISD::FOR";
11527 case X86ISD::FXOR: return "X86ISD::FXOR";
11528 case X86ISD::FSRL: return "X86ISD::FSRL";
11529 case X86ISD::FILD: return "X86ISD::FILD";
11530 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11531 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11532 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11533 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11534 case X86ISD::FLD: return "X86ISD::FLD";
11535 case X86ISD::FST: return "X86ISD::FST";
11536 case X86ISD::CALL: return "X86ISD::CALL";
11537 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11538 case X86ISD::BT: return "X86ISD::BT";
11539 case X86ISD::CMP: return "X86ISD::CMP";
11540 case X86ISD::COMI: return "X86ISD::COMI";
11541 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11542 case X86ISD::SETCC: return "X86ISD::SETCC";
11543 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11544 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11545 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11546 case X86ISD::CMOV: return "X86ISD::CMOV";
11547 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11548 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11549 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11550 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11551 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11552 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11553 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11554 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11555 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11556 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11557 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11558 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11559 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11560 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11561 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11562 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11563 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11564 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11565 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11566 case X86ISD::HADD: return "X86ISD::HADD";
11567 case X86ISD::HSUB: return "X86ISD::HSUB";
11568 case X86ISD::FHADD: return "X86ISD::FHADD";
11569 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11570 case X86ISD::FMAX: return "X86ISD::FMAX";
11571 case X86ISD::FMIN: return "X86ISD::FMIN";
11572 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11573 case X86ISD::FMINC: return "X86ISD::FMINC";
11574 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11575 case X86ISD::FRCP: return "X86ISD::FRCP";
11576 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11577 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11578 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11579 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11580 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11581 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11582 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11583 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11584 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11585 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11586 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11587 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11588 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11589 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11590 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11591 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11592 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11593 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11594 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11595 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11596 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11597 case X86ISD::VSHL: return "X86ISD::VSHL";
11598 case X86ISD::VSRL: return "X86ISD::VSRL";
11599 case X86ISD::VSRA: return "X86ISD::VSRA";
11600 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11601 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11602 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11603 case X86ISD::CMPP: return "X86ISD::CMPP";
11604 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11605 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11606 case X86ISD::ADD: return "X86ISD::ADD";
11607 case X86ISD::SUB: return "X86ISD::SUB";
11608 case X86ISD::ADC: return "X86ISD::ADC";
11609 case X86ISD::SBB: return "X86ISD::SBB";
11610 case X86ISD::SMUL: return "X86ISD::SMUL";
11611 case X86ISD::UMUL: return "X86ISD::UMUL";
11612 case X86ISD::INC: return "X86ISD::INC";
11613 case X86ISD::DEC: return "X86ISD::DEC";
11614 case X86ISD::OR: return "X86ISD::OR";
11615 case X86ISD::XOR: return "X86ISD::XOR";
11616 case X86ISD::AND: return "X86ISD::AND";
11617 case X86ISD::ANDN: return "X86ISD::ANDN";
11618 case X86ISD::BLSI: return "X86ISD::BLSI";
11619 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11620 case X86ISD::BLSR: return "X86ISD::BLSR";
11621 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11622 case X86ISD::PTEST: return "X86ISD::PTEST";
11623 case X86ISD::TESTP: return "X86ISD::TESTP";
11624 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11625 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11626 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11627 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11628 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11629 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11630 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11631 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11632 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11633 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11634 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11635 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11636 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11637 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11638 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11639 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11640 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11641 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11642 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11643 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11644 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11645 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11646 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11647 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11648 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11649 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11650 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11651 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11652 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11653 case X86ISD::SAHF: return "X86ISD::SAHF";
11654 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11655 case X86ISD::FMADD: return "X86ISD::FMADD";
11656 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11657 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11658 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11659 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11660 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11664 // isLegalAddressingMode - Return true if the addressing mode represented
11665 // by AM is legal for this target, for a load/store of the specified type.
11666 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11668 // X86 supports extremely general addressing modes.
11669 CodeModel::Model M = getTargetMachine().getCodeModel();
11670 Reloc::Model R = getTargetMachine().getRelocationModel();
11672 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11673 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11678 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11680 // If a reference to this global requires an extra load, we can't fold it.
11681 if (isGlobalStubReference(GVFlags))
11684 // If BaseGV requires a register for the PIC base, we cannot also have a
11685 // BaseReg specified.
11686 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11689 // If lower 4G is not available, then we must use rip-relative addressing.
11690 if ((M != CodeModel::Small || R != Reloc::Static) &&
11691 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11695 switch (AM.Scale) {
11701 // These scales always work.
11706 // These scales are formed with basereg+scalereg. Only accept if there is
11711 default: // Other stuff never works.
11719 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11720 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11722 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11723 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11724 if (NumBits1 <= NumBits2)
11729 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11730 return Imm == (int32_t)Imm;
11733 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11734 // Can also use sub to handle negated immediates.
11735 return Imm == (int32_t)Imm;
11738 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11739 if (!VT1.isInteger() || !VT2.isInteger())
11741 unsigned NumBits1 = VT1.getSizeInBits();
11742 unsigned NumBits2 = VT2.getSizeInBits();
11743 if (NumBits1 <= NumBits2)
11748 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11749 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11750 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11753 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11754 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11755 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11758 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11759 // i16 instructions are longer (0x66 prefix) and potentially slower.
11760 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11763 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11764 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11765 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11766 /// are assumed to be legal.
11768 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11770 // Very little shuffling can be done for 64-bit vectors right now.
11771 if (VT.getSizeInBits() == 64)
11774 // FIXME: pshufb, blends, shifts.
11775 return (VT.getVectorNumElements() == 2 ||
11776 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11777 isMOVLMask(M, VT) ||
11778 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11779 isPSHUFDMask(M, VT) ||
11780 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11781 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11782 isPALIGNRMask(M, VT, Subtarget) ||
11783 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11784 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11785 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11786 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11790 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11792 unsigned NumElts = VT.getVectorNumElements();
11793 // FIXME: This collection of masks seems suspect.
11796 if (NumElts == 4 && VT.is128BitVector()) {
11797 return (isMOVLMask(Mask, VT) ||
11798 isCommutedMOVLMask(Mask, VT, true) ||
11799 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11800 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11805 //===----------------------------------------------------------------------===//
11806 // X86 Scheduler Hooks
11807 //===----------------------------------------------------------------------===//
11809 // private utility function
11810 MachineBasicBlock *
11811 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11812 MachineBasicBlock *MBB,
11819 const TargetRegisterClass *RC,
11820 bool Invert) const {
11821 // For the atomic bitwise operator, we generate
11824 // ld t1 = [bitinstr.addr]
11825 // op t2 = t1, [bitinstr.val]
11826 // not t3 = t2 (if Invert)
11828 // lcs dest = [bitinstr.addr], t3 [EAX is implicit]
11830 // fallthrough -->nextMBB
11831 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11832 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11833 MachineFunction::iterator MBBIter = MBB;
11836 /// First build the CFG
11837 MachineFunction *F = MBB->getParent();
11838 MachineBasicBlock *thisMBB = MBB;
11839 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11840 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11841 F->insert(MBBIter, newMBB);
11842 F->insert(MBBIter, nextMBB);
11844 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11845 nextMBB->splice(nextMBB->begin(), thisMBB,
11846 llvm::next(MachineBasicBlock::iterator(bInstr)),
11848 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11850 // Update thisMBB to fall through to newMBB
11851 thisMBB->addSuccessor(newMBB);
11853 // newMBB jumps to itself and fall through to nextMBB
11854 newMBB->addSuccessor(nextMBB);
11855 newMBB->addSuccessor(newMBB);
11857 // Insert instructions into newMBB based on incoming instruction
11858 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11859 "unexpected number of operands");
11860 DebugLoc dl = bInstr->getDebugLoc();
11861 MachineOperand& destOper = bInstr->getOperand(0);
11862 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11863 int numArgs = bInstr->getNumOperands() - 1;
11864 for (int i=0; i < numArgs; ++i)
11865 argOpers[i] = &bInstr->getOperand(i+1);
11867 // x86 address has 4 operands: base, index, scale, and displacement
11868 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11869 int valArgIndx = lastAddrIndx + 1;
11871 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11872 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11873 for (int i=0; i <= lastAddrIndx; ++i)
11874 (*MIB).addOperand(*argOpers[i]);
11876 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11877 assert((argOpers[valArgIndx]->isReg() ||
11878 argOpers[valArgIndx]->isImm()) &&
11879 "invalid operand");
11880 if (argOpers[valArgIndx]->isReg())
11881 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11883 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11885 (*MIB).addOperand(*argOpers[valArgIndx]);
11887 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11889 MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11894 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11897 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11898 for (int i=0; i <= lastAddrIndx; ++i)
11899 (*MIB).addOperand(*argOpers[i]);
11901 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11902 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11903 bInstr->memoperands_end());
11905 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11906 MIB.addReg(EAXreg);
11909 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11911 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11915 // private utility function: 64 bit atomics on 32 bit host.
11916 MachineBasicBlock *
11917 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11918 MachineBasicBlock *MBB,
11923 bool Invert) const {
11924 // For the atomic bitwise operator, we generate
11925 // thisMBB (instructions are in pairs, except cmpxchg8b)
11926 // ld t1,t2 = [bitinstr.addr]
11928 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11929 // op t5, t6 <- out1, out2, [bitinstr.val]
11930 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11931 // neg t7, t8 < t5, t6 (if Invert)
11932 // mov ECX, EBX <- t5, t6
11933 // mov EAX, EDX <- t1, t2
11934 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11935 // mov t3, t4 <- EAX, EDX
11937 // result in out1, out2
11938 // fallthrough -->nextMBB
11940 const TargetRegisterClass *RC = &X86::GR32RegClass;
11941 const unsigned LoadOpc = X86::MOV32rm;
11942 const unsigned NotOpc = X86::NOT32r;
11943 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11944 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11945 MachineFunction::iterator MBBIter = MBB;
11948 /// First build the CFG
11949 MachineFunction *F = MBB->getParent();
11950 MachineBasicBlock *thisMBB = MBB;
11951 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11952 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11953 F->insert(MBBIter, newMBB);
11954 F->insert(MBBIter, nextMBB);
11956 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11957 nextMBB->splice(nextMBB->begin(), thisMBB,
11958 llvm::next(MachineBasicBlock::iterator(bInstr)),
11960 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11962 // Update thisMBB to fall through to newMBB
11963 thisMBB->addSuccessor(newMBB);
11965 // newMBB jumps to itself and fall through to nextMBB
11966 newMBB->addSuccessor(nextMBB);
11967 newMBB->addSuccessor(newMBB);
11969 DebugLoc dl = bInstr->getDebugLoc();
11970 // Insert instructions into newMBB based on incoming instruction
11971 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11972 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11973 "unexpected number of operands");
11974 MachineOperand& dest1Oper = bInstr->getOperand(0);
11975 MachineOperand& dest2Oper = bInstr->getOperand(1);
11976 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11977 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11978 argOpers[i] = &bInstr->getOperand(i+2);
11980 // We use some of the operands multiple times, so conservatively just
11981 // clear any kill flags that might be present.
11982 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11983 argOpers[i]->setIsKill(false);
11986 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11987 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11989 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11990 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11991 for (int i=0; i <= lastAddrIndx; ++i)
11992 (*MIB).addOperand(*argOpers[i]);
11993 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11994 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11995 // add 4 to displacement.
11996 for (int i=0; i <= lastAddrIndx-2; ++i)
11997 (*MIB).addOperand(*argOpers[i]);
11998 MachineOperand newOp3 = *(argOpers[3]);
11999 if (newOp3.isImm())
12000 newOp3.setImm(newOp3.getImm()+4);
12002 newOp3.setOffset(newOp3.getOffset()+4);
12003 (*MIB).addOperand(newOp3);
12004 (*MIB).addOperand(*argOpers[lastAddrIndx]);
12006 // t3/4 are defined later, at the bottom of the loop
12007 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
12008 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
12009 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
12010 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
12011 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
12012 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
12014 // The subsequent operations should be using the destination registers of
12015 // the PHI instructions.
12016 t1 = dest1Oper.getReg();
12017 t2 = dest2Oper.getReg();
12019 int valArgIndx = lastAddrIndx + 1;
12020 assert((argOpers[valArgIndx]->isReg() ||
12021 argOpers[valArgIndx]->isImm()) &&
12022 "invalid operand");
12023 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
12024 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
12025 if (argOpers[valArgIndx]->isReg())
12026 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
12028 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
12029 if (regOpcL != X86::MOV32rr)
12031 (*MIB).addOperand(*argOpers[valArgIndx]);
12032 assert(argOpers[valArgIndx + 1]->isReg() ==
12033 argOpers[valArgIndx]->isReg());
12034 assert(argOpers[valArgIndx + 1]->isImm() ==
12035 argOpers[valArgIndx]->isImm());
12036 if (argOpers[valArgIndx + 1]->isReg())
12037 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
12039 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
12040 if (regOpcH != X86::MOV32rr)
12042 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
12046 t7 = F->getRegInfo().createVirtualRegister(RC);
12047 t8 = F->getRegInfo().createVirtualRegister(RC);
12048 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
12049 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
12055 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12057 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
12060 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
12062 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
12065 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
12066 for (int i=0; i <= lastAddrIndx; ++i)
12067 (*MIB).addOperand(*argOpers[i]);
12069 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12070 (*MIB).setMemRefs(bInstr->memoperands_begin(),
12071 bInstr->memoperands_end());
12073 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12074 MIB.addReg(X86::EAX);
12075 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12076 MIB.addReg(X86::EDX);
12079 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12081 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
12085 // private utility function
12086 MachineBasicBlock *
12087 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12088 MachineBasicBlock *MBB,
12089 unsigned cmovOpc) const {
12090 // For the atomic min/max operator, we generate
12093 // ld t1 = [min/max.addr]
12094 // mov t2 = [min/max.val]
12096 // cmov[cond] t2 = t1
12098 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
12100 // fallthrough -->nextMBB
12102 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12103 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12104 MachineFunction::iterator MBBIter = MBB;
12107 /// First build the CFG
12108 MachineFunction *F = MBB->getParent();
12109 MachineBasicBlock *thisMBB = MBB;
12110 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12111 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12112 F->insert(MBBIter, newMBB);
12113 F->insert(MBBIter, nextMBB);
12115 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12116 nextMBB->splice(nextMBB->begin(), thisMBB,
12117 llvm::next(MachineBasicBlock::iterator(mInstr)),
12119 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12121 // Update thisMBB to fall through to newMBB
12122 thisMBB->addSuccessor(newMBB);
12124 // newMBB jumps to newMBB and fall through to nextMBB
12125 newMBB->addSuccessor(nextMBB);
12126 newMBB->addSuccessor(newMBB);
12128 DebugLoc dl = mInstr->getDebugLoc();
12129 // Insert instructions into newMBB based on incoming instruction
12130 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12131 "unexpected number of operands");
12132 MachineOperand& destOper = mInstr->getOperand(0);
12133 MachineOperand* argOpers[2 + X86::AddrNumOperands];
12134 int numArgs = mInstr->getNumOperands() - 1;
12135 for (int i=0; i < numArgs; ++i)
12136 argOpers[i] = &mInstr->getOperand(i+1);
12138 // x86 address has 4 operands: base, index, scale, and displacement
12139 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12140 int valArgIndx = lastAddrIndx + 1;
12142 unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12143 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12144 for (int i=0; i <= lastAddrIndx; ++i)
12145 (*MIB).addOperand(*argOpers[i]);
12147 // We only support register and immediate values
12148 assert((argOpers[valArgIndx]->isReg() ||
12149 argOpers[valArgIndx]->isImm()) &&
12150 "invalid operand");
12152 unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12153 if (argOpers[valArgIndx]->isReg())
12154 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12156 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12157 (*MIB).addOperand(*argOpers[valArgIndx]);
12159 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12162 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12167 unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12168 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12172 // Cmp and exchange if none has modified the memory location
12173 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12174 for (int i=0; i <= lastAddrIndx; ++i)
12175 (*MIB).addOperand(*argOpers[i]);
12177 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12178 (*MIB).setMemRefs(mInstr->memoperands_begin(),
12179 mInstr->memoperands_end());
12181 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12182 MIB.addReg(X86::EAX);
12185 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12187 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
12191 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12192 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12193 // in the .td file.
12194 MachineBasicBlock *
12195 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12196 unsigned numArgs, bool memArg) const {
12197 assert(Subtarget->hasSSE42() &&
12198 "Target must have SSE4.2 or AVX features enabled");
12200 DebugLoc dl = MI->getDebugLoc();
12201 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12203 if (!Subtarget->hasAVX()) {
12205 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12207 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12210 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12212 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12215 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12216 for (unsigned i = 0; i < numArgs; ++i) {
12217 MachineOperand &Op = MI->getOperand(i+1);
12218 if (!(Op.isReg() && Op.isImplicit()))
12219 MIB.addOperand(Op);
12221 BuildMI(*BB, MI, dl,
12222 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12223 .addReg(X86::XMM0);
12225 MI->eraseFromParent();
12229 MachineBasicBlock *
12230 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12231 DebugLoc dl = MI->getDebugLoc();
12232 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12234 // Address into RAX/EAX, other two args into ECX, EDX.
12235 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12236 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12237 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12238 for (int i = 0; i < X86::AddrNumOperands; ++i)
12239 MIB.addOperand(MI->getOperand(i));
12241 unsigned ValOps = X86::AddrNumOperands;
12242 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12243 .addReg(MI->getOperand(ValOps).getReg());
12244 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12245 .addReg(MI->getOperand(ValOps+1).getReg());
12247 // The instruction doesn't actually take any operands though.
12248 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12250 MI->eraseFromParent(); // The pseudo is gone now.
12254 MachineBasicBlock *
12255 X86TargetLowering::EmitVAARG64WithCustomInserter(
12257 MachineBasicBlock *MBB) const {
12258 // Emit va_arg instruction on X86-64.
12260 // Operands to this pseudo-instruction:
12261 // 0 ) Output : destination address (reg)
12262 // 1-5) Input : va_list address (addr, i64mem)
12263 // 6 ) ArgSize : Size (in bytes) of vararg type
12264 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12265 // 8 ) Align : Alignment of type
12266 // 9 ) EFLAGS (implicit-def)
12268 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12269 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12271 unsigned DestReg = MI->getOperand(0).getReg();
12272 MachineOperand &Base = MI->getOperand(1);
12273 MachineOperand &Scale = MI->getOperand(2);
12274 MachineOperand &Index = MI->getOperand(3);
12275 MachineOperand &Disp = MI->getOperand(4);
12276 MachineOperand &Segment = MI->getOperand(5);
12277 unsigned ArgSize = MI->getOperand(6).getImm();
12278 unsigned ArgMode = MI->getOperand(7).getImm();
12279 unsigned Align = MI->getOperand(8).getImm();
12281 // Memory Reference
12282 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12283 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12284 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12286 // Machine Information
12287 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12288 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12289 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12290 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12291 DebugLoc DL = MI->getDebugLoc();
12293 // struct va_list {
12296 // i64 overflow_area (address)
12297 // i64 reg_save_area (address)
12299 // sizeof(va_list) = 24
12300 // alignment(va_list) = 8
12302 unsigned TotalNumIntRegs = 6;
12303 unsigned TotalNumXMMRegs = 8;
12304 bool UseGPOffset = (ArgMode == 1);
12305 bool UseFPOffset = (ArgMode == 2);
12306 unsigned MaxOffset = TotalNumIntRegs * 8 +
12307 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12309 /* Align ArgSize to a multiple of 8 */
12310 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12311 bool NeedsAlign = (Align > 8);
12313 MachineBasicBlock *thisMBB = MBB;
12314 MachineBasicBlock *overflowMBB;
12315 MachineBasicBlock *offsetMBB;
12316 MachineBasicBlock *endMBB;
12318 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12319 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12320 unsigned OffsetReg = 0;
12322 if (!UseGPOffset && !UseFPOffset) {
12323 // If we only pull from the overflow region, we don't create a branch.
12324 // We don't need to alter control flow.
12325 OffsetDestReg = 0; // unused
12326 OverflowDestReg = DestReg;
12329 overflowMBB = thisMBB;
12332 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12333 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12334 // If not, pull from overflow_area. (branch to overflowMBB)
12339 // offsetMBB overflowMBB
12344 // Registers for the PHI in endMBB
12345 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12346 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12348 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12349 MachineFunction *MF = MBB->getParent();
12350 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12351 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12352 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12354 MachineFunction::iterator MBBIter = MBB;
12357 // Insert the new basic blocks
12358 MF->insert(MBBIter, offsetMBB);
12359 MF->insert(MBBIter, overflowMBB);
12360 MF->insert(MBBIter, endMBB);
12362 // Transfer the remainder of MBB and its successor edges to endMBB.
12363 endMBB->splice(endMBB->begin(), thisMBB,
12364 llvm::next(MachineBasicBlock::iterator(MI)),
12366 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12368 // Make offsetMBB and overflowMBB successors of thisMBB
12369 thisMBB->addSuccessor(offsetMBB);
12370 thisMBB->addSuccessor(overflowMBB);
12372 // endMBB is a successor of both offsetMBB and overflowMBB
12373 offsetMBB->addSuccessor(endMBB);
12374 overflowMBB->addSuccessor(endMBB);
12376 // Load the offset value into a register
12377 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12378 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12382 .addDisp(Disp, UseFPOffset ? 4 : 0)
12383 .addOperand(Segment)
12384 .setMemRefs(MMOBegin, MMOEnd);
12386 // Check if there is enough room left to pull this argument.
12387 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12389 .addImm(MaxOffset + 8 - ArgSizeA8);
12391 // Branch to "overflowMBB" if offset >= max
12392 // Fall through to "offsetMBB" otherwise
12393 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12394 .addMBB(overflowMBB);
12397 // In offsetMBB, emit code to use the reg_save_area.
12399 assert(OffsetReg != 0);
12401 // Read the reg_save_area address.
12402 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12403 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12408 .addOperand(Segment)
12409 .setMemRefs(MMOBegin, MMOEnd);
12411 // Zero-extend the offset
12412 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12413 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12416 .addImm(X86::sub_32bit);
12418 // Add the offset to the reg_save_area to get the final address.
12419 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12420 .addReg(OffsetReg64)
12421 .addReg(RegSaveReg);
12423 // Compute the offset for the next argument
12424 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12425 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12427 .addImm(UseFPOffset ? 16 : 8);
12429 // Store it back into the va_list.
12430 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12434 .addDisp(Disp, UseFPOffset ? 4 : 0)
12435 .addOperand(Segment)
12436 .addReg(NextOffsetReg)
12437 .setMemRefs(MMOBegin, MMOEnd);
12440 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12445 // Emit code to use overflow area
12448 // Load the overflow_area address into a register.
12449 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12450 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12455 .addOperand(Segment)
12456 .setMemRefs(MMOBegin, MMOEnd);
12458 // If we need to align it, do so. Otherwise, just copy the address
12459 // to OverflowDestReg.
12461 // Align the overflow address
12462 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12463 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12465 // aligned_addr = (addr + (align-1)) & ~(align-1)
12466 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12467 .addReg(OverflowAddrReg)
12470 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12472 .addImm(~(uint64_t)(Align-1));
12474 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12475 .addReg(OverflowAddrReg);
12478 // Compute the next overflow address after this argument.
12479 // (the overflow address should be kept 8-byte aligned)
12480 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12481 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12482 .addReg(OverflowDestReg)
12483 .addImm(ArgSizeA8);
12485 // Store the new overflow address.
12486 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12491 .addOperand(Segment)
12492 .addReg(NextAddrReg)
12493 .setMemRefs(MMOBegin, MMOEnd);
12495 // If we branched, emit the PHI to the front of endMBB.
12497 BuildMI(*endMBB, endMBB->begin(), DL,
12498 TII->get(X86::PHI), DestReg)
12499 .addReg(OffsetDestReg).addMBB(offsetMBB)
12500 .addReg(OverflowDestReg).addMBB(overflowMBB);
12503 // Erase the pseudo instruction
12504 MI->eraseFromParent();
12509 MachineBasicBlock *
12510 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12512 MachineBasicBlock *MBB) const {
12513 // Emit code to save XMM registers to the stack. The ABI says that the
12514 // number of registers to save is given in %al, so it's theoretically
12515 // possible to do an indirect jump trick to avoid saving all of them,
12516 // however this code takes a simpler approach and just executes all
12517 // of the stores if %al is non-zero. It's less code, and it's probably
12518 // easier on the hardware branch predictor, and stores aren't all that
12519 // expensive anyway.
12521 // Create the new basic blocks. One block contains all the XMM stores,
12522 // and one block is the final destination regardless of whether any
12523 // stores were performed.
12524 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12525 MachineFunction *F = MBB->getParent();
12526 MachineFunction::iterator MBBIter = MBB;
12528 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12529 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12530 F->insert(MBBIter, XMMSaveMBB);
12531 F->insert(MBBIter, EndMBB);
12533 // Transfer the remainder of MBB and its successor edges to EndMBB.
12534 EndMBB->splice(EndMBB->begin(), MBB,
12535 llvm::next(MachineBasicBlock::iterator(MI)),
12537 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12539 // The original block will now fall through to the XMM save block.
12540 MBB->addSuccessor(XMMSaveMBB);
12541 // The XMMSaveMBB will fall through to the end block.
12542 XMMSaveMBB->addSuccessor(EndMBB);
12544 // Now add the instructions.
12545 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12546 DebugLoc DL = MI->getDebugLoc();
12548 unsigned CountReg = MI->getOperand(0).getReg();
12549 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12550 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12552 if (!Subtarget->isTargetWin64()) {
12553 // If %al is 0, branch around the XMM save block.
12554 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12555 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12556 MBB->addSuccessor(EndMBB);
12559 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12560 // In the XMM save block, save all the XMM argument registers.
12561 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12562 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12563 MachineMemOperand *MMO =
12564 F->getMachineMemOperand(
12565 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12566 MachineMemOperand::MOStore,
12567 /*Size=*/16, /*Align=*/16);
12568 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12569 .addFrameIndex(RegSaveFrameIndex)
12570 .addImm(/*Scale=*/1)
12571 .addReg(/*IndexReg=*/0)
12572 .addImm(/*Disp=*/Offset)
12573 .addReg(/*Segment=*/0)
12574 .addReg(MI->getOperand(i).getReg())
12575 .addMemOperand(MMO);
12578 MI->eraseFromParent(); // The pseudo instruction is gone now.
12583 // The EFLAGS operand of SelectItr might be missing a kill marker
12584 // because there were multiple uses of EFLAGS, and ISel didn't know
12585 // which to mark. Figure out whether SelectItr should have had a
12586 // kill marker, and set it if it should. Returns the correct kill
12588 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12589 MachineBasicBlock* BB,
12590 const TargetRegisterInfo* TRI) {
12591 // Scan forward through BB for a use/def of EFLAGS.
12592 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12593 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12594 const MachineInstr& mi = *miI;
12595 if (mi.readsRegister(X86::EFLAGS))
12597 if (mi.definesRegister(X86::EFLAGS))
12598 break; // Should have kill-flag - update below.
12601 // If we hit the end of the block, check whether EFLAGS is live into a
12603 if (miI == BB->end()) {
12604 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12605 sEnd = BB->succ_end();
12606 sItr != sEnd; ++sItr) {
12607 MachineBasicBlock* succ = *sItr;
12608 if (succ->isLiveIn(X86::EFLAGS))
12613 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12614 // out. SelectMI should have a kill flag on EFLAGS.
12615 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12619 MachineBasicBlock *
12620 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12621 MachineBasicBlock *BB) const {
12622 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12623 DebugLoc DL = MI->getDebugLoc();
12625 // To "insert" a SELECT_CC instruction, we actually have to insert the
12626 // diamond control-flow pattern. The incoming instruction knows the
12627 // destination vreg to set, the condition code register to branch on, the
12628 // true/false values to select between, and a branch opcode to use.
12629 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12630 MachineFunction::iterator It = BB;
12636 // cmpTY ccX, r1, r2
12638 // fallthrough --> copy0MBB
12639 MachineBasicBlock *thisMBB = BB;
12640 MachineFunction *F = BB->getParent();
12641 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12642 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12643 F->insert(It, copy0MBB);
12644 F->insert(It, sinkMBB);
12646 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12647 // live into the sink and copy blocks.
12648 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12649 if (!MI->killsRegister(X86::EFLAGS) &&
12650 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12651 copy0MBB->addLiveIn(X86::EFLAGS);
12652 sinkMBB->addLiveIn(X86::EFLAGS);
12655 // Transfer the remainder of BB and its successor edges to sinkMBB.
12656 sinkMBB->splice(sinkMBB->begin(), BB,
12657 llvm::next(MachineBasicBlock::iterator(MI)),
12659 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12661 // Add the true and fallthrough blocks as its successors.
12662 BB->addSuccessor(copy0MBB);
12663 BB->addSuccessor(sinkMBB);
12665 // Create the conditional branch instruction.
12667 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12668 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12671 // %FalseValue = ...
12672 // # fallthrough to sinkMBB
12673 copy0MBB->addSuccessor(sinkMBB);
12676 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12678 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12679 TII->get(X86::PHI), MI->getOperand(0).getReg())
12680 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12681 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12683 MI->eraseFromParent(); // The pseudo instruction is gone now.
12687 MachineBasicBlock *
12688 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12689 bool Is64Bit) const {
12690 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12691 DebugLoc DL = MI->getDebugLoc();
12692 MachineFunction *MF = BB->getParent();
12693 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12695 assert(getTargetMachine().Options.EnableSegmentedStacks);
12697 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12698 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12701 // ... [Till the alloca]
12702 // If stacklet is not large enough, jump to mallocMBB
12705 // Allocate by subtracting from RSP
12706 // Jump to continueMBB
12709 // Allocate by call to runtime
12713 // [rest of original BB]
12716 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12717 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12718 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12720 MachineRegisterInfo &MRI = MF->getRegInfo();
12721 const TargetRegisterClass *AddrRegClass =
12722 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12724 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12725 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12726 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12727 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12728 sizeVReg = MI->getOperand(1).getReg(),
12729 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12731 MachineFunction::iterator MBBIter = BB;
12734 MF->insert(MBBIter, bumpMBB);
12735 MF->insert(MBBIter, mallocMBB);
12736 MF->insert(MBBIter, continueMBB);
12738 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12739 (MachineBasicBlock::iterator(MI)), BB->end());
12740 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12742 // Add code to the main basic block to check if the stack limit has been hit,
12743 // and if so, jump to mallocMBB otherwise to bumpMBB.
12744 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12745 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12746 .addReg(tmpSPVReg).addReg(sizeVReg);
12747 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12748 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12749 .addReg(SPLimitVReg);
12750 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12752 // bumpMBB simply decreases the stack pointer, since we know the current
12753 // stacklet has enough space.
12754 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12755 .addReg(SPLimitVReg);
12756 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12757 .addReg(SPLimitVReg);
12758 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12760 // Calls into a routine in libgcc to allocate more space from the heap.
12761 const uint32_t *RegMask =
12762 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12764 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12766 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12767 .addExternalSymbol("__morestack_allocate_stack_space")
12768 .addRegMask(RegMask)
12769 .addReg(X86::RDI, RegState::Implicit)
12770 .addReg(X86::RAX, RegState::ImplicitDefine);
12772 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12774 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12775 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12776 .addExternalSymbol("__morestack_allocate_stack_space")
12777 .addRegMask(RegMask)
12778 .addReg(X86::EAX, RegState::ImplicitDefine);
12782 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12785 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12786 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12787 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12789 // Set up the CFG correctly.
12790 BB->addSuccessor(bumpMBB);
12791 BB->addSuccessor(mallocMBB);
12792 mallocMBB->addSuccessor(continueMBB);
12793 bumpMBB->addSuccessor(continueMBB);
12795 // Take care of the PHI nodes.
12796 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12797 MI->getOperand(0).getReg())
12798 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12799 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12801 // Delete the original pseudo instruction.
12802 MI->eraseFromParent();
12805 return continueMBB;
12808 MachineBasicBlock *
12809 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12810 MachineBasicBlock *BB) const {
12811 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12812 DebugLoc DL = MI->getDebugLoc();
12814 assert(!Subtarget->isTargetEnvMacho());
12816 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12817 // non-trivial part is impdef of ESP.
12819 if (Subtarget->isTargetWin64()) {
12820 if (Subtarget->isTargetCygMing()) {
12821 // ___chkstk(Mingw64):
12822 // Clobbers R10, R11, RAX and EFLAGS.
12824 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12825 .addExternalSymbol("___chkstk")
12826 .addReg(X86::RAX, RegState::Implicit)
12827 .addReg(X86::RSP, RegState::Implicit)
12828 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12829 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12830 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12832 // __chkstk(MSVCRT): does not update stack pointer.
12833 // Clobbers R10, R11 and EFLAGS.
12834 // FIXME: RAX(allocated size) might be reused and not killed.
12835 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12836 .addExternalSymbol("__chkstk")
12837 .addReg(X86::RAX, RegState::Implicit)
12838 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12839 // RAX has the offset to subtracted from RSP.
12840 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12845 const char *StackProbeSymbol =
12846 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12848 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12849 .addExternalSymbol(StackProbeSymbol)
12850 .addReg(X86::EAX, RegState::Implicit)
12851 .addReg(X86::ESP, RegState::Implicit)
12852 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12853 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12854 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12857 MI->eraseFromParent(); // The pseudo instruction is gone now.
12861 MachineBasicBlock *
12862 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12863 MachineBasicBlock *BB) const {
12864 // This is pretty easy. We're taking the value that we received from
12865 // our load from the relocation, sticking it in either RDI (x86-64)
12866 // or EAX and doing an indirect call. The return value will then
12867 // be in the normal return register.
12868 const X86InstrInfo *TII
12869 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12870 DebugLoc DL = MI->getDebugLoc();
12871 MachineFunction *F = BB->getParent();
12873 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12874 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12876 // Get a register mask for the lowered call.
12877 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12878 // proper register mask.
12879 const uint32_t *RegMask =
12880 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12881 if (Subtarget->is64Bit()) {
12882 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12883 TII->get(X86::MOV64rm), X86::RDI)
12885 .addImm(0).addReg(0)
12886 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12887 MI->getOperand(3).getTargetFlags())
12889 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12890 addDirectMem(MIB, X86::RDI);
12891 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12892 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12893 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12894 TII->get(X86::MOV32rm), X86::EAX)
12896 .addImm(0).addReg(0)
12897 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12898 MI->getOperand(3).getTargetFlags())
12900 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12901 addDirectMem(MIB, X86::EAX);
12902 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12904 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12905 TII->get(X86::MOV32rm), X86::EAX)
12906 .addReg(TII->getGlobalBaseReg(F))
12907 .addImm(0).addReg(0)
12908 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12909 MI->getOperand(3).getTargetFlags())
12911 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12912 addDirectMem(MIB, X86::EAX);
12913 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12916 MI->eraseFromParent(); // The pseudo instruction is gone now.
12920 MachineBasicBlock *
12921 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12922 MachineBasicBlock *BB) const {
12923 switch (MI->getOpcode()) {
12924 default: llvm_unreachable("Unexpected instr type to insert");
12925 case X86::TAILJMPd64:
12926 case X86::TAILJMPr64:
12927 case X86::TAILJMPm64:
12928 llvm_unreachable("TAILJMP64 would not be touched here.");
12929 case X86::TCRETURNdi64:
12930 case X86::TCRETURNri64:
12931 case X86::TCRETURNmi64:
12933 case X86::WIN_ALLOCA:
12934 return EmitLoweredWinAlloca(MI, BB);
12935 case X86::SEG_ALLOCA_32:
12936 return EmitLoweredSegAlloca(MI, BB, false);
12937 case X86::SEG_ALLOCA_64:
12938 return EmitLoweredSegAlloca(MI, BB, true);
12939 case X86::TLSCall_32:
12940 case X86::TLSCall_64:
12941 return EmitLoweredTLSCall(MI, BB);
12942 case X86::CMOV_GR8:
12943 case X86::CMOV_FR32:
12944 case X86::CMOV_FR64:
12945 case X86::CMOV_V4F32:
12946 case X86::CMOV_V2F64:
12947 case X86::CMOV_V2I64:
12948 case X86::CMOV_V8F32:
12949 case X86::CMOV_V4F64:
12950 case X86::CMOV_V4I64:
12951 case X86::CMOV_GR16:
12952 case X86::CMOV_GR32:
12953 case X86::CMOV_RFP32:
12954 case X86::CMOV_RFP64:
12955 case X86::CMOV_RFP80:
12956 return EmitLoweredSelect(MI, BB);
12958 case X86::FP32_TO_INT16_IN_MEM:
12959 case X86::FP32_TO_INT32_IN_MEM:
12960 case X86::FP32_TO_INT64_IN_MEM:
12961 case X86::FP64_TO_INT16_IN_MEM:
12962 case X86::FP64_TO_INT32_IN_MEM:
12963 case X86::FP64_TO_INT64_IN_MEM:
12964 case X86::FP80_TO_INT16_IN_MEM:
12965 case X86::FP80_TO_INT32_IN_MEM:
12966 case X86::FP80_TO_INT64_IN_MEM: {
12967 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12968 DebugLoc DL = MI->getDebugLoc();
12970 // Change the floating point control register to use "round towards zero"
12971 // mode when truncating to an integer value.
12972 MachineFunction *F = BB->getParent();
12973 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12974 addFrameReference(BuildMI(*BB, MI, DL,
12975 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12977 // Load the old value of the high byte of the control word...
12979 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12980 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12983 // Set the high part to be round to zero...
12984 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12987 // Reload the modified control word now...
12988 addFrameReference(BuildMI(*BB, MI, DL,
12989 TII->get(X86::FLDCW16m)), CWFrameIdx);
12991 // Restore the memory image of control word to original value
12992 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12995 // Get the X86 opcode to use.
12997 switch (MI->getOpcode()) {
12998 default: llvm_unreachable("illegal opcode!");
12999 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13000 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13001 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13002 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13003 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13004 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13005 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13006 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13007 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13011 MachineOperand &Op = MI->getOperand(0);
13013 AM.BaseType = X86AddressMode::RegBase;
13014 AM.Base.Reg = Op.getReg();
13016 AM.BaseType = X86AddressMode::FrameIndexBase;
13017 AM.Base.FrameIndex = Op.getIndex();
13019 Op = MI->getOperand(1);
13021 AM.Scale = Op.getImm();
13022 Op = MI->getOperand(2);
13024 AM.IndexReg = Op.getImm();
13025 Op = MI->getOperand(3);
13026 if (Op.isGlobal()) {
13027 AM.GV = Op.getGlobal();
13029 AM.Disp = Op.getImm();
13031 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13032 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13034 // Reload the original control word now.
13035 addFrameReference(BuildMI(*BB, MI, DL,
13036 TII->get(X86::FLDCW16m)), CWFrameIdx);
13038 MI->eraseFromParent(); // The pseudo instruction is gone now.
13041 // String/text processing lowering.
13042 case X86::PCMPISTRM128REG:
13043 case X86::VPCMPISTRM128REG:
13044 case X86::PCMPISTRM128MEM:
13045 case X86::VPCMPISTRM128MEM:
13046 case X86::PCMPESTRM128REG:
13047 case X86::VPCMPESTRM128REG:
13048 case X86::PCMPESTRM128MEM:
13049 case X86::VPCMPESTRM128MEM: {
13052 switch (MI->getOpcode()) {
13053 default: llvm_unreachable("illegal opcode!");
13054 case X86::PCMPISTRM128REG:
13055 case X86::VPCMPISTRM128REG:
13056 NumArgs = 3; MemArg = false; break;
13057 case X86::PCMPISTRM128MEM:
13058 case X86::VPCMPISTRM128MEM:
13059 NumArgs = 3; MemArg = true; break;
13060 case X86::PCMPESTRM128REG:
13061 case X86::VPCMPESTRM128REG:
13062 NumArgs = 5; MemArg = false; break;
13063 case X86::PCMPESTRM128MEM:
13064 case X86::VPCMPESTRM128MEM:
13065 NumArgs = 5; MemArg = true; break;
13067 return EmitPCMP(MI, BB, NumArgs, MemArg);
13070 // Thread synchronization.
13072 return EmitMonitor(MI, BB);
13074 // Atomic Lowering.
13075 case X86::ATOMMIN32:
13076 case X86::ATOMMAX32:
13077 case X86::ATOMUMIN32:
13078 case X86::ATOMUMAX32:
13079 case X86::ATOMMIN16:
13080 case X86::ATOMMAX16:
13081 case X86::ATOMUMIN16:
13082 case X86::ATOMUMAX16:
13083 case X86::ATOMMIN64:
13084 case X86::ATOMMAX64:
13085 case X86::ATOMUMIN64:
13086 case X86::ATOMUMAX64: {
13088 switch (MI->getOpcode()) {
13089 default: llvm_unreachable("illegal opcode!");
13090 case X86::ATOMMIN32: Opc = X86::CMOVL32rr; break;
13091 case X86::ATOMMAX32: Opc = X86::CMOVG32rr; break;
13092 case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13093 case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13094 case X86::ATOMMIN16: Opc = X86::CMOVL16rr; break;
13095 case X86::ATOMMAX16: Opc = X86::CMOVG16rr; break;
13096 case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13097 case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13098 case X86::ATOMMIN64: Opc = X86::CMOVL64rr; break;
13099 case X86::ATOMMAX64: Opc = X86::CMOVG64rr; break;
13100 case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13101 case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13102 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13104 return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13107 case X86::ATOMAND32:
13108 case X86::ATOMOR32:
13109 case X86::ATOMXOR32:
13110 case X86::ATOMNAND32: {
13111 bool Invert = false;
13112 unsigned RegOpc, ImmOpc;
13113 switch (MI->getOpcode()) {
13114 default: llvm_unreachable("illegal opcode!");
13115 case X86::ATOMAND32:
13116 RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13117 case X86::ATOMOR32:
13118 RegOpc = X86::OR32rr; ImmOpc = X86::OR32ri; break;
13119 case X86::ATOMXOR32:
13120 RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13121 case X86::ATOMNAND32:
13122 RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13124 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13125 X86::MOV32rm, X86::LCMPXCHG32,
13126 X86::NOT32r, X86::EAX,
13127 &X86::GR32RegClass, Invert);
13130 case X86::ATOMAND16:
13131 case X86::ATOMOR16:
13132 case X86::ATOMXOR16:
13133 case X86::ATOMNAND16: {
13134 bool Invert = false;
13135 unsigned RegOpc, ImmOpc;
13136 switch (MI->getOpcode()) {
13137 default: llvm_unreachable("illegal opcode!");
13138 case X86::ATOMAND16:
13139 RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13140 case X86::ATOMOR16:
13141 RegOpc = X86::OR16rr; ImmOpc = X86::OR16ri; break;
13142 case X86::ATOMXOR16:
13143 RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13144 case X86::ATOMNAND16:
13145 RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13147 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13148 X86::MOV16rm, X86::LCMPXCHG16,
13149 X86::NOT16r, X86::AX,
13150 &X86::GR16RegClass, Invert);
13153 case X86::ATOMAND8:
13155 case X86::ATOMXOR8:
13156 case X86::ATOMNAND8: {
13157 bool Invert = false;
13158 unsigned RegOpc, ImmOpc;
13159 switch (MI->getOpcode()) {
13160 default: llvm_unreachable("illegal opcode!");
13161 case X86::ATOMAND8:
13162 RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13164 RegOpc = X86::OR8rr; ImmOpc = X86::OR8ri; break;
13165 case X86::ATOMXOR8:
13166 RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13167 case X86::ATOMNAND8:
13168 RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13170 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13171 X86::MOV8rm, X86::LCMPXCHG8,
13172 X86::NOT8r, X86::AL,
13173 &X86::GR8RegClass, Invert);
13176 // This group is for 64-bit host.
13177 case X86::ATOMAND64:
13178 case X86::ATOMOR64:
13179 case X86::ATOMXOR64:
13180 case X86::ATOMNAND64: {
13181 bool Invert = false;
13182 unsigned RegOpc, ImmOpc;
13183 switch (MI->getOpcode()) {
13184 default: llvm_unreachable("illegal opcode!");
13185 case X86::ATOMAND64:
13186 RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13187 case X86::ATOMOR64:
13188 RegOpc = X86::OR64rr; ImmOpc = X86::OR64ri32; break;
13189 case X86::ATOMXOR64:
13190 RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13191 case X86::ATOMNAND64:
13192 RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13194 return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13195 X86::MOV64rm, X86::LCMPXCHG64,
13196 X86::NOT64r, X86::RAX,
13197 &X86::GR64RegClass, Invert);
13200 // This group does 64-bit operations on a 32-bit host.
13201 case X86::ATOMAND6432:
13202 case X86::ATOMOR6432:
13203 case X86::ATOMXOR6432:
13204 case X86::ATOMNAND6432:
13205 case X86::ATOMADD6432:
13206 case X86::ATOMSUB6432:
13207 case X86::ATOMSWAP6432: {
13208 bool Invert = false;
13209 unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13210 switch (MI->getOpcode()) {
13211 default: llvm_unreachable("illegal opcode!");
13212 case X86::ATOMAND6432:
13213 RegOpcL = RegOpcH = X86::AND32rr;
13214 ImmOpcL = ImmOpcH = X86::AND32ri;
13216 case X86::ATOMOR6432:
13217 RegOpcL = RegOpcH = X86::OR32rr;
13218 ImmOpcL = ImmOpcH = X86::OR32ri;
13220 case X86::ATOMXOR6432:
13221 RegOpcL = RegOpcH = X86::XOR32rr;
13222 ImmOpcL = ImmOpcH = X86::XOR32ri;
13224 case X86::ATOMNAND6432:
13225 RegOpcL = RegOpcH = X86::AND32rr;
13226 ImmOpcL = ImmOpcH = X86::AND32ri;
13229 case X86::ATOMADD6432:
13230 RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13231 ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13233 case X86::ATOMSUB6432:
13234 RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13235 ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13237 case X86::ATOMSWAP6432:
13238 RegOpcL = RegOpcH = X86::MOV32rr;
13239 ImmOpcL = ImmOpcH = X86::MOV32ri;
13242 return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13243 ImmOpcL, ImmOpcH, Invert);
13246 case X86::VASTART_SAVE_XMM_REGS:
13247 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13249 case X86::VAARG_64:
13250 return EmitVAARG64WithCustomInserter(MI, BB);
13254 //===----------------------------------------------------------------------===//
13255 // X86 Optimization Hooks
13256 //===----------------------------------------------------------------------===//
13258 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13261 const SelectionDAG &DAG,
13262 unsigned Depth) const {
13263 unsigned BitWidth = KnownZero.getBitWidth();
13264 unsigned Opc = Op.getOpcode();
13265 assert((Opc >= ISD::BUILTIN_OP_END ||
13266 Opc == ISD::INTRINSIC_WO_CHAIN ||
13267 Opc == ISD::INTRINSIC_W_CHAIN ||
13268 Opc == ISD::INTRINSIC_VOID) &&
13269 "Should use MaskedValueIsZero if you don't know whether Op"
13270 " is a target node!");
13272 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13286 // These nodes' second result is a boolean.
13287 if (Op.getResNo() == 0)
13290 case X86ISD::SETCC:
13291 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13293 case ISD::INTRINSIC_WO_CHAIN: {
13294 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13295 unsigned NumLoBits = 0;
13298 case Intrinsic::x86_sse_movmsk_ps:
13299 case Intrinsic::x86_avx_movmsk_ps_256:
13300 case Intrinsic::x86_sse2_movmsk_pd:
13301 case Intrinsic::x86_avx_movmsk_pd_256:
13302 case Intrinsic::x86_mmx_pmovmskb:
13303 case Intrinsic::x86_sse2_pmovmskb_128:
13304 case Intrinsic::x86_avx2_pmovmskb: {
13305 // High bits of movmskp{s|d}, pmovmskb are known zero.
13307 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13308 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13309 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13310 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13311 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13312 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13313 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13314 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13316 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13325 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13326 unsigned Depth) const {
13327 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13328 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13329 return Op.getValueType().getScalarType().getSizeInBits();
13335 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13336 /// node is a GlobalAddress + offset.
13337 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13338 const GlobalValue* &GA,
13339 int64_t &Offset) const {
13340 if (N->getOpcode() == X86ISD::Wrapper) {
13341 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13342 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13343 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13347 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13350 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13351 /// same as extracting the high 128-bit part of 256-bit vector and then
13352 /// inserting the result into the low part of a new 256-bit vector
13353 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13354 EVT VT = SVOp->getValueType(0);
13355 unsigned NumElems = VT.getVectorNumElements();
13357 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13358 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13359 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13360 SVOp->getMaskElt(j) >= 0)
13366 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13367 /// same as extracting the low 128-bit part of 256-bit vector and then
13368 /// inserting the result into the high part of a new 256-bit vector
13369 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13370 EVT VT = SVOp->getValueType(0);
13371 unsigned NumElems = VT.getVectorNumElements();
13373 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13374 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13375 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13376 SVOp->getMaskElt(j) >= 0)
13382 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13383 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13384 TargetLowering::DAGCombinerInfo &DCI,
13385 const X86Subtarget* Subtarget) {
13386 DebugLoc dl = N->getDebugLoc();
13387 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13388 SDValue V1 = SVOp->getOperand(0);
13389 SDValue V2 = SVOp->getOperand(1);
13390 EVT VT = SVOp->getValueType(0);
13391 unsigned NumElems = VT.getVectorNumElements();
13393 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13394 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13398 // V UNDEF BUILD_VECTOR UNDEF
13400 // CONCAT_VECTOR CONCAT_VECTOR
13403 // RESULT: V + zero extended
13405 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13406 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13407 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13410 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13413 // To match the shuffle mask, the first half of the mask should
13414 // be exactly the first vector, and all the rest a splat with the
13415 // first element of the second one.
13416 for (unsigned i = 0; i != NumElems/2; ++i)
13417 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13418 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13421 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13422 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13423 if (Ld->hasNUsesOfValue(1, 0)) {
13424 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13425 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13427 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13429 Ld->getPointerInfo(),
13430 Ld->getAlignment(),
13431 false/*isVolatile*/, true/*ReadMem*/,
13432 false/*WriteMem*/);
13433 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13437 // Emit a zeroed vector and insert the desired subvector on its
13439 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13440 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13441 return DCI.CombineTo(N, InsV);
13444 //===--------------------------------------------------------------------===//
13445 // Combine some shuffles into subvector extracts and inserts:
13448 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13449 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13450 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13451 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13452 return DCI.CombineTo(N, InsV);
13455 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13456 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13457 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13458 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13459 return DCI.CombineTo(N, InsV);
13465 /// PerformShuffleCombine - Performs several different shuffle combines.
13466 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13467 TargetLowering::DAGCombinerInfo &DCI,
13468 const X86Subtarget *Subtarget) {
13469 DebugLoc dl = N->getDebugLoc();
13470 EVT VT = N->getValueType(0);
13472 // Don't create instructions with illegal types after legalize types has run.
13473 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13474 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13477 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13478 if (Subtarget->hasAVX() && VT.is256BitVector() &&
13479 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13480 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13482 // Only handle 128 wide vector from here on.
13483 if (!VT.is128BitVector())
13486 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13487 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13488 // consecutive, non-overlapping, and in the right order.
13489 SmallVector<SDValue, 16> Elts;
13490 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13491 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13493 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13497 /// DCI, PerformTruncateCombine - Converts truncate operation to
13498 /// a sequence of vector shuffle operations.
13499 /// It is possible when we truncate 256-bit vector to 128-bit vector
13501 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13502 DAGCombinerInfo &DCI) const {
13503 if (!DCI.isBeforeLegalizeOps())
13506 if (!Subtarget->hasAVX())
13509 EVT VT = N->getValueType(0);
13510 SDValue Op = N->getOperand(0);
13511 EVT OpVT = Op.getValueType();
13512 DebugLoc dl = N->getDebugLoc();
13514 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13516 if (Subtarget->hasAVX2()) {
13517 // AVX2: v4i64 -> v4i32
13520 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13522 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13523 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13526 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13527 DAG.getIntPtrConstant(0));
13530 // AVX: v4i64 -> v4i32
13531 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13532 DAG.getIntPtrConstant(0));
13534 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13535 DAG.getIntPtrConstant(2));
13537 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13538 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13541 static const int ShufMask1[] = {0, 2, 0, 0};
13543 SDValue Undef = DAG.getUNDEF(VT);
13544 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13545 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13548 static const int ShufMask2[] = {0, 1, 4, 5};
13550 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13553 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13555 if (Subtarget->hasAVX2()) {
13556 // AVX2: v8i32 -> v8i16
13558 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13561 SmallVector<SDValue,32> pshufbMask;
13562 for (unsigned i = 0; i < 2; ++i) {
13563 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13564 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13565 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13566 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13567 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13568 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13569 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13570 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13571 for (unsigned j = 0; j < 8; ++j)
13572 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13574 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13575 &pshufbMask[0], 32);
13576 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13578 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13580 static const int ShufMask[] = {0, 2, -1, -1};
13581 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13584 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13585 DAG.getIntPtrConstant(0));
13587 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13590 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13591 DAG.getIntPtrConstant(0));
13593 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13594 DAG.getIntPtrConstant(4));
13596 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13597 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13600 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13601 -1, -1, -1, -1, -1, -1, -1, -1};
13603 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13604 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13605 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13607 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13608 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13611 static const int ShufMask2[] = {0, 1, 4, 5};
13613 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13614 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13620 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13621 /// specific shuffle of a load can be folded into a single element load.
13622 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13623 /// shuffles have been customed lowered so we need to handle those here.
13624 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13625 TargetLowering::DAGCombinerInfo &DCI) {
13626 if (DCI.isBeforeLegalizeOps())
13629 SDValue InVec = N->getOperand(0);
13630 SDValue EltNo = N->getOperand(1);
13632 if (!isa<ConstantSDNode>(EltNo))
13635 EVT VT = InVec.getValueType();
13637 bool HasShuffleIntoBitcast = false;
13638 if (InVec.getOpcode() == ISD::BITCAST) {
13639 // Don't duplicate a load with other uses.
13640 if (!InVec.hasOneUse())
13642 EVT BCVT = InVec.getOperand(0).getValueType();
13643 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13645 InVec = InVec.getOperand(0);
13646 HasShuffleIntoBitcast = true;
13649 if (!isTargetShuffle(InVec.getOpcode()))
13652 // Don't duplicate a load with other uses.
13653 if (!InVec.hasOneUse())
13656 SmallVector<int, 16> ShuffleMask;
13658 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13662 // Select the input vector, guarding against out of range extract vector.
13663 unsigned NumElems = VT.getVectorNumElements();
13664 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13665 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13666 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13667 : InVec.getOperand(1);
13669 // If inputs to shuffle are the same for both ops, then allow 2 uses
13670 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13672 if (LdNode.getOpcode() == ISD::BITCAST) {
13673 // Don't duplicate a load with other uses.
13674 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13677 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13678 LdNode = LdNode.getOperand(0);
13681 if (!ISD::isNormalLoad(LdNode.getNode()))
13684 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13686 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13689 if (HasShuffleIntoBitcast) {
13690 // If there's a bitcast before the shuffle, check if the load type and
13691 // alignment is valid.
13692 unsigned Align = LN0->getAlignment();
13693 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13694 unsigned NewAlign = TLI.getTargetData()->
13695 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13697 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13701 // All checks match so transform back to vector_shuffle so that DAG combiner
13702 // can finish the job
13703 DebugLoc dl = N->getDebugLoc();
13705 // Create shuffle node taking into account the case that its a unary shuffle
13706 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13707 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13708 InVec.getOperand(0), Shuffle,
13710 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13711 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13715 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13716 /// generation and convert it from being a bunch of shuffles and extracts
13717 /// to a simple store and scalar loads to extract the elements.
13718 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13719 TargetLowering::DAGCombinerInfo &DCI) {
13720 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13721 if (NewOp.getNode())
13724 SDValue InputVector = N->getOperand(0);
13726 // Only operate on vectors of 4 elements, where the alternative shuffling
13727 // gets to be more expensive.
13728 if (InputVector.getValueType() != MVT::v4i32)
13731 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13732 // single use which is a sign-extend or zero-extend, and all elements are
13734 SmallVector<SDNode *, 4> Uses;
13735 unsigned ExtractedElements = 0;
13736 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13737 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13738 if (UI.getUse().getResNo() != InputVector.getResNo())
13741 SDNode *Extract = *UI;
13742 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13745 if (Extract->getValueType(0) != MVT::i32)
13747 if (!Extract->hasOneUse())
13749 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13750 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13752 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13755 // Record which element was extracted.
13756 ExtractedElements |=
13757 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13759 Uses.push_back(Extract);
13762 // If not all the elements were used, this may not be worthwhile.
13763 if (ExtractedElements != 15)
13766 // Ok, we've now decided to do the transformation.
13767 DebugLoc dl = InputVector.getDebugLoc();
13769 // Store the value to a temporary stack slot.
13770 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13771 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13772 MachinePointerInfo(), false, false, 0);
13774 // Replace each use (extract) with a load of the appropriate element.
13775 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13776 UE = Uses.end(); UI != UE; ++UI) {
13777 SDNode *Extract = *UI;
13779 // cOMpute the element's address.
13780 SDValue Idx = Extract->getOperand(1);
13782 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13783 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13784 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13785 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13787 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13788 StackPtr, OffsetVal);
13790 // Load the scalar.
13791 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13792 ScalarAddr, MachinePointerInfo(),
13793 false, false, false, 0);
13795 // Replace the exact with the load.
13796 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13799 // The replacement was made in place; don't return anything.
13803 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13805 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13806 TargetLowering::DAGCombinerInfo &DCI,
13807 const X86Subtarget *Subtarget) {
13808 DebugLoc DL = N->getDebugLoc();
13809 SDValue Cond = N->getOperand(0);
13810 // Get the LHS/RHS of the select.
13811 SDValue LHS = N->getOperand(1);
13812 SDValue RHS = N->getOperand(2);
13813 EVT VT = LHS.getValueType();
13815 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13816 // instructions match the semantics of the common C idiom x<y?x:y but not
13817 // x<=y?x:y, because of how they handle negative zero (which can be
13818 // ignored in unsafe-math mode).
13819 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13820 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13821 (Subtarget->hasSSE2() ||
13822 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13823 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13825 unsigned Opcode = 0;
13826 // Check for x CC y ? x : y.
13827 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13828 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13832 // Converting this to a min would handle NaNs incorrectly, and swapping
13833 // the operands would cause it to handle comparisons between positive
13834 // and negative zero incorrectly.
13835 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13836 if (!DAG.getTarget().Options.UnsafeFPMath &&
13837 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13839 std::swap(LHS, RHS);
13841 Opcode = X86ISD::FMIN;
13844 // Converting this to a min would handle comparisons between positive
13845 // and negative zero incorrectly.
13846 if (!DAG.getTarget().Options.UnsafeFPMath &&
13847 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13849 Opcode = X86ISD::FMIN;
13852 // Converting this to a min would handle both negative zeros and NaNs
13853 // incorrectly, but we can swap the operands to fix both.
13854 std::swap(LHS, RHS);
13858 Opcode = X86ISD::FMIN;
13862 // Converting this to a max would handle comparisons between positive
13863 // and negative zero incorrectly.
13864 if (!DAG.getTarget().Options.UnsafeFPMath &&
13865 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13867 Opcode = X86ISD::FMAX;
13870 // Converting this to a max would handle NaNs incorrectly, and swapping
13871 // the operands would cause it to handle comparisons between positive
13872 // and negative zero incorrectly.
13873 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13874 if (!DAG.getTarget().Options.UnsafeFPMath &&
13875 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13877 std::swap(LHS, RHS);
13879 Opcode = X86ISD::FMAX;
13882 // Converting this to a max would handle both negative zeros and NaNs
13883 // incorrectly, but we can swap the operands to fix both.
13884 std::swap(LHS, RHS);
13888 Opcode = X86ISD::FMAX;
13891 // Check for x CC y ? y : x -- a min/max with reversed arms.
13892 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13893 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13897 // Converting this to a min would handle comparisons between positive
13898 // and negative zero incorrectly, and swapping the operands would
13899 // cause it to handle NaNs incorrectly.
13900 if (!DAG.getTarget().Options.UnsafeFPMath &&
13901 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13902 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13904 std::swap(LHS, RHS);
13906 Opcode = X86ISD::FMIN;
13909 // Converting this to a min would handle NaNs incorrectly.
13910 if (!DAG.getTarget().Options.UnsafeFPMath &&
13911 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13913 Opcode = X86ISD::FMIN;
13916 // Converting this to a min would handle both negative zeros and NaNs
13917 // incorrectly, but we can swap the operands to fix both.
13918 std::swap(LHS, RHS);
13922 Opcode = X86ISD::FMIN;
13926 // Converting this to a max would handle NaNs incorrectly.
13927 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13929 Opcode = X86ISD::FMAX;
13932 // Converting this to a max would handle comparisons between positive
13933 // and negative zero incorrectly, and swapping the operands would
13934 // cause it to handle NaNs incorrectly.
13935 if (!DAG.getTarget().Options.UnsafeFPMath &&
13936 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13937 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13939 std::swap(LHS, RHS);
13941 Opcode = X86ISD::FMAX;
13944 // Converting this to a max would handle both negative zeros and NaNs
13945 // incorrectly, but we can swap the operands to fix both.
13946 std::swap(LHS, RHS);
13950 Opcode = X86ISD::FMAX;
13956 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13959 // If this is a select between two integer constants, try to do some
13961 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13962 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13963 // Don't do this for crazy integer types.
13964 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13965 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13966 // so that TrueC (the true value) is larger than FalseC.
13967 bool NeedsCondInvert = false;
13969 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13970 // Efficiently invertible.
13971 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13972 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13973 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13974 NeedsCondInvert = true;
13975 std::swap(TrueC, FalseC);
13978 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13979 if (FalseC->getAPIntValue() == 0 &&
13980 TrueC->getAPIntValue().isPowerOf2()) {
13981 if (NeedsCondInvert) // Invert the condition if needed.
13982 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13983 DAG.getConstant(1, Cond.getValueType()));
13985 // Zero extend the condition if needed.
13986 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13988 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13989 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13990 DAG.getConstant(ShAmt, MVT::i8));
13993 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13994 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13995 if (NeedsCondInvert) // Invert the condition if needed.
13996 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13997 DAG.getConstant(1, Cond.getValueType()));
13999 // Zero extend the condition if needed.
14000 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14001 FalseC->getValueType(0), Cond);
14002 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14003 SDValue(FalseC, 0));
14006 // Optimize cases that will turn into an LEA instruction. This requires
14007 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14008 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14009 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14010 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14012 bool isFastMultiplier = false;
14014 switch ((unsigned char)Diff) {
14016 case 1: // result = add base, cond
14017 case 2: // result = lea base( , cond*2)
14018 case 3: // result = lea base(cond, cond*2)
14019 case 4: // result = lea base( , cond*4)
14020 case 5: // result = lea base(cond, cond*4)
14021 case 8: // result = lea base( , cond*8)
14022 case 9: // result = lea base(cond, cond*8)
14023 isFastMultiplier = true;
14028 if (isFastMultiplier) {
14029 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14030 if (NeedsCondInvert) // Invert the condition if needed.
14031 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14032 DAG.getConstant(1, Cond.getValueType()));
14034 // Zero extend the condition if needed.
14035 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14037 // Scale the condition by the difference.
14039 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14040 DAG.getConstant(Diff, Cond.getValueType()));
14042 // Add the base if non-zero.
14043 if (FalseC->getAPIntValue() != 0)
14044 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14045 SDValue(FalseC, 0));
14052 // Canonicalize max and min:
14053 // (x > y) ? x : y -> (x >= y) ? x : y
14054 // (x < y) ? x : y -> (x <= y) ? x : y
14055 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14056 // the need for an extra compare
14057 // against zero. e.g.
14058 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14060 // testl %edi, %edi
14062 // cmovgl %edi, %eax
14066 // cmovsl %eax, %edi
14067 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14068 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14069 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14070 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14075 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14076 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14077 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14078 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14083 // If we know that this node is legal then we know that it is going to be
14084 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14085 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14086 // to simplify previous instructions.
14087 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14088 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14089 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14090 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14092 // Don't optimize vector selects that map to mask-registers.
14096 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14097 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14099 APInt KnownZero, KnownOne;
14100 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14101 DCI.isBeforeLegalizeOps());
14102 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14103 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14104 DCI.CommitTargetLoweringOpt(TLO);
14110 // Check whether a boolean test is testing a boolean value generated by
14111 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14114 // Simplify the following patterns:
14115 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14116 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14117 // to (Op EFLAGS Cond)
14119 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14120 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14121 // to (Op EFLAGS !Cond)
14123 // where Op could be BRCOND or CMOV.
14125 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14126 // Quit if not CMP and SUB with its value result used.
14127 if (Cmp.getOpcode() != X86ISD::CMP &&
14128 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14131 // Quit if not used as a boolean value.
14132 if (CC != X86::COND_E && CC != X86::COND_NE)
14135 // Check CMP operands. One of them should be 0 or 1 and the other should be
14136 // an SetCC or extended from it.
14137 SDValue Op1 = Cmp.getOperand(0);
14138 SDValue Op2 = Cmp.getOperand(1);
14141 const ConstantSDNode* C = 0;
14142 bool needOppositeCond = (CC == X86::COND_E);
14144 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14146 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14148 else // Quit if all operands are not constants.
14151 if (C->getZExtValue() == 1)
14152 needOppositeCond = !needOppositeCond;
14153 else if (C->getZExtValue() != 0)
14154 // Quit if the constant is neither 0 or 1.
14157 // Skip 'zext' node.
14158 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14159 SetCC = SetCC.getOperand(0);
14161 switch (SetCC.getOpcode()) {
14162 case X86ISD::SETCC:
14163 // Set the condition code or opposite one if necessary.
14164 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14165 if (needOppositeCond)
14166 CC = X86::GetOppositeBranchCondition(CC);
14167 return SetCC.getOperand(1);
14168 case X86ISD::CMOV: {
14169 // Check whether false/true value has canonical one, i.e. 0 or 1.
14170 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14171 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14172 // Quit if true value is not a constant.
14175 // Quit if false value is not a constant.
14177 // A special case for rdrand, where 0 is set if false cond is found.
14178 SDValue Op = SetCC.getOperand(0);
14179 if (Op.getOpcode() != X86ISD::RDRAND)
14182 // Quit if false value is not the constant 0 or 1.
14183 bool FValIsFalse = true;
14184 if (FVal && FVal->getZExtValue() != 0) {
14185 if (FVal->getZExtValue() != 1)
14187 // If FVal is 1, opposite cond is needed.
14188 needOppositeCond = !needOppositeCond;
14189 FValIsFalse = false;
14191 // Quit if TVal is not the constant opposite of FVal.
14192 if (FValIsFalse && TVal->getZExtValue() != 1)
14194 if (!FValIsFalse && TVal->getZExtValue() != 0)
14196 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14197 if (needOppositeCond)
14198 CC = X86::GetOppositeBranchCondition(CC);
14199 return SetCC.getOperand(3);
14206 /// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14207 /// updated. If only flag result is used and the result is evaluated from a
14208 /// series of element extraction, try to combine it into a PTEST.
14209 static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14211 const X86Subtarget *Subtarget) {
14212 SDNode *N = Or.getNode();
14213 DebugLoc DL = N->getDebugLoc();
14215 // Only SSE4.1 and beyond supports PTEST or like.
14216 if (!Subtarget->hasSSE41())
14219 if (N->getOpcode() != X86ISD::OR)
14222 // Quit if the value result of OR is used.
14223 if (N->hasAnyUseOfValue(0))
14226 // Quit if not used as a boolean value.
14227 if (CC != X86::COND_E && CC != X86::COND_NE)
14230 SmallVector<SDValue, 8> Opnds;
14232 EVT VT = MVT::Other;
14235 // Recognize a special case where a vector is casted into wide integer to
14237 Opnds.push_back(N->getOperand(0));
14238 Opnds.push_back(N->getOperand(1));
14240 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14241 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14242 // BFS traverse all OR'd operands.
14243 if (I->getOpcode() == ISD::OR) {
14244 Opnds.push_back(I->getOperand(0));
14245 Opnds.push_back(I->getOperand(1));
14246 // Re-evaluate the number of nodes to be traversed.
14247 e += 2; // 2 more nodes (LHS and RHS) are pushed.
14251 // Quit if a non-EXTRACT_VECTOR_ELT
14252 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14255 // Quit if without a constant index.
14256 SDValue Idx = I->getOperand(1);
14257 if (!isa<ConstantSDNode>(Idx))
14260 // Check if all elements are extracted from the same vector.
14261 SDValue ExtractedFromVec = I->getOperand(0);
14262 if (VecIn.getNode() == 0) {
14263 VT = ExtractedFromVec.getValueType();
14264 // FIXME: only 128-bit vector is supported so far.
14265 if (!VT.is128BitVector())
14267 VecIn = ExtractedFromVec;
14268 } else if (VecIn != ExtractedFromVec)
14271 // Record the constant index.
14272 Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14275 assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14277 // Quit if not all elements are used.
14278 if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14281 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14284 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14285 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14286 TargetLowering::DAGCombinerInfo &DCI,
14287 const X86Subtarget *Subtarget) {
14288 DebugLoc DL = N->getDebugLoc();
14290 // If the flag operand isn't dead, don't touch this CMOV.
14291 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14294 SDValue FalseOp = N->getOperand(0);
14295 SDValue TrueOp = N->getOperand(1);
14296 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14297 SDValue Cond = N->getOperand(3);
14299 if (CC == X86::COND_E || CC == X86::COND_NE) {
14300 switch (Cond.getOpcode()) {
14304 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14305 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14306 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14312 Flags = checkBoolTestSetCCCombine(Cond, CC);
14313 if (Flags.getNode() &&
14314 // Extra check as FCMOV only supports a subset of X86 cond.
14315 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14316 SDValue Ops[] = { FalseOp, TrueOp,
14317 DAG.getConstant(CC, MVT::i8), Flags };
14318 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14319 Ops, array_lengthof(Ops));
14322 Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14323 if (Flags.getNode()) {
14324 SDValue Ops[] = { FalseOp, TrueOp,
14325 DAG.getConstant(CC, MVT::i8), Flags };
14326 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14327 Ops, array_lengthof(Ops));
14330 // If this is a select between two integer constants, try to do some
14331 // optimizations. Note that the operands are ordered the opposite of SELECT
14333 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14334 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14335 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14336 // larger than FalseC (the false value).
14337 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14338 CC = X86::GetOppositeBranchCondition(CC);
14339 std::swap(TrueC, FalseC);
14342 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14343 // This is efficient for any integer data type (including i8/i16) and
14345 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14346 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14347 DAG.getConstant(CC, MVT::i8), Cond);
14349 // Zero extend the condition if needed.
14350 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14352 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14353 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14354 DAG.getConstant(ShAmt, MVT::i8));
14355 if (N->getNumValues() == 2) // Dead flag value?
14356 return DCI.CombineTo(N, Cond, SDValue());
14360 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14361 // for any integer data type, including i8/i16.
14362 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14363 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14364 DAG.getConstant(CC, MVT::i8), Cond);
14366 // Zero extend the condition if needed.
14367 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14368 FalseC->getValueType(0), Cond);
14369 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14370 SDValue(FalseC, 0));
14372 if (N->getNumValues() == 2) // Dead flag value?
14373 return DCI.CombineTo(N, Cond, SDValue());
14377 // Optimize cases that will turn into an LEA instruction. This requires
14378 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14379 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14380 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14381 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14383 bool isFastMultiplier = false;
14385 switch ((unsigned char)Diff) {
14387 case 1: // result = add base, cond
14388 case 2: // result = lea base( , cond*2)
14389 case 3: // result = lea base(cond, cond*2)
14390 case 4: // result = lea base( , cond*4)
14391 case 5: // result = lea base(cond, cond*4)
14392 case 8: // result = lea base( , cond*8)
14393 case 9: // result = lea base(cond, cond*8)
14394 isFastMultiplier = true;
14399 if (isFastMultiplier) {
14400 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14401 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14402 DAG.getConstant(CC, MVT::i8), Cond);
14403 // Zero extend the condition if needed.
14404 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14406 // Scale the condition by the difference.
14408 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14409 DAG.getConstant(Diff, Cond.getValueType()));
14411 // Add the base if non-zero.
14412 if (FalseC->getAPIntValue() != 0)
14413 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14414 SDValue(FalseC, 0));
14415 if (N->getNumValues() == 2) // Dead flag value?
14416 return DCI.CombineTo(N, Cond, SDValue());
14426 /// PerformMulCombine - Optimize a single multiply with constant into two
14427 /// in order to implement it with two cheaper instructions, e.g.
14428 /// LEA + SHL, LEA + LEA.
14429 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14430 TargetLowering::DAGCombinerInfo &DCI) {
14431 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14434 EVT VT = N->getValueType(0);
14435 if (VT != MVT::i64)
14438 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14441 uint64_t MulAmt = C->getZExtValue();
14442 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14445 uint64_t MulAmt1 = 0;
14446 uint64_t MulAmt2 = 0;
14447 if ((MulAmt % 9) == 0) {
14449 MulAmt2 = MulAmt / 9;
14450 } else if ((MulAmt % 5) == 0) {
14452 MulAmt2 = MulAmt / 5;
14453 } else if ((MulAmt % 3) == 0) {
14455 MulAmt2 = MulAmt / 3;
14458 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14459 DebugLoc DL = N->getDebugLoc();
14461 if (isPowerOf2_64(MulAmt2) &&
14462 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14463 // If second multiplifer is pow2, issue it first. We want the multiply by
14464 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14466 std::swap(MulAmt1, MulAmt2);
14469 if (isPowerOf2_64(MulAmt1))
14470 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14471 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14473 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14474 DAG.getConstant(MulAmt1, VT));
14476 if (isPowerOf2_64(MulAmt2))
14477 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14478 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14480 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14481 DAG.getConstant(MulAmt2, VT));
14483 // Do not add new nodes to DAG combiner worklist.
14484 DCI.CombineTo(N, NewMul, false);
14489 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14490 SDValue N0 = N->getOperand(0);
14491 SDValue N1 = N->getOperand(1);
14492 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14493 EVT VT = N0.getValueType();
14495 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14496 // since the result of setcc_c is all zero's or all ones.
14497 if (VT.isInteger() && !VT.isVector() &&
14498 N1C && N0.getOpcode() == ISD::AND &&
14499 N0.getOperand(1).getOpcode() == ISD::Constant) {
14500 SDValue N00 = N0.getOperand(0);
14501 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14502 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14503 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14504 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14505 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14506 APInt ShAmt = N1C->getAPIntValue();
14507 Mask = Mask.shl(ShAmt);
14509 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14510 N00, DAG.getConstant(Mask, VT));
14515 // Hardware support for vector shifts is sparse which makes us scalarize the
14516 // vector operations in many cases. Also, on sandybridge ADD is faster than
14518 // (shl V, 1) -> add V,V
14519 if (isSplatVector(N1.getNode())) {
14520 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14521 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14522 // We shift all of the values by one. In many cases we do not have
14523 // hardware support for this operation. This is better expressed as an ADD
14525 if (N1C && (1 == N1C->getZExtValue())) {
14526 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14533 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14535 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14536 TargetLowering::DAGCombinerInfo &DCI,
14537 const X86Subtarget *Subtarget) {
14538 EVT VT = N->getValueType(0);
14539 if (N->getOpcode() == ISD::SHL) {
14540 SDValue V = PerformSHLCombine(N, DAG);
14541 if (V.getNode()) return V;
14544 // On X86 with SSE2 support, we can transform this to a vector shift if
14545 // all elements are shifted by the same amount. We can't do this in legalize
14546 // because the a constant vector is typically transformed to a constant pool
14547 // so we have no knowledge of the shift amount.
14548 if (!Subtarget->hasSSE2())
14551 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14552 (!Subtarget->hasAVX2() ||
14553 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14556 SDValue ShAmtOp = N->getOperand(1);
14557 EVT EltVT = VT.getVectorElementType();
14558 DebugLoc DL = N->getDebugLoc();
14559 SDValue BaseShAmt = SDValue();
14560 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14561 unsigned NumElts = VT.getVectorNumElements();
14563 for (; i != NumElts; ++i) {
14564 SDValue Arg = ShAmtOp.getOperand(i);
14565 if (Arg.getOpcode() == ISD::UNDEF) continue;
14569 // Handle the case where the build_vector is all undef
14570 // FIXME: Should DAG allow this?
14574 for (; i != NumElts; ++i) {
14575 SDValue Arg = ShAmtOp.getOperand(i);
14576 if (Arg.getOpcode() == ISD::UNDEF) continue;
14577 if (Arg != BaseShAmt) {
14581 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14582 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14583 SDValue InVec = ShAmtOp.getOperand(0);
14584 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14585 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14587 for (; i != NumElts; ++i) {
14588 SDValue Arg = InVec.getOperand(i);
14589 if (Arg.getOpcode() == ISD::UNDEF) continue;
14593 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14594 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14595 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14596 if (C->getZExtValue() == SplatIdx)
14597 BaseShAmt = InVec.getOperand(1);
14600 if (BaseShAmt.getNode() == 0) {
14601 // Don't create instructions with illegal types after legalize
14603 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14604 !DCI.isBeforeLegalize())
14607 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14608 DAG.getIntPtrConstant(0));
14613 // The shift amount is an i32.
14614 if (EltVT.bitsGT(MVT::i32))
14615 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14616 else if (EltVT.bitsLT(MVT::i32))
14617 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14619 // The shift amount is identical so we can do a vector shift.
14620 SDValue ValOp = N->getOperand(0);
14621 switch (N->getOpcode()) {
14623 llvm_unreachable("Unknown shift opcode!");
14625 switch (VT.getSimpleVT().SimpleTy) {
14626 default: return SDValue();
14633 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14636 switch (VT.getSimpleVT().SimpleTy) {
14637 default: return SDValue();
14642 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14645 switch (VT.getSimpleVT().SimpleTy) {
14646 default: return SDValue();
14653 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14659 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14660 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14661 // and friends. Likewise for OR -> CMPNEQSS.
14662 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14663 TargetLowering::DAGCombinerInfo &DCI,
14664 const X86Subtarget *Subtarget) {
14667 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14668 // we're requiring SSE2 for both.
14669 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14670 SDValue N0 = N->getOperand(0);
14671 SDValue N1 = N->getOperand(1);
14672 SDValue CMP0 = N0->getOperand(1);
14673 SDValue CMP1 = N1->getOperand(1);
14674 DebugLoc DL = N->getDebugLoc();
14676 // The SETCCs should both refer to the same CMP.
14677 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14680 SDValue CMP00 = CMP0->getOperand(0);
14681 SDValue CMP01 = CMP0->getOperand(1);
14682 EVT VT = CMP00.getValueType();
14684 if (VT == MVT::f32 || VT == MVT::f64) {
14685 bool ExpectingFlags = false;
14686 // Check for any users that want flags:
14687 for (SDNode::use_iterator UI = N->use_begin(),
14689 !ExpectingFlags && UI != UE; ++UI)
14690 switch (UI->getOpcode()) {
14695 ExpectingFlags = true;
14697 case ISD::CopyToReg:
14698 case ISD::SIGN_EXTEND:
14699 case ISD::ZERO_EXTEND:
14700 case ISD::ANY_EXTEND:
14704 if (!ExpectingFlags) {
14705 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14706 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14708 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14709 X86::CondCode tmp = cc0;
14714 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14715 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14716 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14717 X86ISD::NodeType NTOperator = is64BitFP ?
14718 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14719 // FIXME: need symbolic constants for these magic numbers.
14720 // See X86ATTInstPrinter.cpp:printSSECC().
14721 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14722 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14723 DAG.getConstant(x86cc, MVT::i8));
14724 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14726 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14727 DAG.getConstant(1, MVT::i32));
14728 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14729 return OneBitOfTruth;
14737 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14738 /// so it can be folded inside ANDNP.
14739 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14740 EVT VT = N->getValueType(0);
14742 // Match direct AllOnes for 128 and 256-bit vectors
14743 if (ISD::isBuildVectorAllOnes(N))
14746 // Look through a bit convert.
14747 if (N->getOpcode() == ISD::BITCAST)
14748 N = N->getOperand(0).getNode();
14750 // Sometimes the operand may come from a insert_subvector building a 256-bit
14752 if (VT.is256BitVector() &&
14753 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14754 SDValue V1 = N->getOperand(0);
14755 SDValue V2 = N->getOperand(1);
14757 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14758 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14759 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14760 ISD::isBuildVectorAllOnes(V2.getNode()))
14767 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14768 TargetLowering::DAGCombinerInfo &DCI,
14769 const X86Subtarget *Subtarget) {
14770 if (DCI.isBeforeLegalizeOps())
14773 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14777 EVT VT = N->getValueType(0);
14779 // Create ANDN, BLSI, and BLSR instructions
14780 // BLSI is X & (-X)
14781 // BLSR is X & (X-1)
14782 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14783 SDValue N0 = N->getOperand(0);
14784 SDValue N1 = N->getOperand(1);
14785 DebugLoc DL = N->getDebugLoc();
14787 // Check LHS for not
14788 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14789 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14790 // Check RHS for not
14791 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14792 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14794 // Check LHS for neg
14795 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14796 isZero(N0.getOperand(0)))
14797 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14799 // Check RHS for neg
14800 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14801 isZero(N1.getOperand(0)))
14802 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14804 // Check LHS for X-1
14805 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14806 isAllOnes(N0.getOperand(1)))
14807 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14809 // Check RHS for X-1
14810 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14811 isAllOnes(N1.getOperand(1)))
14812 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14817 // Want to form ANDNP nodes:
14818 // 1) In the hopes of then easily combining them with OR and AND nodes
14819 // to form PBLEND/PSIGN.
14820 // 2) To match ANDN packed intrinsics
14821 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14824 SDValue N0 = N->getOperand(0);
14825 SDValue N1 = N->getOperand(1);
14826 DebugLoc DL = N->getDebugLoc();
14828 // Check LHS for vnot
14829 if (N0.getOpcode() == ISD::XOR &&
14830 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14831 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14832 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14834 // Check RHS for vnot
14835 if (N1.getOpcode() == ISD::XOR &&
14836 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14837 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14838 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14843 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14844 TargetLowering::DAGCombinerInfo &DCI,
14845 const X86Subtarget *Subtarget) {
14846 if (DCI.isBeforeLegalizeOps())
14849 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14853 EVT VT = N->getValueType(0);
14855 SDValue N0 = N->getOperand(0);
14856 SDValue N1 = N->getOperand(1);
14858 // look for psign/blend
14859 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14860 if (!Subtarget->hasSSSE3() ||
14861 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14864 // Canonicalize pandn to RHS
14865 if (N0.getOpcode() == X86ISD::ANDNP)
14867 // or (and (m, y), (pandn m, x))
14868 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14869 SDValue Mask = N1.getOperand(0);
14870 SDValue X = N1.getOperand(1);
14872 if (N0.getOperand(0) == Mask)
14873 Y = N0.getOperand(1);
14874 if (N0.getOperand(1) == Mask)
14875 Y = N0.getOperand(0);
14877 // Check to see if the mask appeared in both the AND and ANDNP and
14881 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14882 // Look through mask bitcast.
14883 if (Mask.getOpcode() == ISD::BITCAST)
14884 Mask = Mask.getOperand(0);
14885 if (X.getOpcode() == ISD::BITCAST)
14886 X = X.getOperand(0);
14887 if (Y.getOpcode() == ISD::BITCAST)
14888 Y = Y.getOperand(0);
14890 EVT MaskVT = Mask.getValueType();
14892 // Validate that the Mask operand is a vector sra node.
14893 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14894 // there is no psrai.b
14895 if (Mask.getOpcode() != X86ISD::VSRAI)
14898 // Check that the SRA is all signbits.
14899 SDValue SraC = Mask.getOperand(1);
14900 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14901 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14902 if ((SraAmt + 1) != EltBits)
14905 DebugLoc DL = N->getDebugLoc();
14907 // Now we know we at least have a plendvb with the mask val. See if
14908 // we can form a psignb/w/d.
14909 // psign = x.type == y.type == mask.type && y = sub(0, x);
14910 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14911 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14912 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14913 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14914 "Unsupported VT for PSIGN");
14915 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14916 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14918 // PBLENDVB only available on SSE 4.1
14919 if (!Subtarget->hasSSE41())
14922 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14924 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14925 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14926 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14927 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14928 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14932 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14935 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14936 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14938 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14940 if (!N0.hasOneUse() || !N1.hasOneUse())
14943 SDValue ShAmt0 = N0.getOperand(1);
14944 if (ShAmt0.getValueType() != MVT::i8)
14946 SDValue ShAmt1 = N1.getOperand(1);
14947 if (ShAmt1.getValueType() != MVT::i8)
14949 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14950 ShAmt0 = ShAmt0.getOperand(0);
14951 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14952 ShAmt1 = ShAmt1.getOperand(0);
14954 DebugLoc DL = N->getDebugLoc();
14955 unsigned Opc = X86ISD::SHLD;
14956 SDValue Op0 = N0.getOperand(0);
14957 SDValue Op1 = N1.getOperand(0);
14958 if (ShAmt0.getOpcode() == ISD::SUB) {
14959 Opc = X86ISD::SHRD;
14960 std::swap(Op0, Op1);
14961 std::swap(ShAmt0, ShAmt1);
14964 unsigned Bits = VT.getSizeInBits();
14965 if (ShAmt1.getOpcode() == ISD::SUB) {
14966 SDValue Sum = ShAmt1.getOperand(0);
14967 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14968 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14969 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14970 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14971 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14972 return DAG.getNode(Opc, DL, VT,
14974 DAG.getNode(ISD::TRUNCATE, DL,
14977 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14978 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14980 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14981 return DAG.getNode(Opc, DL, VT,
14982 N0.getOperand(0), N1.getOperand(0),
14983 DAG.getNode(ISD::TRUNCATE, DL,
14990 // Generate NEG and CMOV for integer abs.
14991 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14992 EVT VT = N->getValueType(0);
14994 // Since X86 does not have CMOV for 8-bit integer, we don't convert
14995 // 8-bit integer abs to NEG and CMOV.
14996 if (VT.isInteger() && VT.getSizeInBits() == 8)
14999 SDValue N0 = N->getOperand(0);
15000 SDValue N1 = N->getOperand(1);
15001 DebugLoc DL = N->getDebugLoc();
15003 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15004 // and change it to SUB and CMOV.
15005 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15006 N0.getOpcode() == ISD::ADD &&
15007 N0.getOperand(1) == N1 &&
15008 N1.getOpcode() == ISD::SRA &&
15009 N1.getOperand(0) == N0.getOperand(0))
15010 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15011 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15012 // Generate SUB & CMOV.
15013 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15014 DAG.getConstant(0, VT), N0.getOperand(0));
15016 SDValue Ops[] = { N0.getOperand(0), Neg,
15017 DAG.getConstant(X86::COND_GE, MVT::i8),
15018 SDValue(Neg.getNode(), 1) };
15019 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15020 Ops, array_lengthof(Ops));
15025 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15026 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15027 TargetLowering::DAGCombinerInfo &DCI,
15028 const X86Subtarget *Subtarget) {
15029 if (DCI.isBeforeLegalizeOps())
15032 if (Subtarget->hasCMov()) {
15033 SDValue RV = performIntegerAbsCombine(N, DAG);
15038 // Try forming BMI if it is available.
15039 if (!Subtarget->hasBMI())
15042 EVT VT = N->getValueType(0);
15044 if (VT != MVT::i32 && VT != MVT::i64)
15047 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15049 // Create BLSMSK instructions by finding X ^ (X-1)
15050 SDValue N0 = N->getOperand(0);
15051 SDValue N1 = N->getOperand(1);
15052 DebugLoc DL = N->getDebugLoc();
15054 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15055 isAllOnes(N0.getOperand(1)))
15056 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15058 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15059 isAllOnes(N1.getOperand(1)))
15060 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15065 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15066 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15067 TargetLowering::DAGCombinerInfo &DCI,
15068 const X86Subtarget *Subtarget) {
15069 LoadSDNode *Ld = cast<LoadSDNode>(N);
15070 EVT RegVT = Ld->getValueType(0);
15071 EVT MemVT = Ld->getMemoryVT();
15072 DebugLoc dl = Ld->getDebugLoc();
15073 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15075 ISD::LoadExtType Ext = Ld->getExtensionType();
15077 // If this is a vector EXT Load then attempt to optimize it using a
15078 // shuffle. We need SSE4 for the shuffles.
15079 // TODO: It is possible to support ZExt by zeroing the undef values
15080 // during the shuffle phase or after the shuffle.
15081 if (RegVT.isVector() && RegVT.isInteger() &&
15082 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15083 assert(MemVT != RegVT && "Cannot extend to the same type");
15084 assert(MemVT.isVector() && "Must load a vector from memory");
15086 unsigned NumElems = RegVT.getVectorNumElements();
15087 unsigned RegSz = RegVT.getSizeInBits();
15088 unsigned MemSz = MemVT.getSizeInBits();
15089 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15091 // All sizes must be a power of two.
15092 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15095 // Attempt to load the original value using scalar loads.
15096 // Find the largest scalar type that divides the total loaded size.
15097 MVT SclrLoadTy = MVT::i8;
15098 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15099 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15100 MVT Tp = (MVT::SimpleValueType)tp;
15101 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15106 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15107 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15109 SclrLoadTy = MVT::f64;
15111 // Calculate the number of scalar loads that we need to perform
15112 // in order to load our vector from memory.
15113 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15115 // Represent our vector as a sequence of elements which are the
15116 // largest scalar that we can load.
15117 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15118 RegSz/SclrLoadTy.getSizeInBits());
15120 // Represent the data using the same element type that is stored in
15121 // memory. In practice, we ''widen'' MemVT.
15122 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15123 RegSz/MemVT.getScalarType().getSizeInBits());
15125 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15126 "Invalid vector type");
15128 // We can't shuffle using an illegal type.
15129 if (!TLI.isTypeLegal(WideVecVT))
15132 SmallVector<SDValue, 8> Chains;
15133 SDValue Ptr = Ld->getBasePtr();
15134 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15135 TLI.getPointerTy());
15136 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15138 for (unsigned i = 0; i < NumLoads; ++i) {
15139 // Perform a single load.
15140 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15141 Ptr, Ld->getPointerInfo(),
15142 Ld->isVolatile(), Ld->isNonTemporal(),
15143 Ld->isInvariant(), Ld->getAlignment());
15144 Chains.push_back(ScalarLoad.getValue(1));
15145 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15146 // another round of DAGCombining.
15148 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15150 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15151 ScalarLoad, DAG.getIntPtrConstant(i));
15153 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15156 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15159 // Bitcast the loaded value to a vector of the original element type, in
15160 // the size of the target vector type.
15161 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15162 unsigned SizeRatio = RegSz/MemSz;
15164 // Redistribute the loaded elements into the different locations.
15165 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15166 for (unsigned i = 0; i != NumElems; ++i)
15167 ShuffleVec[i*SizeRatio] = i;
15169 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15170 DAG.getUNDEF(WideVecVT),
15173 // Bitcast to the requested type.
15174 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15175 // Replace the original load with the new sequence
15176 // and return the new chain.
15177 return DCI.CombineTo(N, Shuff, TF, true);
15183 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15184 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15185 const X86Subtarget *Subtarget) {
15186 StoreSDNode *St = cast<StoreSDNode>(N);
15187 EVT VT = St->getValue().getValueType();
15188 EVT StVT = St->getMemoryVT();
15189 DebugLoc dl = St->getDebugLoc();
15190 SDValue StoredVal = St->getOperand(1);
15191 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15193 // If we are saving a concatenation of two XMM registers, perform two stores.
15194 // On Sandy Bridge, 256-bit memory operations are executed by two
15195 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15196 // memory operation.
15197 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15198 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15199 StoredVal.getNumOperands() == 2) {
15200 SDValue Value0 = StoredVal.getOperand(0);
15201 SDValue Value1 = StoredVal.getOperand(1);
15203 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15204 SDValue Ptr0 = St->getBasePtr();
15205 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15207 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15208 St->getPointerInfo(), St->isVolatile(),
15209 St->isNonTemporal(), St->getAlignment());
15210 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15211 St->getPointerInfo(), St->isVolatile(),
15212 St->isNonTemporal(), St->getAlignment());
15213 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15216 // Optimize trunc store (of multiple scalars) to shuffle and store.
15217 // First, pack all of the elements in one place. Next, store to memory
15218 // in fewer chunks.
15219 if (St->isTruncatingStore() && VT.isVector()) {
15220 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15221 unsigned NumElems = VT.getVectorNumElements();
15222 assert(StVT != VT && "Cannot truncate to the same type");
15223 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15224 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15226 // From, To sizes and ElemCount must be pow of two
15227 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15228 // We are going to use the original vector elt for storing.
15229 // Accumulated smaller vector elements must be a multiple of the store size.
15230 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15232 unsigned SizeRatio = FromSz / ToSz;
15234 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15236 // Create a type on which we perform the shuffle
15237 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15238 StVT.getScalarType(), NumElems*SizeRatio);
15240 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15242 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15243 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15244 for (unsigned i = 0; i != NumElems; ++i)
15245 ShuffleVec[i] = i * SizeRatio;
15247 // Can't shuffle using an illegal type.
15248 if (!TLI.isTypeLegal(WideVecVT))
15251 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15252 DAG.getUNDEF(WideVecVT),
15254 // At this point all of the data is stored at the bottom of the
15255 // register. We now need to save it to mem.
15257 // Find the largest store unit
15258 MVT StoreType = MVT::i8;
15259 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15260 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15261 MVT Tp = (MVT::SimpleValueType)tp;
15262 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15266 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15267 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15268 (64 <= NumElems * ToSz))
15269 StoreType = MVT::f64;
15271 // Bitcast the original vector into a vector of store-size units
15272 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15273 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15274 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15275 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15276 SmallVector<SDValue, 8> Chains;
15277 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15278 TLI.getPointerTy());
15279 SDValue Ptr = St->getBasePtr();
15281 // Perform one or more big stores into memory.
15282 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15283 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15284 StoreType, ShuffWide,
15285 DAG.getIntPtrConstant(i));
15286 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15287 St->getPointerInfo(), St->isVolatile(),
15288 St->isNonTemporal(), St->getAlignment());
15289 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15290 Chains.push_back(Ch);
15293 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15298 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15299 // the FP state in cases where an emms may be missing.
15300 // A preferable solution to the general problem is to figure out the right
15301 // places to insert EMMS. This qualifies as a quick hack.
15303 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15304 if (VT.getSizeInBits() != 64)
15307 const Function *F = DAG.getMachineFunction().getFunction();
15308 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15309 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15310 && Subtarget->hasSSE2();
15311 if ((VT.isVector() ||
15312 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15313 isa<LoadSDNode>(St->getValue()) &&
15314 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15315 St->getChain().hasOneUse() && !St->isVolatile()) {
15316 SDNode* LdVal = St->getValue().getNode();
15317 LoadSDNode *Ld = 0;
15318 int TokenFactorIndex = -1;
15319 SmallVector<SDValue, 8> Ops;
15320 SDNode* ChainVal = St->getChain().getNode();
15321 // Must be a store of a load. We currently handle two cases: the load
15322 // is a direct child, and it's under an intervening TokenFactor. It is
15323 // possible to dig deeper under nested TokenFactors.
15324 if (ChainVal == LdVal)
15325 Ld = cast<LoadSDNode>(St->getChain());
15326 else if (St->getValue().hasOneUse() &&
15327 ChainVal->getOpcode() == ISD::TokenFactor) {
15328 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15329 if (ChainVal->getOperand(i).getNode() == LdVal) {
15330 TokenFactorIndex = i;
15331 Ld = cast<LoadSDNode>(St->getValue());
15333 Ops.push_back(ChainVal->getOperand(i));
15337 if (!Ld || !ISD::isNormalLoad(Ld))
15340 // If this is not the MMX case, i.e. we are just turning i64 load/store
15341 // into f64 load/store, avoid the transformation if there are multiple
15342 // uses of the loaded value.
15343 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15346 DebugLoc LdDL = Ld->getDebugLoc();
15347 DebugLoc StDL = N->getDebugLoc();
15348 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15349 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15351 if (Subtarget->is64Bit() || F64IsLegal) {
15352 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15353 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15354 Ld->getPointerInfo(), Ld->isVolatile(),
15355 Ld->isNonTemporal(), Ld->isInvariant(),
15356 Ld->getAlignment());
15357 SDValue NewChain = NewLd.getValue(1);
15358 if (TokenFactorIndex != -1) {
15359 Ops.push_back(NewChain);
15360 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15363 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15364 St->getPointerInfo(),
15365 St->isVolatile(), St->isNonTemporal(),
15366 St->getAlignment());
15369 // Otherwise, lower to two pairs of 32-bit loads / stores.
15370 SDValue LoAddr = Ld->getBasePtr();
15371 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15372 DAG.getConstant(4, MVT::i32));
15374 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15375 Ld->getPointerInfo(),
15376 Ld->isVolatile(), Ld->isNonTemporal(),
15377 Ld->isInvariant(), Ld->getAlignment());
15378 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15379 Ld->getPointerInfo().getWithOffset(4),
15380 Ld->isVolatile(), Ld->isNonTemporal(),
15382 MinAlign(Ld->getAlignment(), 4));
15384 SDValue NewChain = LoLd.getValue(1);
15385 if (TokenFactorIndex != -1) {
15386 Ops.push_back(LoLd);
15387 Ops.push_back(HiLd);
15388 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15392 LoAddr = St->getBasePtr();
15393 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15394 DAG.getConstant(4, MVT::i32));
15396 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15397 St->getPointerInfo(),
15398 St->isVolatile(), St->isNonTemporal(),
15399 St->getAlignment());
15400 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15401 St->getPointerInfo().getWithOffset(4),
15403 St->isNonTemporal(),
15404 MinAlign(St->getAlignment(), 4));
15405 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15410 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15411 /// and return the operands for the horizontal operation in LHS and RHS. A
15412 /// horizontal operation performs the binary operation on successive elements
15413 /// of its first operand, then on successive elements of its second operand,
15414 /// returning the resulting values in a vector. For example, if
15415 /// A = < float a0, float a1, float a2, float a3 >
15417 /// B = < float b0, float b1, float b2, float b3 >
15418 /// then the result of doing a horizontal operation on A and B is
15419 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15420 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15421 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15422 /// set to A, RHS to B, and the routine returns 'true'.
15423 /// Note that the binary operation should have the property that if one of the
15424 /// operands is UNDEF then the result is UNDEF.
15425 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15426 // Look for the following pattern: if
15427 // A = < float a0, float a1, float a2, float a3 >
15428 // B = < float b0, float b1, float b2, float b3 >
15430 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15431 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15432 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15433 // which is A horizontal-op B.
15435 // At least one of the operands should be a vector shuffle.
15436 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15437 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15440 EVT VT = LHS.getValueType();
15442 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15443 "Unsupported vector type for horizontal add/sub");
15445 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15446 // operate independently on 128-bit lanes.
15447 unsigned NumElts = VT.getVectorNumElements();
15448 unsigned NumLanes = VT.getSizeInBits()/128;
15449 unsigned NumLaneElts = NumElts / NumLanes;
15450 assert((NumLaneElts % 2 == 0) &&
15451 "Vector type should have an even number of elements in each lane");
15452 unsigned HalfLaneElts = NumLaneElts/2;
15454 // View LHS in the form
15455 // LHS = VECTOR_SHUFFLE A, B, LMask
15456 // If LHS is not a shuffle then pretend it is the shuffle
15457 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15458 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15461 SmallVector<int, 16> LMask(NumElts);
15462 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15463 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15464 A = LHS.getOperand(0);
15465 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15466 B = LHS.getOperand(1);
15467 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15468 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15470 if (LHS.getOpcode() != ISD::UNDEF)
15472 for (unsigned i = 0; i != NumElts; ++i)
15476 // Likewise, view RHS in the form
15477 // RHS = VECTOR_SHUFFLE C, D, RMask
15479 SmallVector<int, 16> RMask(NumElts);
15480 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15481 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15482 C = RHS.getOperand(0);
15483 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15484 D = RHS.getOperand(1);
15485 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15486 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15488 if (RHS.getOpcode() != ISD::UNDEF)
15490 for (unsigned i = 0; i != NumElts; ++i)
15494 // Check that the shuffles are both shuffling the same vectors.
15495 if (!(A == C && B == D) && !(A == D && B == C))
15498 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15499 if (!A.getNode() && !B.getNode())
15502 // If A and B occur in reverse order in RHS, then "swap" them (which means
15503 // rewriting the mask).
15505 CommuteVectorShuffleMask(RMask, NumElts);
15507 // At this point LHS and RHS are equivalent to
15508 // LHS = VECTOR_SHUFFLE A, B, LMask
15509 // RHS = VECTOR_SHUFFLE A, B, RMask
15510 // Check that the masks correspond to performing a horizontal operation.
15511 for (unsigned i = 0; i != NumElts; ++i) {
15512 int LIdx = LMask[i], RIdx = RMask[i];
15514 // Ignore any UNDEF components.
15515 if (LIdx < 0 || RIdx < 0 ||
15516 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15517 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15520 // Check that successive elements are being operated on. If not, this is
15521 // not a horizontal operation.
15522 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15523 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15524 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15525 if (!(LIdx == Index && RIdx == Index + 1) &&
15526 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15530 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15531 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15535 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15536 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15537 const X86Subtarget *Subtarget) {
15538 EVT VT = N->getValueType(0);
15539 SDValue LHS = N->getOperand(0);
15540 SDValue RHS = N->getOperand(1);
15542 // Try to synthesize horizontal adds from adds of shuffles.
15543 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15544 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15545 isHorizontalBinOp(LHS, RHS, true))
15546 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15550 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15551 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15552 const X86Subtarget *Subtarget) {
15553 EVT VT = N->getValueType(0);
15554 SDValue LHS = N->getOperand(0);
15555 SDValue RHS = N->getOperand(1);
15557 // Try to synthesize horizontal subs from subs of shuffles.
15558 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15559 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15560 isHorizontalBinOp(LHS, RHS, false))
15561 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15565 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15566 /// X86ISD::FXOR nodes.
15567 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15568 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15569 // F[X]OR(0.0, x) -> x
15570 // F[X]OR(x, 0.0) -> x
15571 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15572 if (C->getValueAPF().isPosZero())
15573 return N->getOperand(1);
15574 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15575 if (C->getValueAPF().isPosZero())
15576 return N->getOperand(0);
15580 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15581 /// X86ISD::FMAX nodes.
15582 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15583 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15585 // Only perform optimizations if UnsafeMath is used.
15586 if (!DAG.getTarget().Options.UnsafeFPMath)
15589 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15590 // into FMINC and FMAXC, which are Commutative operations.
15591 unsigned NewOp = 0;
15592 switch (N->getOpcode()) {
15593 default: llvm_unreachable("unknown opcode");
15594 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
15595 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
15598 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15599 N->getOperand(0), N->getOperand(1));
15603 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15604 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15605 // FAND(0.0, x) -> 0.0
15606 // FAND(x, 0.0) -> 0.0
15607 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15608 if (C->getValueAPF().isPosZero())
15609 return N->getOperand(0);
15610 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15611 if (C->getValueAPF().isPosZero())
15612 return N->getOperand(1);
15616 static SDValue PerformBTCombine(SDNode *N,
15618 TargetLowering::DAGCombinerInfo &DCI) {
15619 // BT ignores high bits in the bit index operand.
15620 SDValue Op1 = N->getOperand(1);
15621 if (Op1.hasOneUse()) {
15622 unsigned BitWidth = Op1.getValueSizeInBits();
15623 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15624 APInt KnownZero, KnownOne;
15625 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15626 !DCI.isBeforeLegalizeOps());
15627 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15628 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15629 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15630 DCI.CommitTargetLoweringOpt(TLO);
15635 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15636 SDValue Op = N->getOperand(0);
15637 if (Op.getOpcode() == ISD::BITCAST)
15638 Op = Op.getOperand(0);
15639 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15640 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15641 VT.getVectorElementType().getSizeInBits() ==
15642 OpVT.getVectorElementType().getSizeInBits()) {
15643 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15648 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15649 TargetLowering::DAGCombinerInfo &DCI,
15650 const X86Subtarget *Subtarget) {
15651 if (!DCI.isBeforeLegalizeOps())
15654 if (!Subtarget->hasAVX())
15657 EVT VT = N->getValueType(0);
15658 SDValue Op = N->getOperand(0);
15659 EVT OpVT = Op.getValueType();
15660 DebugLoc dl = N->getDebugLoc();
15662 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15663 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15665 if (Subtarget->hasAVX2())
15666 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15668 // Optimize vectors in AVX mode
15669 // Sign extend v8i16 to v8i32 and
15672 // Divide input vector into two parts
15673 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15674 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15675 // concat the vectors to original VT
15677 unsigned NumElems = OpVT.getVectorNumElements();
15678 SDValue Undef = DAG.getUNDEF(OpVT);
15680 SmallVector<int,8> ShufMask1(NumElems, -1);
15681 for (unsigned i = 0; i != NumElems/2; ++i)
15684 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15686 SmallVector<int,8> ShufMask2(NumElems, -1);
15687 for (unsigned i = 0; i != NumElems/2; ++i)
15688 ShufMask2[i] = i + NumElems/2;
15690 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15692 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15693 VT.getVectorNumElements()/2);
15695 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15696 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15698 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15703 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15704 const X86Subtarget* Subtarget) {
15705 DebugLoc dl = N->getDebugLoc();
15706 EVT VT = N->getValueType(0);
15708 // Let legalize expand this if it isn't a legal type yet.
15709 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15712 EVT ScalarVT = VT.getScalarType();
15713 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15714 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15717 SDValue A = N->getOperand(0);
15718 SDValue B = N->getOperand(1);
15719 SDValue C = N->getOperand(2);
15721 bool NegA = (A.getOpcode() == ISD::FNEG);
15722 bool NegB = (B.getOpcode() == ISD::FNEG);
15723 bool NegC = (C.getOpcode() == ISD::FNEG);
15725 // Negative multiplication when NegA xor NegB
15726 bool NegMul = (NegA != NegB);
15728 A = A.getOperand(0);
15730 B = B.getOperand(0);
15732 C = C.getOperand(0);
15736 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15738 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15740 return DAG.getNode(Opcode, dl, VT, A, B, C);
15743 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15744 TargetLowering::DAGCombinerInfo &DCI,
15745 const X86Subtarget *Subtarget) {
15746 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15747 // (and (i32 x86isd::setcc_carry), 1)
15748 // This eliminates the zext. This transformation is necessary because
15749 // ISD::SETCC is always legalized to i8.
15750 DebugLoc dl = N->getDebugLoc();
15751 SDValue N0 = N->getOperand(0);
15752 EVT VT = N->getValueType(0);
15753 EVT OpVT = N0.getValueType();
15755 if (N0.getOpcode() == ISD::AND &&
15757 N0.getOperand(0).hasOneUse()) {
15758 SDValue N00 = N0.getOperand(0);
15759 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15761 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15762 if (!C || C->getZExtValue() != 1)
15764 return DAG.getNode(ISD::AND, dl, VT,
15765 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15766 N00.getOperand(0), N00.getOperand(1)),
15767 DAG.getConstant(1, VT));
15770 // Optimize vectors in AVX mode:
15773 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15774 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15775 // Concat upper and lower parts.
15778 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15779 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15780 // Concat upper and lower parts.
15782 if (!DCI.isBeforeLegalizeOps())
15785 if (!Subtarget->hasAVX())
15788 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15789 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15791 if (Subtarget->hasAVX2())
15792 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15794 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15795 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15796 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15798 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15799 VT.getVectorNumElements()/2);
15801 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15802 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15804 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15810 // Optimize x == -y --> x+y == 0
15811 // x != -y --> x+y != 0
15812 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15813 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15814 SDValue LHS = N->getOperand(0);
15815 SDValue RHS = N->getOperand(1);
15817 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15818 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15819 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15820 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15821 LHS.getValueType(), RHS, LHS.getOperand(1));
15822 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15823 addV, DAG.getConstant(0, addV.getValueType()), CC);
15825 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15826 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15827 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15828 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15829 RHS.getValueType(), LHS, RHS.getOperand(1));
15830 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15831 addV, DAG.getConstant(0, addV.getValueType()), CC);
15836 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15837 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15838 TargetLowering::DAGCombinerInfo &DCI,
15839 const X86Subtarget *Subtarget) {
15840 DebugLoc DL = N->getDebugLoc();
15841 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15842 SDValue EFLAGS = N->getOperand(1);
15844 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15845 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15847 if (CC == X86::COND_B)
15848 return DAG.getNode(ISD::AND, DL, MVT::i8,
15849 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15850 DAG.getConstant(CC, MVT::i8), EFLAGS),
15851 DAG.getConstant(1, MVT::i8));
15855 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15856 if (Flags.getNode()) {
15857 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15858 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15861 Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15862 if (Flags.getNode()) {
15863 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15864 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15870 // Optimize branch condition evaluation.
15872 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15873 TargetLowering::DAGCombinerInfo &DCI,
15874 const X86Subtarget *Subtarget) {
15875 DebugLoc DL = N->getDebugLoc();
15876 SDValue Chain = N->getOperand(0);
15877 SDValue Dest = N->getOperand(1);
15878 SDValue EFLAGS = N->getOperand(3);
15879 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15883 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15884 if (Flags.getNode()) {
15885 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15886 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15890 Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15891 if (Flags.getNode()) {
15892 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15893 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15900 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15901 SDValue Op0 = N->getOperand(0);
15902 EVT InVT = Op0->getValueType(0);
15904 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15905 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15906 DebugLoc dl = N->getDebugLoc();
15907 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15908 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15909 // Notice that we use SINT_TO_FP because we know that the high bits
15910 // are zero and SINT_TO_FP is better supported by the hardware.
15911 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15917 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15918 const X86TargetLowering *XTLI) {
15919 SDValue Op0 = N->getOperand(0);
15920 EVT InVT = Op0->getValueType(0);
15922 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15923 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15924 DebugLoc dl = N->getDebugLoc();
15925 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15926 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15927 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15930 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15931 // a 32-bit target where SSE doesn't support i64->FP operations.
15932 if (Op0.getOpcode() == ISD::LOAD) {
15933 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15934 EVT VT = Ld->getValueType(0);
15935 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15936 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15937 !XTLI->getSubtarget()->is64Bit() &&
15938 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15939 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15940 Ld->getChain(), Op0, DAG);
15941 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15948 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15949 EVT VT = N->getValueType(0);
15951 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15952 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15953 DebugLoc dl = N->getDebugLoc();
15954 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15955 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15956 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15962 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15963 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15964 X86TargetLowering::DAGCombinerInfo &DCI) {
15965 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15966 // the result is either zero or one (depending on the input carry bit).
15967 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15968 if (X86::isZeroNode(N->getOperand(0)) &&
15969 X86::isZeroNode(N->getOperand(1)) &&
15970 // We don't have a good way to replace an EFLAGS use, so only do this when
15972 SDValue(N, 1).use_empty()) {
15973 DebugLoc DL = N->getDebugLoc();
15974 EVT VT = N->getValueType(0);
15975 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15976 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15977 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15978 DAG.getConstant(X86::COND_B,MVT::i8),
15980 DAG.getConstant(1, VT));
15981 return DCI.CombineTo(N, Res1, CarryOut);
15987 // fold (add Y, (sete X, 0)) -> adc 0, Y
15988 // (add Y, (setne X, 0)) -> sbb -1, Y
15989 // (sub (sete X, 0), Y) -> sbb 0, Y
15990 // (sub (setne X, 0), Y) -> adc -1, Y
15991 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15992 DebugLoc DL = N->getDebugLoc();
15994 // Look through ZExts.
15995 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15996 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15999 SDValue SetCC = Ext.getOperand(0);
16000 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16003 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16004 if (CC != X86::COND_E && CC != X86::COND_NE)
16007 SDValue Cmp = SetCC.getOperand(1);
16008 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16009 !X86::isZeroNode(Cmp.getOperand(1)) ||
16010 !Cmp.getOperand(0).getValueType().isInteger())
16013 SDValue CmpOp0 = Cmp.getOperand(0);
16014 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16015 DAG.getConstant(1, CmpOp0.getValueType()));
16017 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16018 if (CC == X86::COND_NE)
16019 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16020 DL, OtherVal.getValueType(), OtherVal,
16021 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16022 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16023 DL, OtherVal.getValueType(), OtherVal,
16024 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16027 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16028 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16029 const X86Subtarget *Subtarget) {
16030 EVT VT = N->getValueType(0);
16031 SDValue Op0 = N->getOperand(0);
16032 SDValue Op1 = N->getOperand(1);
16034 // Try to synthesize horizontal adds from adds of shuffles.
16035 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16036 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16037 isHorizontalBinOp(Op0, Op1, true))
16038 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16040 return OptimizeConditionalInDecrement(N, DAG);
16043 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16044 const X86Subtarget *Subtarget) {
16045 SDValue Op0 = N->getOperand(0);
16046 SDValue Op1 = N->getOperand(1);
16048 // X86 can't encode an immediate LHS of a sub. See if we can push the
16049 // negation into a preceding instruction.
16050 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16051 // If the RHS of the sub is a XOR with one use and a constant, invert the
16052 // immediate. Then add one to the LHS of the sub so we can turn
16053 // X-Y -> X+~Y+1, saving one register.
16054 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16055 isa<ConstantSDNode>(Op1.getOperand(1))) {
16056 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16057 EVT VT = Op0.getValueType();
16058 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16060 DAG.getConstant(~XorC, VT));
16061 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16062 DAG.getConstant(C->getAPIntValue()+1, VT));
16066 // Try to synthesize horizontal adds from adds of shuffles.
16067 EVT VT = N->getValueType(0);
16068 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16069 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16070 isHorizontalBinOp(Op0, Op1, true))
16071 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16073 return OptimizeConditionalInDecrement(N, DAG);
16076 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16077 DAGCombinerInfo &DCI) const {
16078 SelectionDAG &DAG = DCI.DAG;
16079 switch (N->getOpcode()) {
16081 case ISD::EXTRACT_VECTOR_ELT:
16082 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16084 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16085 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16086 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16087 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16088 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16089 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16092 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16093 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16094 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16095 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16096 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16097 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16098 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16099 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16100 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
16101 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16102 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16104 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16106 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16107 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16108 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16109 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16110 case ISD::ANY_EXTEND:
16111 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16112 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16113 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG, DCI);
16114 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16115 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16116 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16117 case X86ISD::SHUFP: // Handle all target specific shuffles
16118 case X86ISD::PALIGN:
16119 case X86ISD::UNPCKH:
16120 case X86ISD::UNPCKL:
16121 case X86ISD::MOVHLPS:
16122 case X86ISD::MOVLHPS:
16123 case X86ISD::PSHUFD:
16124 case X86ISD::PSHUFHW:
16125 case X86ISD::PSHUFLW:
16126 case X86ISD::MOVSS:
16127 case X86ISD::MOVSD:
16128 case X86ISD::VPERMILP:
16129 case X86ISD::VPERM2X128:
16130 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16131 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16137 /// isTypeDesirableForOp - Return true if the target has native support for
16138 /// the specified value type and it is 'desirable' to use the type for the
16139 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16140 /// instruction encodings are longer and some i16 instructions are slow.
16141 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16142 if (!isTypeLegal(VT))
16144 if (VT != MVT::i16)
16151 case ISD::SIGN_EXTEND:
16152 case ISD::ZERO_EXTEND:
16153 case ISD::ANY_EXTEND:
16166 /// IsDesirableToPromoteOp - This method query the target whether it is
16167 /// beneficial for dag combiner to promote the specified node. If true, it
16168 /// should return the desired promotion type by reference.
16169 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16170 EVT VT = Op.getValueType();
16171 if (VT != MVT::i16)
16174 bool Promote = false;
16175 bool Commute = false;
16176 switch (Op.getOpcode()) {
16179 LoadSDNode *LD = cast<LoadSDNode>(Op);
16180 // If the non-extending load has a single use and it's not live out, then it
16181 // might be folded.
16182 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16183 Op.hasOneUse()*/) {
16184 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16185 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16186 // The only case where we'd want to promote LOAD (rather then it being
16187 // promoted as an operand is when it's only use is liveout.
16188 if (UI->getOpcode() != ISD::CopyToReg)
16195 case ISD::SIGN_EXTEND:
16196 case ISD::ZERO_EXTEND:
16197 case ISD::ANY_EXTEND:
16202 SDValue N0 = Op.getOperand(0);
16203 // Look out for (store (shl (load), x)).
16204 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16217 SDValue N0 = Op.getOperand(0);
16218 SDValue N1 = Op.getOperand(1);
16219 if (!Commute && MayFoldLoad(N1))
16221 // Avoid disabling potential load folding opportunities.
16222 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16224 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16234 //===----------------------------------------------------------------------===//
16235 // X86 Inline Assembly Support
16236 //===----------------------------------------------------------------------===//
16239 // Helper to match a string separated by whitespace.
16240 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16241 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16243 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16244 StringRef piece(*args[i]);
16245 if (!s.startswith(piece)) // Check if the piece matches.
16248 s = s.substr(piece.size());
16249 StringRef::size_type pos = s.find_first_not_of(" \t");
16250 if (pos == 0) // We matched a prefix.
16258 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16261 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16262 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16264 std::string AsmStr = IA->getAsmString();
16266 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16267 if (!Ty || Ty->getBitWidth() % 16 != 0)
16270 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16271 SmallVector<StringRef, 4> AsmPieces;
16272 SplitString(AsmStr, AsmPieces, ";\n");
16274 switch (AsmPieces.size()) {
16275 default: return false;
16277 // FIXME: this should verify that we are targeting a 486 or better. If not,
16278 // we will turn this bswap into something that will be lowered to logical
16279 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16280 // lower so don't worry about this.
16282 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16283 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16284 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16285 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16286 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16287 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16288 // No need to check constraints, nothing other than the equivalent of
16289 // "=r,0" would be valid here.
16290 return IntrinsicLowering::LowerToByteSwap(CI);
16293 // rorw $$8, ${0:w} --> llvm.bswap.i16
16294 if (CI->getType()->isIntegerTy(16) &&
16295 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16296 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16297 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16299 const std::string &ConstraintsStr = IA->getConstraintString();
16300 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16301 std::sort(AsmPieces.begin(), AsmPieces.end());
16302 if (AsmPieces.size() == 4 &&
16303 AsmPieces[0] == "~{cc}" &&
16304 AsmPieces[1] == "~{dirflag}" &&
16305 AsmPieces[2] == "~{flags}" &&
16306 AsmPieces[3] == "~{fpsr}")
16307 return IntrinsicLowering::LowerToByteSwap(CI);
16311 if (CI->getType()->isIntegerTy(32) &&
16312 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16313 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16314 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16315 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16317 const std::string &ConstraintsStr = IA->getConstraintString();
16318 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16319 std::sort(AsmPieces.begin(), AsmPieces.end());
16320 if (AsmPieces.size() == 4 &&
16321 AsmPieces[0] == "~{cc}" &&
16322 AsmPieces[1] == "~{dirflag}" &&
16323 AsmPieces[2] == "~{flags}" &&
16324 AsmPieces[3] == "~{fpsr}")
16325 return IntrinsicLowering::LowerToByteSwap(CI);
16328 if (CI->getType()->isIntegerTy(64)) {
16329 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16330 if (Constraints.size() >= 2 &&
16331 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16332 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16333 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16334 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16335 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16336 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16337 return IntrinsicLowering::LowerToByteSwap(CI);
16347 /// getConstraintType - Given a constraint letter, return the type of
16348 /// constraint it is for this target.
16349 X86TargetLowering::ConstraintType
16350 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16351 if (Constraint.size() == 1) {
16352 switch (Constraint[0]) {
16363 return C_RegisterClass;
16387 return TargetLowering::getConstraintType(Constraint);
16390 /// Examine constraint type and operand type and determine a weight value.
16391 /// This object must already have been set up with the operand type
16392 /// and the current alternative constraint selected.
16393 TargetLowering::ConstraintWeight
16394 X86TargetLowering::getSingleConstraintMatchWeight(
16395 AsmOperandInfo &info, const char *constraint) const {
16396 ConstraintWeight weight = CW_Invalid;
16397 Value *CallOperandVal = info.CallOperandVal;
16398 // If we don't have a value, we can't do a match,
16399 // but allow it at the lowest weight.
16400 if (CallOperandVal == NULL)
16402 Type *type = CallOperandVal->getType();
16403 // Look at the constraint type.
16404 switch (*constraint) {
16406 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16417 if (CallOperandVal->getType()->isIntegerTy())
16418 weight = CW_SpecificReg;
16423 if (type->isFloatingPointTy())
16424 weight = CW_SpecificReg;
16427 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16428 weight = CW_SpecificReg;
16432 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16433 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16434 weight = CW_Register;
16437 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16438 if (C->getZExtValue() <= 31)
16439 weight = CW_Constant;
16443 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16444 if (C->getZExtValue() <= 63)
16445 weight = CW_Constant;
16449 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16450 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16451 weight = CW_Constant;
16455 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16456 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16457 weight = CW_Constant;
16461 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16462 if (C->getZExtValue() <= 3)
16463 weight = CW_Constant;
16467 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16468 if (C->getZExtValue() <= 0xff)
16469 weight = CW_Constant;
16474 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16475 weight = CW_Constant;
16479 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16480 if ((C->getSExtValue() >= -0x80000000LL) &&
16481 (C->getSExtValue() <= 0x7fffffffLL))
16482 weight = CW_Constant;
16486 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16487 if (C->getZExtValue() <= 0xffffffff)
16488 weight = CW_Constant;
16495 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16496 /// with another that has more specific requirements based on the type of the
16497 /// corresponding operand.
16498 const char *X86TargetLowering::
16499 LowerXConstraint(EVT ConstraintVT) const {
16500 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16501 // 'f' like normal targets.
16502 if (ConstraintVT.isFloatingPoint()) {
16503 if (Subtarget->hasSSE2())
16505 if (Subtarget->hasSSE1())
16509 return TargetLowering::LowerXConstraint(ConstraintVT);
16512 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16513 /// vector. If it is invalid, don't add anything to Ops.
16514 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16515 std::string &Constraint,
16516 std::vector<SDValue>&Ops,
16517 SelectionDAG &DAG) const {
16518 SDValue Result(0, 0);
16520 // Only support length 1 constraints for now.
16521 if (Constraint.length() > 1) return;
16523 char ConstraintLetter = Constraint[0];
16524 switch (ConstraintLetter) {
16527 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16528 if (C->getZExtValue() <= 31) {
16529 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16535 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16536 if (C->getZExtValue() <= 63) {
16537 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16543 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16544 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16545 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16551 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16552 if (C->getZExtValue() <= 255) {
16553 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16559 // 32-bit signed value
16560 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16561 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16562 C->getSExtValue())) {
16563 // Widen to 64 bits here to get it sign extended.
16564 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16567 // FIXME gcc accepts some relocatable values here too, but only in certain
16568 // memory models; it's complicated.
16573 // 32-bit unsigned value
16574 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16575 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16576 C->getZExtValue())) {
16577 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16581 // FIXME gcc accepts some relocatable values here too, but only in certain
16582 // memory models; it's complicated.
16586 // Literal immediates are always ok.
16587 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16588 // Widen to 64 bits here to get it sign extended.
16589 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16593 // In any sort of PIC mode addresses need to be computed at runtime by
16594 // adding in a register or some sort of table lookup. These can't
16595 // be used as immediates.
16596 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16599 // If we are in non-pic codegen mode, we allow the address of a global (with
16600 // an optional displacement) to be used with 'i'.
16601 GlobalAddressSDNode *GA = 0;
16602 int64_t Offset = 0;
16604 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16606 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16607 Offset += GA->getOffset();
16609 } else if (Op.getOpcode() == ISD::ADD) {
16610 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16611 Offset += C->getZExtValue();
16612 Op = Op.getOperand(0);
16615 } else if (Op.getOpcode() == ISD::SUB) {
16616 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16617 Offset += -C->getZExtValue();
16618 Op = Op.getOperand(0);
16623 // Otherwise, this isn't something we can handle, reject it.
16627 const GlobalValue *GV = GA->getGlobal();
16628 // If we require an extra load to get this address, as in PIC mode, we
16629 // can't accept it.
16630 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16631 getTargetMachine())))
16634 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16635 GA->getValueType(0), Offset);
16640 if (Result.getNode()) {
16641 Ops.push_back(Result);
16644 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16647 std::pair<unsigned, const TargetRegisterClass*>
16648 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16650 // First, see if this is a constraint that directly corresponds to an LLVM
16652 if (Constraint.size() == 1) {
16653 // GCC Constraint Letters
16654 switch (Constraint[0]) {
16656 // TODO: Slight differences here in allocation order and leaving
16657 // RIP in the class. Do they matter any more here than they do
16658 // in the normal allocation?
16659 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16660 if (Subtarget->is64Bit()) {
16661 if (VT == MVT::i32 || VT == MVT::f32)
16662 return std::make_pair(0U, &X86::GR32RegClass);
16663 if (VT == MVT::i16)
16664 return std::make_pair(0U, &X86::GR16RegClass);
16665 if (VT == MVT::i8 || VT == MVT::i1)
16666 return std::make_pair(0U, &X86::GR8RegClass);
16667 if (VT == MVT::i64 || VT == MVT::f64)
16668 return std::make_pair(0U, &X86::GR64RegClass);
16671 // 32-bit fallthrough
16672 case 'Q': // Q_REGS
16673 if (VT == MVT::i32 || VT == MVT::f32)
16674 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16675 if (VT == MVT::i16)
16676 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16677 if (VT == MVT::i8 || VT == MVT::i1)
16678 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16679 if (VT == MVT::i64)
16680 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16682 case 'r': // GENERAL_REGS
16683 case 'l': // INDEX_REGS
16684 if (VT == MVT::i8 || VT == MVT::i1)
16685 return std::make_pair(0U, &X86::GR8RegClass);
16686 if (VT == MVT::i16)
16687 return std::make_pair(0U, &X86::GR16RegClass);
16688 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16689 return std::make_pair(0U, &X86::GR32RegClass);
16690 return std::make_pair(0U, &X86::GR64RegClass);
16691 case 'R': // LEGACY_REGS
16692 if (VT == MVT::i8 || VT == MVT::i1)
16693 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16694 if (VT == MVT::i16)
16695 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16696 if (VT == MVT::i32 || !Subtarget->is64Bit())
16697 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16698 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16699 case 'f': // FP Stack registers.
16700 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16701 // value to the correct fpstack register class.
16702 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16703 return std::make_pair(0U, &X86::RFP32RegClass);
16704 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16705 return std::make_pair(0U, &X86::RFP64RegClass);
16706 return std::make_pair(0U, &X86::RFP80RegClass);
16707 case 'y': // MMX_REGS if MMX allowed.
16708 if (!Subtarget->hasMMX()) break;
16709 return std::make_pair(0U, &X86::VR64RegClass);
16710 case 'Y': // SSE_REGS if SSE2 allowed
16711 if (!Subtarget->hasSSE2()) break;
16713 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16714 if (!Subtarget->hasSSE1()) break;
16716 switch (VT.getSimpleVT().SimpleTy) {
16718 // Scalar SSE types.
16721 return std::make_pair(0U, &X86::FR32RegClass);
16724 return std::make_pair(0U, &X86::FR64RegClass);
16732 return std::make_pair(0U, &X86::VR128RegClass);
16740 return std::make_pair(0U, &X86::VR256RegClass);
16746 // Use the default implementation in TargetLowering to convert the register
16747 // constraint into a member of a register class.
16748 std::pair<unsigned, const TargetRegisterClass*> Res;
16749 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16751 // Not found as a standard register?
16752 if (Res.second == 0) {
16753 // Map st(0) -> st(7) -> ST0
16754 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16755 tolower(Constraint[1]) == 's' &&
16756 tolower(Constraint[2]) == 't' &&
16757 Constraint[3] == '(' &&
16758 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16759 Constraint[5] == ')' &&
16760 Constraint[6] == '}') {
16762 Res.first = X86::ST0+Constraint[4]-'0';
16763 Res.second = &X86::RFP80RegClass;
16767 // GCC allows "st(0)" to be called just plain "st".
16768 if (StringRef("{st}").equals_lower(Constraint)) {
16769 Res.first = X86::ST0;
16770 Res.second = &X86::RFP80RegClass;
16775 if (StringRef("{flags}").equals_lower(Constraint)) {
16776 Res.first = X86::EFLAGS;
16777 Res.second = &X86::CCRRegClass;
16781 // 'A' means EAX + EDX.
16782 if (Constraint == "A") {
16783 Res.first = X86::EAX;
16784 Res.second = &X86::GR32_ADRegClass;
16790 // Otherwise, check to see if this is a register class of the wrong value
16791 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16792 // turn into {ax},{dx}.
16793 if (Res.second->hasType(VT))
16794 return Res; // Correct type already, nothing to do.
16796 // All of the single-register GCC register classes map their values onto
16797 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16798 // really want an 8-bit or 32-bit register, map to the appropriate register
16799 // class and return the appropriate register.
16800 if (Res.second == &X86::GR16RegClass) {
16801 if (VT == MVT::i8) {
16802 unsigned DestReg = 0;
16803 switch (Res.first) {
16805 case X86::AX: DestReg = X86::AL; break;
16806 case X86::DX: DestReg = X86::DL; break;
16807 case X86::CX: DestReg = X86::CL; break;
16808 case X86::BX: DestReg = X86::BL; break;
16811 Res.first = DestReg;
16812 Res.second = &X86::GR8RegClass;
16814 } else if (VT == MVT::i32) {
16815 unsigned DestReg = 0;
16816 switch (Res.first) {
16818 case X86::AX: DestReg = X86::EAX; break;
16819 case X86::DX: DestReg = X86::EDX; break;
16820 case X86::CX: DestReg = X86::ECX; break;
16821 case X86::BX: DestReg = X86::EBX; break;
16822 case X86::SI: DestReg = X86::ESI; break;
16823 case X86::DI: DestReg = X86::EDI; break;
16824 case X86::BP: DestReg = X86::EBP; break;
16825 case X86::SP: DestReg = X86::ESP; break;
16828 Res.first = DestReg;
16829 Res.second = &X86::GR32RegClass;
16831 } else if (VT == MVT::i64) {
16832 unsigned DestReg = 0;
16833 switch (Res.first) {
16835 case X86::AX: DestReg = X86::RAX; break;
16836 case X86::DX: DestReg = X86::RDX; break;
16837 case X86::CX: DestReg = X86::RCX; break;
16838 case X86::BX: DestReg = X86::RBX; break;
16839 case X86::SI: DestReg = X86::RSI; break;
16840 case X86::DI: DestReg = X86::RDI; break;
16841 case X86::BP: DestReg = X86::RBP; break;
16842 case X86::SP: DestReg = X86::RSP; break;
16845 Res.first = DestReg;
16846 Res.second = &X86::GR64RegClass;
16849 } else if (Res.second == &X86::FR32RegClass ||
16850 Res.second == &X86::FR64RegClass ||
16851 Res.second == &X86::VR128RegClass) {
16852 // Handle references to XMM physical registers that got mapped into the
16853 // wrong class. This can happen with constraints like {xmm0} where the
16854 // target independent register mapper will just pick the first match it can
16855 // find, ignoring the required type.
16857 if (VT == MVT::f32 || VT == MVT::i32)
16858 Res.second = &X86::FR32RegClass;
16859 else if (VT == MVT::f64 || VT == MVT::i64)
16860 Res.second = &X86::FR64RegClass;
16861 else if (X86::VR128RegClass.hasType(VT))
16862 Res.second = &X86::VR128RegClass;
16863 else if (X86::VR256RegClass.hasType(VT))
16864 Res.second = &X86::VR256RegClass;