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"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.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/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VariadicFunction.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
56 using namespace dwarf;
58 STATISTIC(NumTailCalls, "Number of tail calls");
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64 static SDValue Insert128BitVector(SDValue Result,
70 static SDValue Extract128BitVector(SDValue Vec,
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference. Idx is an index in the 128 bits we
78 /// want. It need not be aligned to a 128-bit bounday. That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
84 EVT VT = Vec.getValueType();
85 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86 EVT ElVT = VT.getVectorElementType();
87 int Factor = VT.getSizeInBits()/128;
88 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89 VT.getVectorNumElements()/Factor);
91 // Extract from UNDEF is UNDEF.
92 if (Vec.getOpcode() == ISD::UNDEF)
93 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
95 if (isa<ConstantSDNode>(Idx)) {
96 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
98 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
99 // we can match to VEXTRACTF128.
100 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
102 // This is the index of the first element of the 128-bit chunk
104 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
107 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
117 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference. Idx is an index in the 128 bits
120 /// we want. It need not be aligned to a 128-bit bounday. That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
127 if (isa<ConstantSDNode>(Idx)) {
128 EVT VT = Vec.getValueType();
129 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
131 EVT ElVT = VT.getVectorElementType();
132 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133 EVT ResultVT = Result.getValueType();
135 // Insert the relevant 128 bits.
136 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
138 // This is the index of the first element of the 128-bit chunk
140 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
143 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154 bool is64Bit = Subtarget->is64Bit();
156 if (Subtarget->isTargetEnvMacho()) {
158 return new X8664_MachoTargetObjectFile();
159 return new TargetLoweringObjectFileMachO();
162 if (Subtarget->isTargetELF())
163 return new TargetLoweringObjectFileELF();
164 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165 return new TargetLoweringObjectFileCOFF();
166 llvm_unreachable("unknown subtarget type");
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170 : TargetLowering(TM, createTLOF(TM)) {
171 Subtarget = &TM.getSubtarget<X86Subtarget>();
172 X86ScalarSSEf64 = Subtarget->hasXMMInt();
173 X86ScalarSSEf32 = Subtarget->hasXMM();
174 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
176 RegInfo = TM.getRegisterInfo();
177 TD = getTargetData();
179 // Set up the TargetLowering object.
180 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
182 // X86 is weird, it always uses i8 for shift amounts and setcc results.
183 setBooleanContents(ZeroOrOneBooleanContent);
184 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
187 // For 64-bit since we have so many registers use the ILP scheduler, for
188 // 32-bit code use the register pressure specific scheduling.
189 if (Subtarget->is64Bit())
190 setSchedulingPreference(Sched::ILP);
192 setSchedulingPreference(Sched::RegPressure);
193 setStackPointerRegisterToSaveRestore(X86StackPtr);
195 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196 // Setup Windows compiler runtime calls.
197 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199 setLibcallName(RTLIB::SREM_I64, "_allrem");
200 setLibcallName(RTLIB::UREM_I64, "_aullrem");
201 setLibcallName(RTLIB::MUL_I64, "_allmul");
202 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
213 if (Subtarget->isTargetDarwin()) {
214 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215 setUseUnderscoreSetJmp(false);
216 setUseUnderscoreLongJmp(false);
217 } else if (Subtarget->isTargetMingw()) {
218 // MS runtime is weird: it exports _setjmp, but longjmp!
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(false);
222 setUseUnderscoreSetJmp(true);
223 setUseUnderscoreLongJmp(true);
226 // Set up the register classes.
227 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230 if (Subtarget->is64Bit())
231 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
233 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
235 // We don't accept any truncstore of integer registers.
236 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
243 // SETOEQ and SETUNE require checking two conditions.
244 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
251 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
253 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
254 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
257 if (Subtarget->is64Bit()) {
258 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
260 } else if (!TM.Options.UseSoftFloat) {
261 // We have an algorithm for SSE2->double, and we turn this into a
262 // 64-bit FILD followed by conditional FADD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
264 // We have an algorithm for SSE2, and we turn this into a 64-bit
265 // FILD for other targets.
266 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
269 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
271 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
272 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
274 if (!TM.Options.UseSoftFloat) {
275 // SSE has no i16 to fp conversion, only i32
276 if (X86ScalarSSEf32) {
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
278 // f32 and f64 cases are Legal, f80 case is not
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
286 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
289 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
290 // are Legal, f80 is custom lowered.
291 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
292 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
294 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
296 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
297 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
299 if (X86ScalarSSEf32) {
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
301 // f32 and f64 cases are Legal, f80 case is not
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
305 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
308 // Handle FP_TO_UINT by promoting the destination to a larger signed
310 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
311 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
314 if (Subtarget->is64Bit()) {
315 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
316 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
317 } else if (!TM.Options.UseSoftFloat) {
318 // Since AVX is a superset of SSE3, only check for SSE here.
319 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320 // Expand FP_TO_UINT into a select.
321 // FIXME: We would like to use a Custom expander here eventually to do
322 // the optimal thing for SSE vs. the default expansion in the legalizer.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
325 // With SSE3 we can use fisttpll to convert to a signed i64; without
326 // SSE, we're stuck with a fistpll.
327 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
330 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331 if (!X86ScalarSSEf64) {
332 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
333 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
334 if (Subtarget->is64Bit()) {
335 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
336 // Without SSE, i64->f64 goes through memory.
337 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
341 // Scalar integer divide and remainder are lowered to use operations that
342 // produce two results, to match the available instructions. This exposes
343 // the two-result form to trivial CSE, which is able to combine x/y and x%y
344 // into a single instruction.
346 // Scalar integer multiply-high is also lowered to use two-result
347 // operations, to match the available instructions. However, plain multiply
348 // (low) operations are left as Legal, as there are single-result
349 // instructions for this in x86. Using the two-result multiply instructions
350 // when both high and low results are needed must be arranged by dagcombine.
351 for (unsigned i = 0, e = 4; i != e; ++i) {
353 setOperationAction(ISD::MULHS, VT, Expand);
354 setOperationAction(ISD::MULHU, VT, Expand);
355 setOperationAction(ISD::SDIV, VT, Expand);
356 setOperationAction(ISD::UDIV, VT, Expand);
357 setOperationAction(ISD::SREM, VT, Expand);
358 setOperationAction(ISD::UREM, VT, Expand);
360 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361 setOperationAction(ISD::ADDC, VT, Custom);
362 setOperationAction(ISD::ADDE, VT, Custom);
363 setOperationAction(ISD::SUBC, VT, Custom);
364 setOperationAction(ISD::SUBE, VT, Custom);
367 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
368 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
369 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
370 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
371 if (Subtarget->is64Bit())
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
376 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f32 , Expand);
378 setOperationAction(ISD::FREM , MVT::f64 , Expand);
379 setOperationAction(ISD::FREM , MVT::f80 , Expand);
380 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
382 if (Subtarget->hasBMI()) {
383 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
384 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i8 , Expand);
385 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
386 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
387 if (Subtarget->is64Bit())
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
390 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
391 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
392 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
393 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i8 , Promote);
394 if (Subtarget->is64Bit())
395 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
398 if (Subtarget->hasLZCNT()) {
399 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
400 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Expand);
401 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
402 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
403 if (Subtarget->is64Bit())
404 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
406 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
407 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
408 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
411 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
412 if (Subtarget->is64Bit()) {
413 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
414 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
418 if (Subtarget->hasPOPCNT()) {
419 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
421 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
422 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
423 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
424 if (Subtarget->is64Bit())
425 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
428 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
429 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
431 // These should be promoted to a larger select which is supported.
432 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
433 // X86 wants to expand cmov itself.
434 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
435 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
436 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
437 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
438 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
439 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
440 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
441 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
442 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
443 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
444 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
445 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
446 if (Subtarget->is64Bit()) {
447 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
450 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
453 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
454 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
455 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
456 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
457 if (Subtarget->is64Bit())
458 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
459 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
460 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
461 if (Subtarget->is64Bit()) {
462 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
463 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
464 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
465 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
466 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
468 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
469 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
470 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
471 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
472 if (Subtarget->is64Bit()) {
473 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
474 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
475 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
478 if (Subtarget->hasXMM())
479 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
481 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
482 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
484 // On X86 and X86-64, atomic operations are lowered to locked instructions.
485 // Locked instructions, in turn, have implicit fence semantics (all memory
486 // operations are flushed before issuing the locked instruction, and they
487 // are not buffered), so we can fold away the common pattern of
488 // fence-atomic-fence.
489 setShouldFoldAtomicFences(true);
491 // Expand certain atomics
492 for (unsigned i = 0, e = 4; i != e; ++i) {
494 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
495 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
496 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
499 if (!Subtarget->is64Bit()) {
500 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
501 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
502 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
503 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
504 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
505 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
506 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
510 if (Subtarget->hasCmpxchg16b()) {
511 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
514 // FIXME - use subtarget debug flags
515 if (!Subtarget->isTargetDarwin() &&
516 !Subtarget->isTargetELF() &&
517 !Subtarget->isTargetCygMing()) {
518 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
521 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
522 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
523 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
524 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
525 if (Subtarget->is64Bit()) {
526 setExceptionPointerRegister(X86::RAX);
527 setExceptionSelectorRegister(X86::RDX);
529 setExceptionPointerRegister(X86::EAX);
530 setExceptionSelectorRegister(X86::EDX);
532 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
533 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
536 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
538 setOperationAction(ISD::TRAP, MVT::Other, Legal);
540 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541 setOperationAction(ISD::VASTART , MVT::Other, Custom);
542 setOperationAction(ISD::VAEND , MVT::Other, Expand);
543 if (Subtarget->is64Bit()) {
544 setOperationAction(ISD::VAARG , MVT::Other, Custom);
545 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
547 setOperationAction(ISD::VAARG , MVT::Other, Expand);
548 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
551 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
552 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
554 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
555 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
556 MVT::i64 : MVT::i32, Custom);
557 else if (TM.Options.EnableSegmentedStacks)
558 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
559 MVT::i64 : MVT::i32, Custom);
561 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
562 MVT::i64 : MVT::i32, Expand);
564 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
565 // f32 and f64 use SSE.
566 // Set up the FP register classes.
567 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
568 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
570 // Use ANDPD to simulate FABS.
571 setOperationAction(ISD::FABS , MVT::f64, Custom);
572 setOperationAction(ISD::FABS , MVT::f32, Custom);
574 // Use XORP to simulate FNEG.
575 setOperationAction(ISD::FNEG , MVT::f64, Custom);
576 setOperationAction(ISD::FNEG , MVT::f32, Custom);
578 // Use ANDPD and ORPD to simulate FCOPYSIGN.
579 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
580 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
582 // Lower this to FGETSIGNx86 plus an AND.
583 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
584 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
586 // We don't support sin/cos/fmod
587 setOperationAction(ISD::FSIN , MVT::f64, Expand);
588 setOperationAction(ISD::FCOS , MVT::f64, Expand);
589 setOperationAction(ISD::FSIN , MVT::f32, Expand);
590 setOperationAction(ISD::FCOS , MVT::f32, Expand);
592 // Expand FP immediates into loads from the stack, except for the special
594 addLegalFPImmediate(APFloat(+0.0)); // xorpd
595 addLegalFPImmediate(APFloat(+0.0f)); // xorps
596 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
597 // Use SSE for f32, x87 for f64.
598 // Set up the FP register classes.
599 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
600 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
602 // Use ANDPS to simulate FABS.
603 setOperationAction(ISD::FABS , MVT::f32, Custom);
605 // Use XORP to simulate FNEG.
606 setOperationAction(ISD::FNEG , MVT::f32, Custom);
608 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
610 // Use ANDPS and ORPS to simulate FCOPYSIGN.
611 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
612 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
614 // We don't support sin/cos/fmod
615 setOperationAction(ISD::FSIN , MVT::f32, Expand);
616 setOperationAction(ISD::FCOS , MVT::f32, Expand);
618 // Special cases we handle for FP constants.
619 addLegalFPImmediate(APFloat(+0.0f)); // xorps
620 addLegalFPImmediate(APFloat(+0.0)); // FLD0
621 addLegalFPImmediate(APFloat(+1.0)); // FLD1
622 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
623 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
625 if (!TM.Options.UnsafeFPMath) {
626 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
627 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
629 } else if (!TM.Options.UseSoftFloat) {
630 // f32 and f64 in x87.
631 // Set up the FP register classes.
632 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
633 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
635 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
636 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
637 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
638 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
640 if (!TM.Options.UnsafeFPMath) {
641 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
642 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
644 addLegalFPImmediate(APFloat(+0.0)); // FLD0
645 addLegalFPImmediate(APFloat(+1.0)); // FLD1
646 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
647 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
648 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
649 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
650 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
651 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
654 // We don't support FMA.
655 setOperationAction(ISD::FMA, MVT::f64, Expand);
656 setOperationAction(ISD::FMA, MVT::f32, Expand);
658 // Long double always uses X87.
659 if (!TM.Options.UseSoftFloat) {
660 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
661 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
662 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
664 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
665 addLegalFPImmediate(TmpFlt); // FLD0
667 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
670 APFloat TmpFlt2(+1.0);
671 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
673 addLegalFPImmediate(TmpFlt2); // FLD1
674 TmpFlt2.changeSign();
675 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
678 if (!TM.Options.UnsafeFPMath) {
679 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
680 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
683 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
684 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
685 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
686 setOperationAction(ISD::FRINT, MVT::f80, Expand);
687 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
688 setOperationAction(ISD::FMA, MVT::f80, Expand);
691 // Always use a library call for pow.
692 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
693 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
694 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
696 setOperationAction(ISD::FLOG, MVT::f80, Expand);
697 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
698 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
699 setOperationAction(ISD::FEXP, MVT::f80, Expand);
700 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
702 // First set operation action for all vector types to either promote
703 // (for widening) or expand (for scalarization). Then we will selectively
704 // turn on ones that can be effectively codegen'd.
705 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
706 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
707 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
722 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
724 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
725 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
759 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
764 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
765 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
766 setTruncStoreAction((MVT::SimpleValueType)VT,
767 (MVT::SimpleValueType)InnerVT, Expand);
768 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
769 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
770 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
773 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
774 // with -msoft-float, disable use of MMX as well.
775 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
776 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
777 // No operations on x86mmx supported, everything uses intrinsics.
780 // MMX-sized vectors (other than x86mmx) are expected to be expanded
781 // into smaller operations.
782 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
783 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
784 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
785 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
786 setOperationAction(ISD::AND, MVT::v8i8, Expand);
787 setOperationAction(ISD::AND, MVT::v4i16, Expand);
788 setOperationAction(ISD::AND, MVT::v2i32, Expand);
789 setOperationAction(ISD::AND, MVT::v1i64, Expand);
790 setOperationAction(ISD::OR, MVT::v8i8, Expand);
791 setOperationAction(ISD::OR, MVT::v4i16, Expand);
792 setOperationAction(ISD::OR, MVT::v2i32, Expand);
793 setOperationAction(ISD::OR, MVT::v1i64, Expand);
794 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
795 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
796 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
797 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
798 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
799 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
800 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
801 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
802 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
803 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
804 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
805 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
806 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
807 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
808 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
809 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
810 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
812 if (!TM.Options.UseSoftFloat && Subtarget->hasXMM()) {
813 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
815 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
816 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
817 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
818 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
819 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
820 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
821 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
822 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
823 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
824 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
825 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
826 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
829 if (!TM.Options.UseSoftFloat && Subtarget->hasXMMInt()) {
830 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
832 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
833 // registers cannot be used even for integer operations.
834 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
835 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
836 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
837 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
839 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
840 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
841 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
842 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
843 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
844 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
845 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
846 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
847 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
848 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
849 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
850 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
851 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
852 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
853 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
854 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
856 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
857 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
858 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
859 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
861 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
862 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
863 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
864 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
865 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
867 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
868 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
869 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
870 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
871 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
873 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
874 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
875 EVT VT = (MVT::SimpleValueType)i;
876 // Do not attempt to custom lower non-power-of-2 vectors
877 if (!isPowerOf2_32(VT.getVectorNumElements()))
879 // Do not attempt to custom lower non-128-bit vectors
880 if (!VT.is128BitVector())
882 setOperationAction(ISD::BUILD_VECTOR,
883 VT.getSimpleVT().SimpleTy, Custom);
884 setOperationAction(ISD::VECTOR_SHUFFLE,
885 VT.getSimpleVT().SimpleTy, Custom);
886 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
887 VT.getSimpleVT().SimpleTy, Custom);
890 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
891 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
892 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
893 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
894 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
895 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
897 if (Subtarget->is64Bit()) {
898 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
899 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
902 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
903 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
904 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
907 // Do not attempt to promote non-128-bit vectors
908 if (!VT.is128BitVector())
911 setOperationAction(ISD::AND, SVT, Promote);
912 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
913 setOperationAction(ISD::OR, SVT, Promote);
914 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
915 setOperationAction(ISD::XOR, SVT, Promote);
916 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
917 setOperationAction(ISD::LOAD, SVT, Promote);
918 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
919 setOperationAction(ISD::SELECT, SVT, Promote);
920 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
923 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
925 // Custom lower v2i64 and v2f64 selects.
926 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
927 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
928 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
929 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
931 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
932 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
935 if (Subtarget->hasSSE41orAVX()) {
936 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
937 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
938 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
939 setOperationAction(ISD::FRINT, MVT::f32, Legal);
940 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
941 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
942 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
943 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
944 setOperationAction(ISD::FRINT, MVT::f64, Legal);
945 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
947 // FIXME: Do we need to handle scalar-to-vector here?
948 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
950 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
951 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
952 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
953 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
954 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
956 // i8 and i16 vectors are custom , because the source register and source
957 // source memory operand types are not the same width. f32 vectors are
958 // custom since the immediate controlling the insert encodes additional
960 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
961 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
965 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
966 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
967 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
968 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
970 // FIXME: these should be Legal but thats only for the case where
971 // the index is constant. For now custom expand to deal with that.
972 if (Subtarget->is64Bit()) {
973 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
974 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
978 if (Subtarget->hasXMMInt()) {
979 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
980 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
982 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
983 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
985 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
986 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
988 if (Subtarget->hasAVX2()) {
989 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
990 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
992 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
993 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
995 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
997 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
998 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1000 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1001 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1003 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1007 if (Subtarget->hasSSE42orAVX())
1008 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1010 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1011 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
1012 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
1013 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
1014 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
1015 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
1016 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
1018 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1019 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1020 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1022 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1023 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1024 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1025 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1026 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1027 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1029 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1030 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1031 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1032 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1033 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1034 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1036 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1037 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1038 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1040 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1041 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1042 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1043 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1044 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1045 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1047 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1048 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1050 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1051 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1053 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1054 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1056 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1057 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1058 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1059 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1061 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1062 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1063 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1065 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1070 if (Subtarget->hasAVX2()) {
1071 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1072 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1073 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1074 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1076 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1077 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1078 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1079 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1081 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1082 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1083 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1084 // Don't lower v32i8 because there is no 128-bit byte mul
1086 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1088 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1089 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1091 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1092 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1094 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1096 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1097 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1098 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1099 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1101 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1102 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1103 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1104 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1106 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1107 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1108 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1109 // Don't lower v32i8 because there is no 128-bit byte mul
1111 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1112 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1114 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1115 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1117 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1120 // Custom lower several nodes for 256-bit types.
1121 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1122 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1123 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1126 // Extract subvector is special because the value type
1127 // (result) is 128-bit but the source is 256-bit wide.
1128 if (VT.is128BitVector())
1129 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1131 // Do not attempt to custom lower other non-256-bit vectors
1132 if (!VT.is256BitVector())
1135 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1136 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1137 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1138 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1139 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1140 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1143 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1144 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1145 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1148 // Do not attempt to promote non-256-bit vectors
1149 if (!VT.is256BitVector())
1152 setOperationAction(ISD::AND, SVT, Promote);
1153 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1154 setOperationAction(ISD::OR, SVT, Promote);
1155 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1156 setOperationAction(ISD::XOR, SVT, Promote);
1157 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1158 setOperationAction(ISD::LOAD, SVT, Promote);
1159 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1160 setOperationAction(ISD::SELECT, SVT, Promote);
1161 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1165 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1166 // of this type with custom code.
1167 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1168 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1169 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1173 // We want to custom lower some of our intrinsics.
1174 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1177 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1178 // handle type legalization for these operations here.
1180 // FIXME: We really should do custom legalization for addition and
1181 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1182 // than generic legalization for 64-bit multiplication-with-overflow, though.
1183 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1184 // Add/Sub/Mul with overflow operations are custom lowered.
1186 setOperationAction(ISD::SADDO, VT, Custom);
1187 setOperationAction(ISD::UADDO, VT, Custom);
1188 setOperationAction(ISD::SSUBO, VT, Custom);
1189 setOperationAction(ISD::USUBO, VT, Custom);
1190 setOperationAction(ISD::SMULO, VT, Custom);
1191 setOperationAction(ISD::UMULO, VT, Custom);
1194 // There are no 8-bit 3-address imul/mul instructions
1195 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1196 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1198 if (!Subtarget->is64Bit()) {
1199 // These libcalls are not available in 32-bit.
1200 setLibcallName(RTLIB::SHL_I128, 0);
1201 setLibcallName(RTLIB::SRL_I128, 0);
1202 setLibcallName(RTLIB::SRA_I128, 0);
1205 // We have target-specific dag combine patterns for the following nodes:
1206 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1207 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1208 setTargetDAGCombine(ISD::VSELECT);
1209 setTargetDAGCombine(ISD::SELECT);
1210 setTargetDAGCombine(ISD::SHL);
1211 setTargetDAGCombine(ISD::SRA);
1212 setTargetDAGCombine(ISD::SRL);
1213 setTargetDAGCombine(ISD::OR);
1214 setTargetDAGCombine(ISD::AND);
1215 setTargetDAGCombine(ISD::ADD);
1216 setTargetDAGCombine(ISD::FADD);
1217 setTargetDAGCombine(ISD::FSUB);
1218 setTargetDAGCombine(ISD::SUB);
1219 setTargetDAGCombine(ISD::LOAD);
1220 setTargetDAGCombine(ISD::STORE);
1221 setTargetDAGCombine(ISD::ZERO_EXTEND);
1222 setTargetDAGCombine(ISD::SINT_TO_FP);
1223 if (Subtarget->is64Bit())
1224 setTargetDAGCombine(ISD::MUL);
1225 if (Subtarget->hasBMI())
1226 setTargetDAGCombine(ISD::XOR);
1228 computeRegisterProperties();
1230 // On Darwin, -Os means optimize for size without hurting performance,
1231 // do not reduce the limit.
1232 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1233 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1234 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1235 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1236 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1237 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1238 setPrefLoopAlignment(4); // 2^4 bytes.
1239 benefitFromCodePlacementOpt = true;
1241 setPrefFunctionAlignment(4); // 2^4 bytes.
1245 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1246 if (!VT.isVector()) return MVT::i8;
1247 return VT.changeVectorElementTypeToInteger();
1251 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1252 /// the desired ByVal argument alignment.
1253 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1256 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1257 if (VTy->getBitWidth() == 128)
1259 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1260 unsigned EltAlign = 0;
1261 getMaxByValAlign(ATy->getElementType(), EltAlign);
1262 if (EltAlign > MaxAlign)
1263 MaxAlign = EltAlign;
1264 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1265 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1266 unsigned EltAlign = 0;
1267 getMaxByValAlign(STy->getElementType(i), EltAlign);
1268 if (EltAlign > MaxAlign)
1269 MaxAlign = EltAlign;
1277 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1278 /// function arguments in the caller parameter area. For X86, aggregates
1279 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1280 /// are at 4-byte boundaries.
1281 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1282 if (Subtarget->is64Bit()) {
1283 // Max of 8 and alignment of type.
1284 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1291 if (Subtarget->hasXMM())
1292 getMaxByValAlign(Ty, Align);
1296 /// getOptimalMemOpType - Returns the target specific optimal type for load
1297 /// and store operations as a result of memset, memcpy, and memmove
1298 /// lowering. If DstAlign is zero that means it's safe to destination
1299 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1300 /// means there isn't a need to check it against alignment requirement,
1301 /// probably because the source does not need to be loaded. If
1302 /// 'IsZeroVal' is true, that means it's safe to return a
1303 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1304 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1305 /// constant so it does not need to be loaded.
1306 /// It returns EVT::Other if the type should be determined using generic
1307 /// target-independent logic.
1309 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1310 unsigned DstAlign, unsigned SrcAlign,
1313 MachineFunction &MF) const {
1314 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1315 // linux. This is because the stack realignment code can't handle certain
1316 // cases like PR2962. This should be removed when PR2962 is fixed.
1317 const Function *F = MF.getFunction();
1319 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1321 (Subtarget->isUnalignedMemAccessFast() ||
1322 ((DstAlign == 0 || DstAlign >= 16) &&
1323 (SrcAlign == 0 || SrcAlign >= 16))) &&
1324 Subtarget->getStackAlignment() >= 16) {
1325 if (Subtarget->hasAVX() &&
1326 Subtarget->getStackAlignment() >= 32)
1328 if (Subtarget->hasXMMInt())
1330 if (Subtarget->hasXMM())
1332 } else if (!MemcpyStrSrc && Size >= 8 &&
1333 !Subtarget->is64Bit() &&
1334 Subtarget->getStackAlignment() >= 8 &&
1335 Subtarget->hasXMMInt()) {
1336 // Do not use f64 to lower memcpy if source is string constant. It's
1337 // better to use i32 to avoid the loads.
1341 if (Subtarget->is64Bit() && Size >= 8)
1346 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1347 /// current function. The returned value is a member of the
1348 /// MachineJumpTableInfo::JTEntryKind enum.
1349 unsigned X86TargetLowering::getJumpTableEncoding() const {
1350 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1352 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1353 Subtarget->isPICStyleGOT())
1354 return MachineJumpTableInfo::EK_Custom32;
1356 // Otherwise, use the normal jump table encoding heuristics.
1357 return TargetLowering::getJumpTableEncoding();
1361 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1362 const MachineBasicBlock *MBB,
1363 unsigned uid,MCContext &Ctx) const{
1364 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1365 Subtarget->isPICStyleGOT());
1366 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1368 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1369 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1372 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1374 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1375 SelectionDAG &DAG) const {
1376 if (!Subtarget->is64Bit())
1377 // This doesn't have DebugLoc associated with it, but is not really the
1378 // same as a Register.
1379 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1383 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1384 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1386 const MCExpr *X86TargetLowering::
1387 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1388 MCContext &Ctx) const {
1389 // X86-64 uses RIP relative addressing based on the jump table label.
1390 if (Subtarget->isPICStyleRIPRel())
1391 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1393 // Otherwise, the reference is relative to the PIC base.
1394 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1397 // FIXME: Why this routine is here? Move to RegInfo!
1398 std::pair<const TargetRegisterClass*, uint8_t>
1399 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1400 const TargetRegisterClass *RRC = 0;
1402 switch (VT.getSimpleVT().SimpleTy) {
1404 return TargetLowering::findRepresentativeClass(VT);
1405 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1406 RRC = (Subtarget->is64Bit()
1407 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1410 RRC = X86::VR64RegisterClass;
1412 case MVT::f32: case MVT::f64:
1413 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1414 case MVT::v4f32: case MVT::v2f64:
1415 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1417 RRC = X86::VR128RegisterClass;
1420 return std::make_pair(RRC, Cost);
1423 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1424 unsigned &Offset) const {
1425 if (!Subtarget->isTargetLinux())
1428 if (Subtarget->is64Bit()) {
1429 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1431 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1444 //===----------------------------------------------------------------------===//
1445 // Return Value Calling Convention Implementation
1446 //===----------------------------------------------------------------------===//
1448 #include "X86GenCallingConv.inc"
1451 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1452 MachineFunction &MF, bool isVarArg,
1453 const SmallVectorImpl<ISD::OutputArg> &Outs,
1454 LLVMContext &Context) const {
1455 SmallVector<CCValAssign, 16> RVLocs;
1456 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1458 return CCInfo.CheckReturn(Outs, RetCC_X86);
1462 X86TargetLowering::LowerReturn(SDValue Chain,
1463 CallingConv::ID CallConv, bool isVarArg,
1464 const SmallVectorImpl<ISD::OutputArg> &Outs,
1465 const SmallVectorImpl<SDValue> &OutVals,
1466 DebugLoc dl, SelectionDAG &DAG) const {
1467 MachineFunction &MF = DAG.getMachineFunction();
1468 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1470 SmallVector<CCValAssign, 16> RVLocs;
1471 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1472 RVLocs, *DAG.getContext());
1473 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1475 // Add the regs to the liveout set for the function.
1476 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1477 for (unsigned i = 0; i != RVLocs.size(); ++i)
1478 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1479 MRI.addLiveOut(RVLocs[i].getLocReg());
1483 SmallVector<SDValue, 6> RetOps;
1484 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1485 // Operand #1 = Bytes To Pop
1486 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1489 // Copy the result values into the output registers.
1490 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1491 CCValAssign &VA = RVLocs[i];
1492 assert(VA.isRegLoc() && "Can only return in registers!");
1493 SDValue ValToCopy = OutVals[i];
1494 EVT ValVT = ValToCopy.getValueType();
1496 // If this is x86-64, and we disabled SSE, we can't return FP values,
1497 // or SSE or MMX vectors.
1498 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1499 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1500 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1501 report_fatal_error("SSE register return with SSE disabled");
1503 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1504 // llvm-gcc has never done it right and no one has noticed, so this
1505 // should be OK for now.
1506 if (ValVT == MVT::f64 &&
1507 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1508 report_fatal_error("SSE2 register return with SSE2 disabled");
1510 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1511 // the RET instruction and handled by the FP Stackifier.
1512 if (VA.getLocReg() == X86::ST0 ||
1513 VA.getLocReg() == X86::ST1) {
1514 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1515 // change the value to the FP stack register class.
1516 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1517 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1518 RetOps.push_back(ValToCopy);
1519 // Don't emit a copytoreg.
1523 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1524 // which is returned in RAX / RDX.
1525 if (Subtarget->is64Bit()) {
1526 if (ValVT == MVT::x86mmx) {
1527 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1528 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1529 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1531 // If we don't have SSE2 available, convert to v4f32 so the generated
1532 // register is legal.
1533 if (!Subtarget->hasXMMInt())
1534 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1539 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1540 Flag = Chain.getValue(1);
1543 // The x86-64 ABI for returning structs by value requires that we copy
1544 // the sret argument into %rax for the return. We saved the argument into
1545 // a virtual register in the entry block, so now we copy the value out
1547 if (Subtarget->is64Bit() &&
1548 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1549 MachineFunction &MF = DAG.getMachineFunction();
1550 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1551 unsigned Reg = FuncInfo->getSRetReturnReg();
1553 "SRetReturnReg should have been set in LowerFormalArguments().");
1554 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1556 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1557 Flag = Chain.getValue(1);
1559 // RAX now acts like a return value.
1560 MRI.addLiveOut(X86::RAX);
1563 RetOps[0] = Chain; // Update chain.
1565 // Add the flag if we have it.
1567 RetOps.push_back(Flag);
1569 return DAG.getNode(X86ISD::RET_FLAG, dl,
1570 MVT::Other, &RetOps[0], RetOps.size());
1573 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1574 if (N->getNumValues() != 1)
1576 if (!N->hasNUsesOfValue(1, 0))
1579 SDNode *Copy = *N->use_begin();
1580 if (Copy->getOpcode() != ISD::CopyToReg &&
1581 Copy->getOpcode() != ISD::FP_EXTEND)
1584 bool HasRet = false;
1585 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1587 if (UI->getOpcode() != X86ISD::RET_FLAG)
1596 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1597 ISD::NodeType ExtendKind) const {
1599 // TODO: Is this also valid on 32-bit?
1600 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1601 ReturnMVT = MVT::i8;
1603 ReturnMVT = MVT::i32;
1605 EVT MinVT = getRegisterType(Context, ReturnMVT);
1606 return VT.bitsLT(MinVT) ? MinVT : VT;
1609 /// LowerCallResult - Lower the result values of a call into the
1610 /// appropriate copies out of appropriate physical registers.
1613 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1614 CallingConv::ID CallConv, bool isVarArg,
1615 const SmallVectorImpl<ISD::InputArg> &Ins,
1616 DebugLoc dl, SelectionDAG &DAG,
1617 SmallVectorImpl<SDValue> &InVals) const {
1619 // Assign locations to each value returned by this call.
1620 SmallVector<CCValAssign, 16> RVLocs;
1621 bool Is64Bit = Subtarget->is64Bit();
1622 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1623 getTargetMachine(), RVLocs, *DAG.getContext());
1624 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1626 // Copy all of the result registers out of their specified physreg.
1627 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1628 CCValAssign &VA = RVLocs[i];
1629 EVT CopyVT = VA.getValVT();
1631 // If this is x86-64, and we disabled SSE, we can't return FP values
1632 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1633 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1634 report_fatal_error("SSE register return with SSE disabled");
1639 // If this is a call to a function that returns an fp value on the floating
1640 // point stack, we must guarantee the the value is popped from the stack, so
1641 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1642 // if the return value is not used. We use the FpPOP_RETVAL instruction
1644 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1645 // If we prefer to use the value in xmm registers, copy it out as f80 and
1646 // use a truncate to move it from fp stack reg to xmm reg.
1647 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1648 SDValue Ops[] = { Chain, InFlag };
1649 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1650 MVT::Other, MVT::Glue, Ops, 2), 1);
1651 Val = Chain.getValue(0);
1653 // Round the f80 to the right size, which also moves it to the appropriate
1655 if (CopyVT != VA.getValVT())
1656 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1657 // This truncation won't change the value.
1658 DAG.getIntPtrConstant(1));
1660 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1661 CopyVT, InFlag).getValue(1);
1662 Val = Chain.getValue(0);
1664 InFlag = Chain.getValue(2);
1665 InVals.push_back(Val);
1672 //===----------------------------------------------------------------------===//
1673 // C & StdCall & Fast Calling Convention implementation
1674 //===----------------------------------------------------------------------===//
1675 // StdCall calling convention seems to be standard for many Windows' API
1676 // routines and around. It differs from C calling convention just a little:
1677 // callee should clean up the stack, not caller. Symbols should be also
1678 // decorated in some fancy way :) It doesn't support any vector arguments.
1679 // For info on fast calling convention see Fast Calling Convention (tail call)
1680 // implementation LowerX86_32FastCCCallTo.
1682 /// CallIsStructReturn - Determines whether a call uses struct return
1684 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1688 return Outs[0].Flags.isSRet();
1691 /// ArgsAreStructReturn - Determines whether a function uses struct
1692 /// return semantics.
1694 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1698 return Ins[0].Flags.isSRet();
1701 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1702 /// by "Src" to address "Dst" with size and alignment information specified by
1703 /// the specific parameter attribute. The copy will be passed as a byval
1704 /// function parameter.
1706 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1707 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1709 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1711 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1712 /*isVolatile*/false, /*AlwaysInline=*/true,
1713 MachinePointerInfo(), MachinePointerInfo());
1716 /// IsTailCallConvention - Return true if the calling convention is one that
1717 /// supports tail call optimization.
1718 static bool IsTailCallConvention(CallingConv::ID CC) {
1719 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1722 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1723 if (!CI->isTailCall())
1727 CallingConv::ID CalleeCC = CS.getCallingConv();
1728 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1734 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1735 /// a tailcall target by changing its ABI.
1736 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1737 bool GuaranteedTailCallOpt) {
1738 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1742 X86TargetLowering::LowerMemArgument(SDValue Chain,
1743 CallingConv::ID CallConv,
1744 const SmallVectorImpl<ISD::InputArg> &Ins,
1745 DebugLoc dl, SelectionDAG &DAG,
1746 const CCValAssign &VA,
1747 MachineFrameInfo *MFI,
1749 // Create the nodes corresponding to a load from this parameter slot.
1750 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1751 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1752 getTargetMachine().Options.GuaranteedTailCallOpt);
1753 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1756 // If value is passed by pointer we have address passed instead of the value
1758 if (VA.getLocInfo() == CCValAssign::Indirect)
1759 ValVT = VA.getLocVT();
1761 ValVT = VA.getValVT();
1763 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1764 // changed with more analysis.
1765 // In case of tail call optimization mark all arguments mutable. Since they
1766 // could be overwritten by lowering of arguments in case of a tail call.
1767 if (Flags.isByVal()) {
1768 unsigned Bytes = Flags.getByValSize();
1769 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1770 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1771 return DAG.getFrameIndex(FI, getPointerTy());
1773 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1774 VA.getLocMemOffset(), isImmutable);
1775 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1776 return DAG.getLoad(ValVT, dl, Chain, FIN,
1777 MachinePointerInfo::getFixedStack(FI),
1778 false, false, false, 0);
1783 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1784 CallingConv::ID CallConv,
1786 const SmallVectorImpl<ISD::InputArg> &Ins,
1789 SmallVectorImpl<SDValue> &InVals)
1791 MachineFunction &MF = DAG.getMachineFunction();
1792 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1794 const Function* Fn = MF.getFunction();
1795 if (Fn->hasExternalLinkage() &&
1796 Subtarget->isTargetCygMing() &&
1797 Fn->getName() == "main")
1798 FuncInfo->setForceFramePointer(true);
1800 MachineFrameInfo *MFI = MF.getFrameInfo();
1801 bool Is64Bit = Subtarget->is64Bit();
1802 bool IsWin64 = Subtarget->isTargetWin64();
1804 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1805 "Var args not supported with calling convention fastcc or ghc");
1807 // Assign locations to all of the incoming arguments.
1808 SmallVector<CCValAssign, 16> ArgLocs;
1809 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1810 ArgLocs, *DAG.getContext());
1812 // Allocate shadow area for Win64
1814 CCInfo.AllocateStack(32, 8);
1817 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1819 unsigned LastVal = ~0U;
1821 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1822 CCValAssign &VA = ArgLocs[i];
1823 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1825 assert(VA.getValNo() != LastVal &&
1826 "Don't support value assigned to multiple locs yet");
1828 LastVal = VA.getValNo();
1830 if (VA.isRegLoc()) {
1831 EVT RegVT = VA.getLocVT();
1832 TargetRegisterClass *RC = NULL;
1833 if (RegVT == MVT::i32)
1834 RC = X86::GR32RegisterClass;
1835 else if (Is64Bit && RegVT == MVT::i64)
1836 RC = X86::GR64RegisterClass;
1837 else if (RegVT == MVT::f32)
1838 RC = X86::FR32RegisterClass;
1839 else if (RegVT == MVT::f64)
1840 RC = X86::FR64RegisterClass;
1841 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1842 RC = X86::VR256RegisterClass;
1843 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1844 RC = X86::VR128RegisterClass;
1845 else if (RegVT == MVT::x86mmx)
1846 RC = X86::VR64RegisterClass;
1848 llvm_unreachable("Unknown argument type!");
1850 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1851 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1853 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1854 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1856 if (VA.getLocInfo() == CCValAssign::SExt)
1857 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1858 DAG.getValueType(VA.getValVT()));
1859 else if (VA.getLocInfo() == CCValAssign::ZExt)
1860 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1861 DAG.getValueType(VA.getValVT()));
1862 else if (VA.getLocInfo() == CCValAssign::BCvt)
1863 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1865 if (VA.isExtInLoc()) {
1866 // Handle MMX values passed in XMM regs.
1867 if (RegVT.isVector()) {
1868 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1871 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1874 assert(VA.isMemLoc());
1875 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1878 // If value is passed via pointer - do a load.
1879 if (VA.getLocInfo() == CCValAssign::Indirect)
1880 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1881 MachinePointerInfo(), false, false, false, 0);
1883 InVals.push_back(ArgValue);
1886 // The x86-64 ABI for returning structs by value requires that we copy
1887 // the sret argument into %rax for the return. Save the argument into
1888 // a virtual register so that we can access it from the return points.
1889 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1890 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1891 unsigned Reg = FuncInfo->getSRetReturnReg();
1893 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1894 FuncInfo->setSRetReturnReg(Reg);
1896 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1897 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1900 unsigned StackSize = CCInfo.getNextStackOffset();
1901 // Align stack specially for tail calls.
1902 if (FuncIsMadeTailCallSafe(CallConv,
1903 MF.getTarget().Options.GuaranteedTailCallOpt))
1904 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1906 // If the function takes variable number of arguments, make a frame index for
1907 // the start of the first vararg value... for expansion of llvm.va_start.
1909 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1910 CallConv != CallingConv::X86_ThisCall)) {
1911 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1914 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1916 // FIXME: We should really autogenerate these arrays
1917 static const unsigned GPR64ArgRegsWin64[] = {
1918 X86::RCX, X86::RDX, X86::R8, X86::R9
1920 static const unsigned GPR64ArgRegs64Bit[] = {
1921 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1923 static const unsigned XMMArgRegs64Bit[] = {
1924 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1925 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1927 const unsigned *GPR64ArgRegs;
1928 unsigned NumXMMRegs = 0;
1931 // The XMM registers which might contain var arg parameters are shadowed
1932 // in their paired GPR. So we only need to save the GPR to their home
1934 TotalNumIntRegs = 4;
1935 GPR64ArgRegs = GPR64ArgRegsWin64;
1937 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1938 GPR64ArgRegs = GPR64ArgRegs64Bit;
1940 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1943 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1946 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1947 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1948 "SSE register cannot be used when SSE is disabled!");
1949 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1950 NoImplicitFloatOps) &&
1951 "SSE register cannot be used when SSE is disabled!");
1952 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1953 !Subtarget->hasXMM())
1954 // Kernel mode asks for SSE to be disabled, so don't push them
1956 TotalNumXMMRegs = 0;
1959 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1960 // Get to the caller-allocated home save location. Add 8 to account
1961 // for the return address.
1962 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1963 FuncInfo->setRegSaveFrameIndex(
1964 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1965 // Fixup to set vararg frame on shadow area (4 x i64).
1967 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1969 // For X86-64, if there are vararg parameters that are passed via
1970 // registers, then we must store them to their spots on the stack so
1971 // they may be loaded by deferencing the result of va_next.
1972 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1973 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1974 FuncInfo->setRegSaveFrameIndex(
1975 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1979 // Store the integer parameter registers.
1980 SmallVector<SDValue, 8> MemOps;
1981 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1983 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1984 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1985 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1986 DAG.getIntPtrConstant(Offset));
1987 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1988 X86::GR64RegisterClass);
1989 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1991 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1992 MachinePointerInfo::getFixedStack(
1993 FuncInfo->getRegSaveFrameIndex(), Offset),
1995 MemOps.push_back(Store);
1999 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2000 // Now store the XMM (fp + vector) parameter registers.
2001 SmallVector<SDValue, 11> SaveXMMOps;
2002 SaveXMMOps.push_back(Chain);
2004 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
2005 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2006 SaveXMMOps.push_back(ALVal);
2008 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2009 FuncInfo->getRegSaveFrameIndex()));
2010 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2011 FuncInfo->getVarArgsFPOffset()));
2013 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2014 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2015 X86::VR128RegisterClass);
2016 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2017 SaveXMMOps.push_back(Val);
2019 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2021 &SaveXMMOps[0], SaveXMMOps.size()));
2024 if (!MemOps.empty())
2025 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2026 &MemOps[0], MemOps.size());
2030 // Some CCs need callee pop.
2031 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2032 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2033 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2035 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2036 // If this is an sret function, the return should pop the hidden pointer.
2037 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2038 FuncInfo->setBytesToPopOnReturn(4);
2042 // RegSaveFrameIndex is X86-64 only.
2043 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2044 if (CallConv == CallingConv::X86_FastCall ||
2045 CallConv == CallingConv::X86_ThisCall)
2046 // fastcc functions can't have varargs.
2047 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2050 FuncInfo->setArgumentStackSize(StackSize);
2056 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2057 SDValue StackPtr, SDValue Arg,
2058 DebugLoc dl, SelectionDAG &DAG,
2059 const CCValAssign &VA,
2060 ISD::ArgFlagsTy Flags) const {
2061 unsigned LocMemOffset = VA.getLocMemOffset();
2062 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2063 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2064 if (Flags.isByVal())
2065 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2067 return DAG.getStore(Chain, dl, Arg, PtrOff,
2068 MachinePointerInfo::getStack(LocMemOffset),
2072 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2073 /// optimization is performed and it is required.
2075 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2076 SDValue &OutRetAddr, SDValue Chain,
2077 bool IsTailCall, bool Is64Bit,
2078 int FPDiff, DebugLoc dl) const {
2079 // Adjust the Return address stack slot.
2080 EVT VT = getPointerTy();
2081 OutRetAddr = getReturnAddressFrameIndex(DAG);
2083 // Load the "old" Return address.
2084 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2085 false, false, false, 0);
2086 return SDValue(OutRetAddr.getNode(), 1);
2089 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2090 /// optimization is performed and it is required (FPDiff!=0).
2092 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2093 SDValue Chain, SDValue RetAddrFrIdx,
2094 bool Is64Bit, int FPDiff, DebugLoc dl) {
2095 // Store the return address to the appropriate stack slot.
2096 if (!FPDiff) return Chain;
2097 // Calculate the new stack slot for the return address.
2098 int SlotSize = Is64Bit ? 8 : 4;
2099 int NewReturnAddrFI =
2100 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2101 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2102 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2103 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2104 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2110 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2111 CallingConv::ID CallConv, bool isVarArg,
2113 const SmallVectorImpl<ISD::OutputArg> &Outs,
2114 const SmallVectorImpl<SDValue> &OutVals,
2115 const SmallVectorImpl<ISD::InputArg> &Ins,
2116 DebugLoc dl, SelectionDAG &DAG,
2117 SmallVectorImpl<SDValue> &InVals) const {
2118 MachineFunction &MF = DAG.getMachineFunction();
2119 bool Is64Bit = Subtarget->is64Bit();
2120 bool IsWin64 = Subtarget->isTargetWin64();
2121 bool IsStructRet = CallIsStructReturn(Outs);
2122 bool IsSibcall = false;
2125 // Check if it's really possible to do a tail call.
2126 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2127 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2128 Outs, OutVals, Ins, DAG);
2130 // Sibcalls are automatically detected tailcalls which do not require
2132 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2139 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2140 "Var args not supported with calling convention fastcc or ghc");
2142 // Analyze operands of the call, assigning locations to each operand.
2143 SmallVector<CCValAssign, 16> ArgLocs;
2144 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2145 ArgLocs, *DAG.getContext());
2147 // Allocate shadow area for Win64
2149 CCInfo.AllocateStack(32, 8);
2152 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2154 // Get a count of how many bytes are to be pushed on the stack.
2155 unsigned NumBytes = CCInfo.getNextStackOffset();
2157 // This is a sibcall. The memory operands are available in caller's
2158 // own caller's stack.
2160 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2161 IsTailCallConvention(CallConv))
2162 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2165 if (isTailCall && !IsSibcall) {
2166 // Lower arguments at fp - stackoffset + fpdiff.
2167 unsigned NumBytesCallerPushed =
2168 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2169 FPDiff = NumBytesCallerPushed - NumBytes;
2171 // Set the delta of movement of the returnaddr stackslot.
2172 // But only set if delta is greater than previous delta.
2173 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2174 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2178 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2180 SDValue RetAddrFrIdx;
2181 // Load return address for tail calls.
2182 if (isTailCall && FPDiff)
2183 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2184 Is64Bit, FPDiff, dl);
2186 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2187 SmallVector<SDValue, 8> MemOpChains;
2190 // Walk the register/memloc assignments, inserting copies/loads. In the case
2191 // of tail call optimization arguments are handle later.
2192 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2193 CCValAssign &VA = ArgLocs[i];
2194 EVT RegVT = VA.getLocVT();
2195 SDValue Arg = OutVals[i];
2196 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2197 bool isByVal = Flags.isByVal();
2199 // Promote the value if needed.
2200 switch (VA.getLocInfo()) {
2201 default: llvm_unreachable("Unknown loc info!");
2202 case CCValAssign::Full: break;
2203 case CCValAssign::SExt:
2204 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2206 case CCValAssign::ZExt:
2207 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2209 case CCValAssign::AExt:
2210 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2211 // Special case: passing MMX values in XMM registers.
2212 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2213 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2214 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2216 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2218 case CCValAssign::BCvt:
2219 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2221 case CCValAssign::Indirect: {
2222 // Store the argument.
2223 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2224 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2225 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2226 MachinePointerInfo::getFixedStack(FI),
2233 if (VA.isRegLoc()) {
2234 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2235 if (isVarArg && IsWin64) {
2236 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2237 // shadow reg if callee is a varargs function.
2238 unsigned ShadowReg = 0;
2239 switch (VA.getLocReg()) {
2240 case X86::XMM0: ShadowReg = X86::RCX; break;
2241 case X86::XMM1: ShadowReg = X86::RDX; break;
2242 case X86::XMM2: ShadowReg = X86::R8; break;
2243 case X86::XMM3: ShadowReg = X86::R9; break;
2246 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2248 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2249 assert(VA.isMemLoc());
2250 if (StackPtr.getNode() == 0)
2251 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2252 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2253 dl, DAG, VA, Flags));
2257 if (!MemOpChains.empty())
2258 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2259 &MemOpChains[0], MemOpChains.size());
2261 // Build a sequence of copy-to-reg nodes chained together with token chain
2262 // and flag operands which copy the outgoing args into registers.
2264 // Tail call byval lowering might overwrite argument registers so in case of
2265 // tail call optimization the copies to registers are lowered later.
2267 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2268 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2269 RegsToPass[i].second, InFlag);
2270 InFlag = Chain.getValue(1);
2273 if (Subtarget->isPICStyleGOT()) {
2274 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2277 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2278 DAG.getNode(X86ISD::GlobalBaseReg,
2279 DebugLoc(), getPointerTy()),
2281 InFlag = Chain.getValue(1);
2283 // If we are tail calling and generating PIC/GOT style code load the
2284 // address of the callee into ECX. The value in ecx is used as target of
2285 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2286 // for tail calls on PIC/GOT architectures. Normally we would just put the
2287 // address of GOT into ebx and then call target@PLT. But for tail calls
2288 // ebx would be restored (since ebx is callee saved) before jumping to the
2291 // Note: The actual moving to ECX is done further down.
2292 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2293 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2294 !G->getGlobal()->hasProtectedVisibility())
2295 Callee = LowerGlobalAddress(Callee, DAG);
2296 else if (isa<ExternalSymbolSDNode>(Callee))
2297 Callee = LowerExternalSymbol(Callee, DAG);
2301 if (Is64Bit && isVarArg && !IsWin64) {
2302 // From AMD64 ABI document:
2303 // For calls that may call functions that use varargs or stdargs
2304 // (prototype-less calls or calls to functions containing ellipsis (...) in
2305 // the declaration) %al is used as hidden argument to specify the number
2306 // of SSE registers used. The contents of %al do not need to match exactly
2307 // the number of registers, but must be an ubound on the number of SSE
2308 // registers used and is in the range 0 - 8 inclusive.
2310 // Count the number of XMM registers allocated.
2311 static const unsigned XMMArgRegs[] = {
2312 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2313 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2315 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2316 assert((Subtarget->hasXMM() || !NumXMMRegs)
2317 && "SSE registers cannot be used when SSE is disabled");
2319 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2320 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2321 InFlag = Chain.getValue(1);
2325 // For tail calls lower the arguments to the 'real' stack slot.
2327 // Force all the incoming stack arguments to be loaded from the stack
2328 // before any new outgoing arguments are stored to the stack, because the
2329 // outgoing stack slots may alias the incoming argument stack slots, and
2330 // the alias isn't otherwise explicit. This is slightly more conservative
2331 // than necessary, because it means that each store effectively depends
2332 // on every argument instead of just those arguments it would clobber.
2333 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2335 SmallVector<SDValue, 8> MemOpChains2;
2338 // Do not flag preceding copytoreg stuff together with the following stuff.
2340 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2341 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2342 CCValAssign &VA = ArgLocs[i];
2345 assert(VA.isMemLoc());
2346 SDValue Arg = OutVals[i];
2347 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2348 // Create frame index.
2349 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2350 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2351 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2352 FIN = DAG.getFrameIndex(FI, getPointerTy());
2354 if (Flags.isByVal()) {
2355 // Copy relative to framepointer.
2356 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2357 if (StackPtr.getNode() == 0)
2358 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2360 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2362 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2366 // Store relative to framepointer.
2367 MemOpChains2.push_back(
2368 DAG.getStore(ArgChain, dl, Arg, FIN,
2369 MachinePointerInfo::getFixedStack(FI),
2375 if (!MemOpChains2.empty())
2376 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2377 &MemOpChains2[0], MemOpChains2.size());
2379 // Copy arguments to their registers.
2380 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2381 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2382 RegsToPass[i].second, InFlag);
2383 InFlag = Chain.getValue(1);
2387 // Store the return address to the appropriate stack slot.
2388 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2392 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2393 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2394 // In the 64-bit large code model, we have to make all calls
2395 // through a register, since the call instruction's 32-bit
2396 // pc-relative offset may not be large enough to hold the whole
2398 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2399 // If the callee is a GlobalAddress node (quite common, every direct call
2400 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2403 // We should use extra load for direct calls to dllimported functions in
2405 const GlobalValue *GV = G->getGlobal();
2406 if (!GV->hasDLLImportLinkage()) {
2407 unsigned char OpFlags = 0;
2408 bool ExtraLoad = false;
2409 unsigned WrapperKind = ISD::DELETED_NODE;
2411 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2412 // external symbols most go through the PLT in PIC mode. If the symbol
2413 // has hidden or protected visibility, or if it is static or local, then
2414 // we don't need to use the PLT - we can directly call it.
2415 if (Subtarget->isTargetELF() &&
2416 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2417 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2418 OpFlags = X86II::MO_PLT;
2419 } else if (Subtarget->isPICStyleStubAny() &&
2420 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2421 (!Subtarget->getTargetTriple().isMacOSX() ||
2422 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2423 // PC-relative references to external symbols should go through $stub,
2424 // unless we're building with the leopard linker or later, which
2425 // automatically synthesizes these stubs.
2426 OpFlags = X86II::MO_DARWIN_STUB;
2427 } else if (Subtarget->isPICStyleRIPRel() &&
2428 isa<Function>(GV) &&
2429 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2430 // If the function is marked as non-lazy, generate an indirect call
2431 // which loads from the GOT directly. This avoids runtime overhead
2432 // at the cost of eager binding (and one extra byte of encoding).
2433 OpFlags = X86II::MO_GOTPCREL;
2434 WrapperKind = X86ISD::WrapperRIP;
2438 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2439 G->getOffset(), OpFlags);
2441 // Add a wrapper if needed.
2442 if (WrapperKind != ISD::DELETED_NODE)
2443 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2444 // Add extra indirection if needed.
2446 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2447 MachinePointerInfo::getGOT(),
2448 false, false, false, 0);
2450 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2451 unsigned char OpFlags = 0;
2453 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2454 // external symbols should go through the PLT.
2455 if (Subtarget->isTargetELF() &&
2456 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2457 OpFlags = X86II::MO_PLT;
2458 } else if (Subtarget->isPICStyleStubAny() &&
2459 (!Subtarget->getTargetTriple().isMacOSX() ||
2460 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2461 // PC-relative references to external symbols should go through $stub,
2462 // unless we're building with the leopard linker or later, which
2463 // automatically synthesizes these stubs.
2464 OpFlags = X86II::MO_DARWIN_STUB;
2467 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2471 // Returns a chain & a flag for retval copy to use.
2472 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2473 SmallVector<SDValue, 8> Ops;
2475 if (!IsSibcall && isTailCall) {
2476 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2477 DAG.getIntPtrConstant(0, true), InFlag);
2478 InFlag = Chain.getValue(1);
2481 Ops.push_back(Chain);
2482 Ops.push_back(Callee);
2485 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2487 // Add argument registers to the end of the list so that they are known live
2489 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2490 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2491 RegsToPass[i].second.getValueType()));
2493 // Add an implicit use GOT pointer in EBX.
2494 if (!isTailCall && Subtarget->isPICStyleGOT())
2495 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2497 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2498 if (Is64Bit && isVarArg && !IsWin64)
2499 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2501 if (InFlag.getNode())
2502 Ops.push_back(InFlag);
2506 //// If this is the first return lowered for this function, add the regs
2507 //// to the liveout set for the function.
2508 // This isn't right, although it's probably harmless on x86; liveouts
2509 // should be computed from returns not tail calls. Consider a void
2510 // function making a tail call to a function returning int.
2511 return DAG.getNode(X86ISD::TC_RETURN, dl,
2512 NodeTys, &Ops[0], Ops.size());
2515 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2516 InFlag = Chain.getValue(1);
2518 // Create the CALLSEQ_END node.
2519 unsigned NumBytesForCalleeToPush;
2520 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2521 getTargetMachine().Options.GuaranteedTailCallOpt))
2522 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2523 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2524 // If this is a call to a struct-return function, the callee
2525 // pops the hidden struct pointer, so we have to push it back.
2526 // This is common for Darwin/X86, Linux & Mingw32 targets.
2527 NumBytesForCalleeToPush = 4;
2529 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2531 // Returns a flag for retval copy to use.
2533 Chain = DAG.getCALLSEQ_END(Chain,
2534 DAG.getIntPtrConstant(NumBytes, true),
2535 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2538 InFlag = Chain.getValue(1);
2541 // Handle result values, copying them out of physregs into vregs that we
2543 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2544 Ins, dl, DAG, InVals);
2548 //===----------------------------------------------------------------------===//
2549 // Fast Calling Convention (tail call) implementation
2550 //===----------------------------------------------------------------------===//
2552 // Like std call, callee cleans arguments, convention except that ECX is
2553 // reserved for storing the tail called function address. Only 2 registers are
2554 // free for argument passing (inreg). Tail call optimization is performed
2556 // * tailcallopt is enabled
2557 // * caller/callee are fastcc
2558 // On X86_64 architecture with GOT-style position independent code only local
2559 // (within module) calls are supported at the moment.
2560 // To keep the stack aligned according to platform abi the function
2561 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2562 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2563 // If a tail called function callee has more arguments than the caller the
2564 // caller needs to make sure that there is room to move the RETADDR to. This is
2565 // achieved by reserving an area the size of the argument delta right after the
2566 // original REtADDR, but before the saved framepointer or the spilled registers
2567 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2579 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2580 /// for a 16 byte align requirement.
2582 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2583 SelectionDAG& DAG) const {
2584 MachineFunction &MF = DAG.getMachineFunction();
2585 const TargetMachine &TM = MF.getTarget();
2586 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2587 unsigned StackAlignment = TFI.getStackAlignment();
2588 uint64_t AlignMask = StackAlignment - 1;
2589 int64_t Offset = StackSize;
2590 uint64_t SlotSize = TD->getPointerSize();
2591 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2592 // Number smaller than 12 so just add the difference.
2593 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2595 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2596 Offset = ((~AlignMask) & Offset) + StackAlignment +
2597 (StackAlignment-SlotSize);
2602 /// MatchingStackOffset - Return true if the given stack call argument is
2603 /// already available in the same position (relatively) of the caller's
2604 /// incoming argument stack.
2606 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2607 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2608 const X86InstrInfo *TII) {
2609 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2611 if (Arg.getOpcode() == ISD::CopyFromReg) {
2612 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2613 if (!TargetRegisterInfo::isVirtualRegister(VR))
2615 MachineInstr *Def = MRI->getVRegDef(VR);
2618 if (!Flags.isByVal()) {
2619 if (!TII->isLoadFromStackSlot(Def, FI))
2622 unsigned Opcode = Def->getOpcode();
2623 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2624 Def->getOperand(1).isFI()) {
2625 FI = Def->getOperand(1).getIndex();
2626 Bytes = Flags.getByValSize();
2630 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2631 if (Flags.isByVal())
2632 // ByVal argument is passed in as a pointer but it's now being
2633 // dereferenced. e.g.
2634 // define @foo(%struct.X* %A) {
2635 // tail call @bar(%struct.X* byval %A)
2638 SDValue Ptr = Ld->getBasePtr();
2639 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2642 FI = FINode->getIndex();
2643 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2644 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2645 FI = FINode->getIndex();
2646 Bytes = Flags.getByValSize();
2650 assert(FI != INT_MAX);
2651 if (!MFI->isFixedObjectIndex(FI))
2653 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2656 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2657 /// for tail call optimization. Targets which want to do tail call
2658 /// optimization should implement this function.
2660 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2661 CallingConv::ID CalleeCC,
2663 bool isCalleeStructRet,
2664 bool isCallerStructRet,
2665 const SmallVectorImpl<ISD::OutputArg> &Outs,
2666 const SmallVectorImpl<SDValue> &OutVals,
2667 const SmallVectorImpl<ISD::InputArg> &Ins,
2668 SelectionDAG& DAG) const {
2669 if (!IsTailCallConvention(CalleeCC) &&
2670 CalleeCC != CallingConv::C)
2673 // If -tailcallopt is specified, make fastcc functions tail-callable.
2674 const MachineFunction &MF = DAG.getMachineFunction();
2675 const Function *CallerF = DAG.getMachineFunction().getFunction();
2676 CallingConv::ID CallerCC = CallerF->getCallingConv();
2677 bool CCMatch = CallerCC == CalleeCC;
2679 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2680 if (IsTailCallConvention(CalleeCC) && CCMatch)
2685 // Look for obvious safe cases to perform tail call optimization that do not
2686 // require ABI changes. This is what gcc calls sibcall.
2688 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2689 // emit a special epilogue.
2690 if (RegInfo->needsStackRealignment(MF))
2693 // Also avoid sibcall optimization if either caller or callee uses struct
2694 // return semantics.
2695 if (isCalleeStructRet || isCallerStructRet)
2698 // An stdcall caller is expected to clean up its arguments; the callee
2699 // isn't going to do that.
2700 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2703 // Do not sibcall optimize vararg calls unless all arguments are passed via
2705 if (isVarArg && !Outs.empty()) {
2707 // Optimizing for varargs on Win64 is unlikely to be safe without
2708 // additional testing.
2709 if (Subtarget->isTargetWin64())
2712 SmallVector<CCValAssign, 16> ArgLocs;
2713 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2714 getTargetMachine(), ArgLocs, *DAG.getContext());
2716 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2717 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2718 if (!ArgLocs[i].isRegLoc())
2722 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2723 // stack. Therefore, if it's not used by the call it is not safe to optimize
2724 // this into a sibcall.
2725 bool Unused = false;
2726 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2733 SmallVector<CCValAssign, 16> RVLocs;
2734 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2735 getTargetMachine(), RVLocs, *DAG.getContext());
2736 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2737 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2738 CCValAssign &VA = RVLocs[i];
2739 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2744 // If the calling conventions do not match, then we'd better make sure the
2745 // results are returned in the same way as what the caller expects.
2747 SmallVector<CCValAssign, 16> RVLocs1;
2748 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2749 getTargetMachine(), RVLocs1, *DAG.getContext());
2750 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2752 SmallVector<CCValAssign, 16> RVLocs2;
2753 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2754 getTargetMachine(), RVLocs2, *DAG.getContext());
2755 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2757 if (RVLocs1.size() != RVLocs2.size())
2759 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2760 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2762 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2764 if (RVLocs1[i].isRegLoc()) {
2765 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2768 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2774 // If the callee takes no arguments then go on to check the results of the
2776 if (!Outs.empty()) {
2777 // Check if stack adjustment is needed. For now, do not do this if any
2778 // argument is passed on the stack.
2779 SmallVector<CCValAssign, 16> ArgLocs;
2780 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2781 getTargetMachine(), ArgLocs, *DAG.getContext());
2783 // Allocate shadow area for Win64
2784 if (Subtarget->isTargetWin64()) {
2785 CCInfo.AllocateStack(32, 8);
2788 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2789 if (CCInfo.getNextStackOffset()) {
2790 MachineFunction &MF = DAG.getMachineFunction();
2791 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2794 // Check if the arguments are already laid out in the right way as
2795 // the caller's fixed stack objects.
2796 MachineFrameInfo *MFI = MF.getFrameInfo();
2797 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2798 const X86InstrInfo *TII =
2799 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2800 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2801 CCValAssign &VA = ArgLocs[i];
2802 SDValue Arg = OutVals[i];
2803 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2804 if (VA.getLocInfo() == CCValAssign::Indirect)
2806 if (!VA.isRegLoc()) {
2807 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2814 // If the tailcall address may be in a register, then make sure it's
2815 // possible to register allocate for it. In 32-bit, the call address can
2816 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2817 // callee-saved registers are restored. These happen to be the same
2818 // registers used to pass 'inreg' arguments so watch out for those.
2819 if (!Subtarget->is64Bit() &&
2820 !isa<GlobalAddressSDNode>(Callee) &&
2821 !isa<ExternalSymbolSDNode>(Callee)) {
2822 unsigned NumInRegs = 0;
2823 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2824 CCValAssign &VA = ArgLocs[i];
2827 unsigned Reg = VA.getLocReg();
2830 case X86::EAX: case X86::EDX: case X86::ECX:
2831 if (++NumInRegs == 3)
2843 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2844 return X86::createFastISel(funcInfo);
2848 //===----------------------------------------------------------------------===//
2849 // Other Lowering Hooks
2850 //===----------------------------------------------------------------------===//
2852 static bool MayFoldLoad(SDValue Op) {
2853 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2856 static bool MayFoldIntoStore(SDValue Op) {
2857 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2860 static bool isTargetShuffle(unsigned Opcode) {
2862 default: return false;
2863 case X86ISD::PSHUFD:
2864 case X86ISD::PSHUFHW:
2865 case X86ISD::PSHUFLW:
2866 case X86ISD::SHUFPD:
2867 case X86ISD::PALIGN:
2868 case X86ISD::SHUFPS:
2869 case X86ISD::MOVLHPS:
2870 case X86ISD::MOVLHPD:
2871 case X86ISD::MOVHLPS:
2872 case X86ISD::MOVLPS:
2873 case X86ISD::MOVLPD:
2874 case X86ISD::MOVSHDUP:
2875 case X86ISD::MOVSLDUP:
2876 case X86ISD::MOVDDUP:
2879 case X86ISD::UNPCKL:
2880 case X86ISD::UNPCKH:
2881 case X86ISD::VPERMILP:
2882 case X86ISD::VPERM2X128:
2888 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2889 SDValue V1, SelectionDAG &DAG) {
2891 default: llvm_unreachable("Unknown x86 shuffle node");
2892 case X86ISD::MOVSHDUP:
2893 case X86ISD::MOVSLDUP:
2894 case X86ISD::MOVDDUP:
2895 return DAG.getNode(Opc, dl, VT, V1);
2901 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2902 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2904 default: llvm_unreachable("Unknown x86 shuffle node");
2905 case X86ISD::PSHUFD:
2906 case X86ISD::PSHUFHW:
2907 case X86ISD::PSHUFLW:
2908 case X86ISD::VPERMILP:
2909 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2915 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2916 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2918 default: llvm_unreachable("Unknown x86 shuffle node");
2919 case X86ISD::PALIGN:
2920 case X86ISD::SHUFPD:
2921 case X86ISD::SHUFPS:
2922 case X86ISD::VPERM2X128:
2923 return DAG.getNode(Opc, dl, VT, V1, V2,
2924 DAG.getConstant(TargetMask, MVT::i8));
2929 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2930 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2932 default: llvm_unreachable("Unknown x86 shuffle node");
2933 case X86ISD::MOVLHPS:
2934 case X86ISD::MOVLHPD:
2935 case X86ISD::MOVHLPS:
2936 case X86ISD::MOVLPS:
2937 case X86ISD::MOVLPD:
2940 case X86ISD::UNPCKL:
2941 case X86ISD::UNPCKH:
2942 return DAG.getNode(Opc, dl, VT, V1, V2);
2947 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2948 MachineFunction &MF = DAG.getMachineFunction();
2949 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2950 int ReturnAddrIndex = FuncInfo->getRAIndex();
2952 if (ReturnAddrIndex == 0) {
2953 // Set up a frame object for the return address.
2954 uint64_t SlotSize = TD->getPointerSize();
2955 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2957 FuncInfo->setRAIndex(ReturnAddrIndex);
2960 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2964 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2965 bool hasSymbolicDisplacement) {
2966 // Offset should fit into 32 bit immediate field.
2967 if (!isInt<32>(Offset))
2970 // If we don't have a symbolic displacement - we don't have any extra
2972 if (!hasSymbolicDisplacement)
2975 // FIXME: Some tweaks might be needed for medium code model.
2976 if (M != CodeModel::Small && M != CodeModel::Kernel)
2979 // For small code model we assume that latest object is 16MB before end of 31
2980 // bits boundary. We may also accept pretty large negative constants knowing
2981 // that all objects are in the positive half of address space.
2982 if (M == CodeModel::Small && Offset < 16*1024*1024)
2985 // For kernel code model we know that all object resist in the negative half
2986 // of 32bits address space. We may not accept negative offsets, since they may
2987 // be just off and we may accept pretty large positive ones.
2988 if (M == CodeModel::Kernel && Offset > 0)
2994 /// isCalleePop - Determines whether the callee is required to pop its
2995 /// own arguments. Callee pop is necessary to support tail calls.
2996 bool X86::isCalleePop(CallingConv::ID CallingConv,
2997 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3001 switch (CallingConv) {
3004 case CallingConv::X86_StdCall:
3006 case CallingConv::X86_FastCall:
3008 case CallingConv::X86_ThisCall:
3010 case CallingConv::Fast:
3012 case CallingConv::GHC:
3017 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3018 /// specific condition code, returning the condition code and the LHS/RHS of the
3019 /// comparison to make.
3020 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3021 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3023 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3024 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3025 // X > -1 -> X == 0, jump !sign.
3026 RHS = DAG.getConstant(0, RHS.getValueType());
3027 return X86::COND_NS;
3028 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3029 // X < 0 -> X == 0, jump on sign.
3031 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3033 RHS = DAG.getConstant(0, RHS.getValueType());
3034 return X86::COND_LE;
3038 switch (SetCCOpcode) {
3039 default: llvm_unreachable("Invalid integer condition!");
3040 case ISD::SETEQ: return X86::COND_E;
3041 case ISD::SETGT: return X86::COND_G;
3042 case ISD::SETGE: return X86::COND_GE;
3043 case ISD::SETLT: return X86::COND_L;
3044 case ISD::SETLE: return X86::COND_LE;
3045 case ISD::SETNE: return X86::COND_NE;
3046 case ISD::SETULT: return X86::COND_B;
3047 case ISD::SETUGT: return X86::COND_A;
3048 case ISD::SETULE: return X86::COND_BE;
3049 case ISD::SETUGE: return X86::COND_AE;
3053 // First determine if it is required or is profitable to flip the operands.
3055 // If LHS is a foldable load, but RHS is not, flip the condition.
3056 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3057 !ISD::isNON_EXTLoad(RHS.getNode())) {
3058 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3059 std::swap(LHS, RHS);
3062 switch (SetCCOpcode) {
3068 std::swap(LHS, RHS);
3072 // On a floating point condition, the flags are set as follows:
3074 // 0 | 0 | 0 | X > Y
3075 // 0 | 0 | 1 | X < Y
3076 // 1 | 0 | 0 | X == Y
3077 // 1 | 1 | 1 | unordered
3078 switch (SetCCOpcode) {
3079 default: llvm_unreachable("Condcode should be pre-legalized away");
3081 case ISD::SETEQ: return X86::COND_E;
3082 case ISD::SETOLT: // flipped
3084 case ISD::SETGT: return X86::COND_A;
3085 case ISD::SETOLE: // flipped
3087 case ISD::SETGE: return X86::COND_AE;
3088 case ISD::SETUGT: // flipped
3090 case ISD::SETLT: return X86::COND_B;
3091 case ISD::SETUGE: // flipped
3093 case ISD::SETLE: return X86::COND_BE;
3095 case ISD::SETNE: return X86::COND_NE;
3096 case ISD::SETUO: return X86::COND_P;
3097 case ISD::SETO: return X86::COND_NP;
3099 case ISD::SETUNE: return X86::COND_INVALID;
3103 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3104 /// code. Current x86 isa includes the following FP cmov instructions:
3105 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3106 static bool hasFPCMov(unsigned X86CC) {
3122 /// isFPImmLegal - Returns true if the target can instruction select the
3123 /// specified FP immediate natively. If false, the legalizer will
3124 /// materialize the FP immediate as a load from a constant pool.
3125 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3126 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3127 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3133 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3134 /// the specified range (L, H].
3135 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3136 return (Val < 0) || (Val >= Low && Val < Hi);
3139 /// isUndefOrInRange - Return true if every element in Mask, begining
3140 /// from position Pos and ending in Pos+Size, falls within the specified
3141 /// range (L, L+Pos]. or is undef.
3142 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3143 int Pos, int Size, int Low, int Hi) {
3144 for (int i = Pos, e = Pos+Size; i != e; ++i)
3145 if (!isUndefOrInRange(Mask[i], Low, Hi))
3150 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3151 /// specified value.
3152 static bool isUndefOrEqual(int Val, int CmpVal) {
3153 if (Val < 0 || Val == CmpVal)
3158 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3159 /// from position Pos and ending in Pos+Size, falls within the specified
3160 /// sequential range (L, L+Pos]. or is undef.
3161 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3162 int Pos, int Size, int Low) {
3163 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3164 if (!isUndefOrEqual(Mask[i], Low))
3169 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3170 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3171 /// the second operand.
3172 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3173 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3174 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3175 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3176 return (Mask[0] < 2 && Mask[1] < 2);
3180 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3181 SmallVector<int, 8> M;
3183 return ::isPSHUFDMask(M, N->getValueType(0));
3186 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3187 /// is suitable for input to PSHUFHW.
3188 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3189 if (VT != MVT::v8i16)
3192 // Lower quadword copied in order or undef.
3193 for (int i = 0; i != 4; ++i)
3194 if (Mask[i] >= 0 && Mask[i] != i)
3197 // Upper quadword shuffled.
3198 for (int i = 4; i != 8; ++i)
3199 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3205 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3206 SmallVector<int, 8> M;
3208 return ::isPSHUFHWMask(M, N->getValueType(0));
3211 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3212 /// is suitable for input to PSHUFLW.
3213 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3214 if (VT != MVT::v8i16)
3217 // Upper quadword copied in order.
3218 for (int i = 4; i != 8; ++i)
3219 if (Mask[i] >= 0 && Mask[i] != i)
3222 // Lower quadword shuffled.
3223 for (int i = 0; i != 4; ++i)
3230 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3231 SmallVector<int, 8> M;
3233 return ::isPSHUFLWMask(M, N->getValueType(0));
3236 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3237 /// is suitable for input to PALIGNR.
3238 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3239 bool hasSSSE3OrAVX) {
3240 int i, e = VT.getVectorNumElements();
3241 if (VT.getSizeInBits() != 128)
3244 // Do not handle v2i64 / v2f64 shuffles with palignr.
3245 if (e < 4 || !hasSSSE3OrAVX)
3248 for (i = 0; i != e; ++i)
3252 // All undef, not a palignr.
3256 // Make sure we're shifting in the right direction.
3260 int s = Mask[i] - i;
3262 // Check the rest of the elements to see if they are consecutive.
3263 for (++i; i != e; ++i) {
3265 if (m >= 0 && m != s+i)
3271 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3272 /// specifies a shuffle of elements that is suitable for input to 256-bit
3274 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3275 bool HasAVX, bool Commuted = false) {
3276 int NumElems = VT.getVectorNumElements();
3278 if (!HasAVX || VT.getSizeInBits() != 256)
3281 if (NumElems != 4 && NumElems != 8)
3284 // VSHUFPSY divides the resulting vector into 4 chunks.
3285 // The sources are also splitted into 4 chunks, and each destination
3286 // chunk must come from a different source chunk.
3288 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3289 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3291 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3292 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3294 // VSHUFPDY divides the resulting vector into 4 chunks.
3295 // The sources are also splitted into 4 chunks, and each destination
3296 // chunk must come from a different source chunk.
3298 // SRC1 => X3 X2 X1 X0
3299 // SRC2 => Y3 Y2 Y1 Y0
3301 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3303 unsigned QuarterSize = NumElems/4;
3304 unsigned HalfSize = QuarterSize*2;
3305 for (unsigned l = 0; l != 2; ++l) {
3306 unsigned LaneStart = l*HalfSize;
3307 for (unsigned s = 0; s != 2; ++s) {
3308 unsigned QuarterStart = s*QuarterSize;
3309 unsigned Src = (Commuted) ? (1-s) : s;
3310 unsigned SrcStart = Src*NumElems + LaneStart;
3311 for (unsigned i = 0; i != QuarterSize; ++i) {
3312 int Idx = Mask[i+QuarterStart+LaneStart];
3313 if (!isUndefOrInRange(Idx, SrcStart, SrcStart+HalfSize))
3315 // For VSHUFPSY, the mask of the second half must be the same as the
3316 // first but with the appropriate offsets. This works in the same way as
3317 // VPERMILPS works with masks.
3318 if (NumElems == 4 || l == 0 || Mask[i+QuarterStart] < 0)
3320 if (!isUndefOrEqual(Idx, Mask[i+QuarterStart]+HalfSize))
3329 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3330 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3331 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3332 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3333 EVT VT = SVOp->getValueType(0);
3334 int NumElems = VT.getVectorNumElements();
3336 assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3337 assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3339 int HalfSize = NumElems/2;
3340 unsigned Mul = (NumElems == 8) ? 2 : 1;
3342 for (int i = 0; i != NumElems; ++i) {
3343 int Elt = SVOp->getMaskElt(i);
3348 // For VSHUFPSY, the mask of the first half must be equal to the second one.
3349 if (NumElems == 8) Shamt %= HalfSize;
3350 Mask |= Elt << (Shamt*Mul);
3356 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3357 /// the two vector operands have swapped position.
3358 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3359 unsigned NumElems) {
3360 for (unsigned i = 0; i != NumElems; ++i) {
3364 else if (idx < (int)NumElems)
3365 Mask[i] = idx + NumElems;
3367 Mask[i] = idx - NumElems;
3371 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3372 /// specifies a shuffle of elements that is suitable for input to 128-bit
3373 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3374 /// reverse of what x86 shuffles want.
3375 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3376 bool Commuted = false) {
3377 unsigned NumElems = VT.getVectorNumElements();
3379 if (VT.getSizeInBits() != 128)
3382 if (NumElems != 2 && NumElems != 4)
3385 unsigned Half = NumElems / 2;
3386 unsigned SrcStart = Commuted ? NumElems : 0;
3387 for (unsigned i = 0; i != Half; ++i)
3388 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3390 SrcStart = Commuted ? 0 : NumElems;
3391 for (unsigned i = Half; i != NumElems; ++i)
3392 if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3398 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3399 SmallVector<int, 8> M;
3401 return ::isSHUFPMask(M, N->getValueType(0));
3404 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3405 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3406 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3407 EVT VT = N->getValueType(0);
3408 unsigned NumElems = VT.getVectorNumElements();
3410 if (VT.getSizeInBits() != 128)
3416 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3417 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3418 isUndefOrEqual(N->getMaskElt(1), 7) &&
3419 isUndefOrEqual(N->getMaskElt(2), 2) &&
3420 isUndefOrEqual(N->getMaskElt(3), 3);
3423 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3424 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3426 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3427 EVT VT = N->getValueType(0);
3428 unsigned NumElems = VT.getVectorNumElements();
3430 if (VT.getSizeInBits() != 128)
3436 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3437 isUndefOrEqual(N->getMaskElt(1), 3) &&
3438 isUndefOrEqual(N->getMaskElt(2), 2) &&
3439 isUndefOrEqual(N->getMaskElt(3), 3);
3442 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3443 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3444 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3445 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3447 if (NumElems != 2 && NumElems != 4)
3450 for (unsigned i = 0; i < NumElems/2; ++i)
3451 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3454 for (unsigned i = NumElems/2; i < NumElems; ++i)
3455 if (!isUndefOrEqual(N->getMaskElt(i), i))
3461 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3462 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3463 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3464 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3466 if ((NumElems != 2 && NumElems != 4)
3467 || N->getValueType(0).getSizeInBits() > 128)
3470 for (unsigned i = 0; i < NumElems/2; ++i)
3471 if (!isUndefOrEqual(N->getMaskElt(i), i))
3474 for (unsigned i = 0; i < NumElems/2; ++i)
3475 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3481 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3482 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3483 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3484 bool HasAVX2, bool V2IsSplat = false) {
3485 unsigned NumElts = VT.getVectorNumElements();
3487 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3488 "Unsupported vector type for unpckh");
3490 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3491 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3494 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3495 // independently on 128-bit lanes.
3496 unsigned NumLanes = VT.getSizeInBits()/128;
3497 unsigned NumLaneElts = NumElts/NumLanes;
3499 for (unsigned l = 0; l != NumLanes; ++l) {
3500 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3501 i != (l+1)*NumLaneElts;
3504 int BitI1 = Mask[i+1];
3505 if (!isUndefOrEqual(BitI, j))
3508 if (!isUndefOrEqual(BitI1, NumElts))
3511 if (!isUndefOrEqual(BitI1, j + NumElts))
3520 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3521 SmallVector<int, 8> M;
3523 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3526 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3527 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3528 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3529 bool HasAVX2, bool V2IsSplat = false) {
3530 unsigned NumElts = VT.getVectorNumElements();
3532 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3533 "Unsupported vector type for unpckh");
3535 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3536 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3539 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3540 // independently on 128-bit lanes.
3541 unsigned NumLanes = VT.getSizeInBits()/128;
3542 unsigned NumLaneElts = NumElts/NumLanes;
3544 for (unsigned l = 0; l != NumLanes; ++l) {
3545 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3546 i != (l+1)*NumLaneElts; i += 2, ++j) {
3548 int BitI1 = Mask[i+1];
3549 if (!isUndefOrEqual(BitI, j))
3552 if (isUndefOrEqual(BitI1, NumElts))
3555 if (!isUndefOrEqual(BitI1, j+NumElts))
3563 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3564 SmallVector<int, 8> M;
3566 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3569 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3570 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3572 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3574 unsigned NumElts = VT.getVectorNumElements();
3576 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3577 "Unsupported vector type for unpckh");
3579 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3580 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3583 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3584 // FIXME: Need a better way to get rid of this, there's no latency difference
3585 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3586 // the former later. We should also remove the "_undef" special mask.
3587 if (NumElts == 4 && VT.getSizeInBits() == 256)
3590 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3591 // independently on 128-bit lanes.
3592 unsigned NumLanes = VT.getSizeInBits()/128;
3593 unsigned NumLaneElts = NumElts/NumLanes;
3595 for (unsigned l = 0; l != NumLanes; ++l) {
3596 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3597 i != (l+1)*NumLaneElts;
3600 int BitI1 = Mask[i+1];
3602 if (!isUndefOrEqual(BitI, j))
3604 if (!isUndefOrEqual(BitI1, j))
3612 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3613 SmallVector<int, 8> M;
3615 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3618 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3619 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3621 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3623 unsigned NumElts = VT.getVectorNumElements();
3625 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3626 "Unsupported vector type for unpckh");
3628 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3629 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3632 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3633 // independently on 128-bit lanes.
3634 unsigned NumLanes = VT.getSizeInBits()/128;
3635 unsigned NumLaneElts = NumElts/NumLanes;
3637 for (unsigned l = 0; l != NumLanes; ++l) {
3638 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3639 i != (l+1)*NumLaneElts; i += 2, ++j) {
3641 int BitI1 = Mask[i+1];
3642 if (!isUndefOrEqual(BitI, j))
3644 if (!isUndefOrEqual(BitI1, j))
3651 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3652 SmallVector<int, 8> M;
3654 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3657 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3658 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3659 /// MOVSD, and MOVD, i.e. setting the lowest element.
3660 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3661 if (VT.getVectorElementType().getSizeInBits() < 32)
3664 int NumElts = VT.getVectorNumElements();
3666 if (!isUndefOrEqual(Mask[0], NumElts))
3669 for (int i = 1; i < NumElts; ++i)
3670 if (!isUndefOrEqual(Mask[i], i))
3676 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3677 SmallVector<int, 8> M;
3679 return ::isMOVLMask(M, N->getValueType(0));
3682 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3683 /// as permutations between 128-bit chunks or halves. As an example: this
3685 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3686 /// The first half comes from the second half of V1 and the second half from the
3687 /// the second half of V2.
3688 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3690 if (!HasAVX || VT.getSizeInBits() != 256)
3693 // The shuffle result is divided into half A and half B. In total the two
3694 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3695 // B must come from C, D, E or F.
3696 int HalfSize = VT.getVectorNumElements()/2;
3697 bool MatchA = false, MatchB = false;
3699 // Check if A comes from one of C, D, E, F.
3700 for (int Half = 0; Half < 4; ++Half) {
3701 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3707 // Check if B comes from one of C, D, E, F.
3708 for (int Half = 0; Half < 4; ++Half) {
3709 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3715 return MatchA && MatchB;
3718 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3719 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3720 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3721 EVT VT = SVOp->getValueType(0);
3723 int HalfSize = VT.getVectorNumElements()/2;
3725 int FstHalf = 0, SndHalf = 0;
3726 for (int i = 0; i < HalfSize; ++i) {
3727 if (SVOp->getMaskElt(i) > 0) {
3728 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3732 for (int i = HalfSize; i < HalfSize*2; ++i) {
3733 if (SVOp->getMaskElt(i) > 0) {
3734 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3739 return (FstHalf | (SndHalf << 4));
3742 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3743 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3744 /// Note that VPERMIL mask matching is different depending whether theunderlying
3745 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3746 /// to the same elements of the low, but to the higher half of the source.
3747 /// In VPERMILPD the two lanes could be shuffled independently of each other
3748 /// with the same restriction that lanes can't be crossed.
3749 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3751 int NumElts = VT.getVectorNumElements();
3752 int NumLanes = VT.getSizeInBits()/128;
3757 // Only match 256-bit with 32/64-bit types
3758 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3761 int LaneSize = NumElts/NumLanes;
3762 for (int l = 0; l != NumLanes; ++l) {
3763 int LaneStart = l*LaneSize;
3764 for (int i = 0; i != LaneSize; ++i) {
3765 if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3767 if (NumElts == 4 || l == 0)
3769 // VPERMILPS handling
3772 if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3780 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3781 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3782 static unsigned getShuffleVPERMILPImmediate(ShuffleVectorSDNode *SVOp) {
3783 EVT VT = SVOp->getValueType(0);
3785 int NumElts = VT.getVectorNumElements();
3786 int NumLanes = VT.getSizeInBits()/128;
3787 int LaneSize = NumElts/NumLanes;
3789 // Although the mask is equal for both lanes do it twice to get the cases
3790 // where a mask will match because the same mask element is undef on the
3791 // first half but valid on the second. This would get pathological cases
3792 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3793 unsigned Shift = (LaneSize == 4) ? 2 : 1;
3795 for (int i = 0; i != NumElts; ++i) {
3796 int MaskElt = SVOp->getMaskElt(i);
3799 MaskElt %= LaneSize;
3801 // VPERMILPSY, the mask of the first half must be equal to the second one
3802 if (NumElts == 8) Shamt %= LaneSize;
3803 Mask |= MaskElt << (Shamt*Shift);
3809 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3810 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3811 /// element of vector 2 and the other elements to come from vector 1 in order.
3812 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3813 bool V2IsSplat = false, bool V2IsUndef = false) {
3814 int NumOps = VT.getVectorNumElements();
3815 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3818 if (!isUndefOrEqual(Mask[0], 0))
3821 for (int i = 1; i < NumOps; ++i)
3822 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3823 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3824 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3830 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3831 bool V2IsUndef = false) {
3832 SmallVector<int, 8> M;
3834 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3837 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3838 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3839 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3840 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3841 const X86Subtarget *Subtarget) {
3842 if (!Subtarget->hasSSE3orAVX())
3845 // The second vector must be undef
3846 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3849 EVT VT = N->getValueType(0);
3850 unsigned NumElems = VT.getVectorNumElements();
3852 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3853 (VT.getSizeInBits() == 256 && NumElems != 8))
3856 // "i+1" is the value the indexed mask element must have
3857 for (unsigned i = 0; i < NumElems; i += 2)
3858 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3859 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3865 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3866 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3867 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3868 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3869 const X86Subtarget *Subtarget) {
3870 if (!Subtarget->hasSSE3orAVX())
3873 // The second vector must be undef
3874 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3877 EVT VT = N->getValueType(0);
3878 unsigned NumElems = VT.getVectorNumElements();
3880 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3881 (VT.getSizeInBits() == 256 && NumElems != 8))
3884 // "i" is the value the indexed mask element must have
3885 for (unsigned i = 0; i < NumElems; i += 2)
3886 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3887 !isUndefOrEqual(N->getMaskElt(i+1), i))
3893 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3894 /// specifies a shuffle of elements that is suitable for input to 256-bit
3895 /// version of MOVDDUP.
3896 static bool isMOVDDUPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3898 int NumElts = VT.getVectorNumElements();
3900 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3903 for (int i = 0; i != NumElts/2; ++i)
3904 if (!isUndefOrEqual(Mask[i], 0))
3906 for (int i = NumElts/2; i != NumElts; ++i)
3907 if (!isUndefOrEqual(Mask[i], NumElts/2))
3912 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to 128-bit
3914 /// version of MOVDDUP.
3915 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3916 EVT VT = N->getValueType(0);
3918 if (VT.getSizeInBits() != 128)
3921 int e = VT.getVectorNumElements() / 2;
3922 for (int i = 0; i < e; ++i)
3923 if (!isUndefOrEqual(N->getMaskElt(i), i))
3925 for (int i = 0; i < e; ++i)
3926 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3931 /// isVEXTRACTF128Index - Return true if the specified
3932 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3933 /// suitable for input to VEXTRACTF128.
3934 bool X86::isVEXTRACTF128Index(SDNode *N) {
3935 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3938 // The index should be aligned on a 128-bit boundary.
3940 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3942 unsigned VL = N->getValueType(0).getVectorNumElements();
3943 unsigned VBits = N->getValueType(0).getSizeInBits();
3944 unsigned ElSize = VBits / VL;
3945 bool Result = (Index * ElSize) % 128 == 0;
3950 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3951 /// operand specifies a subvector insert that is suitable for input to
3953 bool X86::isVINSERTF128Index(SDNode *N) {
3954 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3957 // The index should be aligned on a 128-bit boundary.
3959 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3961 unsigned VL = N->getValueType(0).getVectorNumElements();
3962 unsigned VBits = N->getValueType(0).getSizeInBits();
3963 unsigned ElSize = VBits / VL;
3964 bool Result = (Index * ElSize) % 128 == 0;
3969 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3970 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3971 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3972 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3973 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3975 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3977 for (int i = 0; i < NumOperands; ++i) {
3978 int Val = SVOp->getMaskElt(NumOperands-i-1);
3979 if (Val < 0) Val = 0;
3980 if (Val >= NumOperands) Val -= NumOperands;
3982 if (i != NumOperands - 1)
3988 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3989 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3990 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3991 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3993 // 8 nodes, but we only care about the last 4.
3994 for (unsigned i = 7; i >= 4; --i) {
3995 int Val = SVOp->getMaskElt(i);
4004 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4005 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4006 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4007 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4009 // 8 nodes, but we only care about the first 4.
4010 for (int i = 3; i >= 0; --i) {
4011 int Val = SVOp->getMaskElt(i);
4020 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4021 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4022 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4023 EVT VT = SVOp->getValueType(0);
4024 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4028 for (i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4029 Val = SVOp->getMaskElt(i);
4033 assert(Val - i > 0 && "PALIGNR imm should be positive");
4034 return (Val - i) * EltSize;
4037 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4038 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4040 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4041 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4042 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4045 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4047 EVT VecVT = N->getOperand(0).getValueType();
4048 EVT ElVT = VecVT.getVectorElementType();
4050 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4051 return Index / NumElemsPerChunk;
4054 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4055 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4057 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4058 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4059 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4062 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4064 EVT VecVT = N->getValueType(0);
4065 EVT ElVT = VecVT.getVectorElementType();
4067 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4068 return Index / NumElemsPerChunk;
4071 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4073 bool X86::isZeroNode(SDValue Elt) {
4074 return ((isa<ConstantSDNode>(Elt) &&
4075 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4076 (isa<ConstantFPSDNode>(Elt) &&
4077 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4080 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4081 /// their permute mask.
4082 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4083 SelectionDAG &DAG) {
4084 EVT VT = SVOp->getValueType(0);
4085 unsigned NumElems = VT.getVectorNumElements();
4086 SmallVector<int, 8> MaskVec;
4088 for (unsigned i = 0; i != NumElems; ++i) {
4089 int idx = SVOp->getMaskElt(i);
4091 MaskVec.push_back(idx);
4092 else if (idx < (int)NumElems)
4093 MaskVec.push_back(idx + NumElems);
4095 MaskVec.push_back(idx - NumElems);
4097 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4098 SVOp->getOperand(0), &MaskVec[0]);
4101 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4102 /// match movhlps. The lower half elements should come from upper half of
4103 /// V1 (and in order), and the upper half elements should come from the upper
4104 /// half of V2 (and in order).
4105 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4106 EVT VT = Op->getValueType(0);
4107 if (VT.getSizeInBits() != 128)
4109 if (VT.getVectorNumElements() != 4)
4111 for (unsigned i = 0, e = 2; i != e; ++i)
4112 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4114 for (unsigned i = 2; i != 4; ++i)
4115 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4120 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4121 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4123 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4124 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4126 N = N->getOperand(0).getNode();
4127 if (!ISD::isNON_EXTLoad(N))
4130 *LD = cast<LoadSDNode>(N);
4134 // Test whether the given value is a vector value which will be legalized
4136 static bool WillBeConstantPoolLoad(SDNode *N) {
4137 if (N->getOpcode() != ISD::BUILD_VECTOR)
4140 // Check for any non-constant elements.
4141 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4142 switch (N->getOperand(i).getNode()->getOpcode()) {
4144 case ISD::ConstantFP:
4151 // Vectors of all-zeros and all-ones are materialized with special
4152 // instructions rather than being loaded.
4153 return !ISD::isBuildVectorAllZeros(N) &&
4154 !ISD::isBuildVectorAllOnes(N);
4157 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4158 /// match movlp{s|d}. The lower half elements should come from lower half of
4159 /// V1 (and in order), and the upper half elements should come from the upper
4160 /// half of V2 (and in order). And since V1 will become the source of the
4161 /// MOVLP, it must be either a vector load or a scalar load to vector.
4162 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4163 ShuffleVectorSDNode *Op) {
4164 EVT VT = Op->getValueType(0);
4165 if (VT.getSizeInBits() != 128)
4168 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4170 // Is V2 is a vector load, don't do this transformation. We will try to use
4171 // load folding shufps op.
4172 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4175 unsigned NumElems = VT.getVectorNumElements();
4177 if (NumElems != 2 && NumElems != 4)
4179 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4180 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4182 for (unsigned i = NumElems/2; i != NumElems; ++i)
4183 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4188 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4190 static bool isSplatVector(SDNode *N) {
4191 if (N->getOpcode() != ISD::BUILD_VECTOR)
4194 SDValue SplatValue = N->getOperand(0);
4195 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4196 if (N->getOperand(i) != SplatValue)
4201 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4202 /// to an zero vector.
4203 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4204 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4205 SDValue V1 = N->getOperand(0);
4206 SDValue V2 = N->getOperand(1);
4207 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4208 for (unsigned i = 0; i != NumElems; ++i) {
4209 int Idx = N->getMaskElt(i);
4210 if (Idx >= (int)NumElems) {
4211 unsigned Opc = V2.getOpcode();
4212 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4214 if (Opc != ISD::BUILD_VECTOR ||
4215 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4217 } else if (Idx >= 0) {
4218 unsigned Opc = V1.getOpcode();
4219 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4221 if (Opc != ISD::BUILD_VECTOR ||
4222 !X86::isZeroNode(V1.getOperand(Idx)))
4229 /// getZeroVector - Returns a vector of specified type with all zero elements.
4231 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4233 assert(VT.isVector() && "Expected a vector type");
4235 // Always build SSE zero vectors as <4 x i32> bitcasted
4236 // to their dest type. This ensures they get CSE'd.
4238 if (VT.getSizeInBits() == 128) { // SSE
4239 if (HasXMMInt) { // SSE2
4240 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4241 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4243 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4244 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4246 } else if (VT.getSizeInBits() == 256) { // AVX
4247 // 256-bit logic and arithmetic instructions in AVX are
4248 // all floating-point, no support for integer ops. Default
4249 // to emitting fp zeroed vectors then.
4250 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4251 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4252 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4254 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4257 /// getOnesVector - Returns a vector of specified type with all bits set.
4258 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4259 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4260 /// Then bitcast to their original type, ensuring they get CSE'd.
4261 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4263 assert(VT.isVector() && "Expected a vector type");
4264 assert((VT.is128BitVector() || VT.is256BitVector())
4265 && "Expected a 128-bit or 256-bit vector type");
4267 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4269 if (VT.getSizeInBits() == 256) {
4270 if (HasAVX2) { // AVX2
4271 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4272 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4274 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4275 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4276 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4277 Vec = Insert128BitVector(InsV, Vec,
4278 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4281 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4284 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4287 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4288 /// that point to V2 points to its first element.
4289 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4290 EVT VT = SVOp->getValueType(0);
4291 unsigned NumElems = VT.getVectorNumElements();
4293 bool Changed = false;
4294 SmallVector<int, 8> MaskVec;
4295 SVOp->getMask(MaskVec);
4297 for (unsigned i = 0; i != NumElems; ++i) {
4298 if (MaskVec[i] > (int)NumElems) {
4299 MaskVec[i] = NumElems;
4304 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4305 SVOp->getOperand(1), &MaskVec[0]);
4306 return SDValue(SVOp, 0);
4309 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4310 /// operation of specified width.
4311 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4313 unsigned NumElems = VT.getVectorNumElements();
4314 SmallVector<int, 8> Mask;
4315 Mask.push_back(NumElems);
4316 for (unsigned i = 1; i != NumElems; ++i)
4318 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4321 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4322 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4324 unsigned NumElems = VT.getVectorNumElements();
4325 SmallVector<int, 8> Mask;
4326 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4328 Mask.push_back(i + NumElems);
4330 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4333 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4334 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4336 unsigned NumElems = VT.getVectorNumElements();
4337 unsigned Half = NumElems/2;
4338 SmallVector<int, 8> Mask;
4339 for (unsigned i = 0; i != Half; ++i) {
4340 Mask.push_back(i + Half);
4341 Mask.push_back(i + NumElems + Half);
4343 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4346 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4347 // a generic shuffle instruction because the target has no such instructions.
4348 // Generate shuffles which repeat i16 and i8 several times until they can be
4349 // represented by v4f32 and then be manipulated by target suported shuffles.
4350 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4351 EVT VT = V.getValueType();
4352 int NumElems = VT.getVectorNumElements();
4353 DebugLoc dl = V.getDebugLoc();
4355 while (NumElems > 4) {
4356 if (EltNo < NumElems/2) {
4357 V = getUnpackl(DAG, dl, VT, V, V);
4359 V = getUnpackh(DAG, dl, VT, V, V);
4360 EltNo -= NumElems/2;
4367 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4368 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4369 EVT VT = V.getValueType();
4370 DebugLoc dl = V.getDebugLoc();
4371 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4372 && "Vector size not supported");
4374 if (VT.getSizeInBits() == 128) {
4375 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4376 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4377 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4380 // To use VPERMILPS to splat scalars, the second half of indicies must
4381 // refer to the higher part, which is a duplication of the lower one,
4382 // because VPERMILPS can only handle in-lane permutations.
4383 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4384 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4386 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4387 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4391 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4394 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4395 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4396 EVT SrcVT = SV->getValueType(0);
4397 SDValue V1 = SV->getOperand(0);
4398 DebugLoc dl = SV->getDebugLoc();
4400 int EltNo = SV->getSplatIndex();
4401 int NumElems = SrcVT.getVectorNumElements();
4402 unsigned Size = SrcVT.getSizeInBits();
4404 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4405 "Unknown how to promote splat for type");
4407 // Extract the 128-bit part containing the splat element and update
4408 // the splat element index when it refers to the higher register.
4410 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4411 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4413 EltNo -= NumElems/2;
4416 // All i16 and i8 vector types can't be used directly by a generic shuffle
4417 // instruction because the target has no such instruction. Generate shuffles
4418 // which repeat i16 and i8 several times until they fit in i32, and then can
4419 // be manipulated by target suported shuffles.
4420 EVT EltVT = SrcVT.getVectorElementType();
4421 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4422 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4424 // Recreate the 256-bit vector and place the same 128-bit vector
4425 // into the low and high part. This is necessary because we want
4426 // to use VPERM* to shuffle the vectors
4428 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4429 DAG.getConstant(0, MVT::i32), DAG, dl);
4430 V1 = Insert128BitVector(InsV, V1,
4431 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4434 return getLegalSplat(DAG, V1, EltNo);
4437 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4438 /// vector of zero or undef vector. This produces a shuffle where the low
4439 /// element of V2 is swizzled into the zero/undef vector, landing at element
4440 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4441 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4442 bool isZero, bool HasXMMInt,
4443 SelectionDAG &DAG) {
4444 EVT VT = V2.getValueType();
4446 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4447 unsigned NumElems = VT.getVectorNumElements();
4448 SmallVector<int, 16> MaskVec;
4449 for (unsigned i = 0; i != NumElems; ++i)
4450 // If this is the insertion idx, put the low elt of V2 here.
4451 MaskVec.push_back(i == Idx ? NumElems : i);
4452 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4455 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4456 /// element of the result of the vector shuffle.
4457 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4460 return SDValue(); // Limit search depth.
4462 SDValue V = SDValue(N, 0);
4463 EVT VT = V.getValueType();
4464 unsigned Opcode = V.getOpcode();
4466 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4467 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4468 Index = SV->getMaskElt(Index);
4471 return DAG.getUNDEF(VT.getVectorElementType());
4473 int NumElems = VT.getVectorNumElements();
4474 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4475 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4478 // Recurse into target specific vector shuffles to find scalars.
4479 if (isTargetShuffle(Opcode)) {
4480 int NumElems = VT.getVectorNumElements();
4481 SmallVector<unsigned, 16> ShuffleMask;
4485 case X86ISD::SHUFPS:
4486 case X86ISD::SHUFPD:
4487 ImmN = N->getOperand(N->getNumOperands()-1);
4488 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4491 case X86ISD::UNPCKH:
4492 DecodeUNPCKHMask(VT, ShuffleMask);
4494 case X86ISD::UNPCKL:
4495 DecodeUNPCKLMask(VT, ShuffleMask);
4497 case X86ISD::MOVHLPS:
4498 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4500 case X86ISD::MOVLHPS:
4501 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4503 case X86ISD::PSHUFD:
4504 ImmN = N->getOperand(N->getNumOperands()-1);
4505 DecodePSHUFMask(NumElems,
4506 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4509 case X86ISD::PSHUFHW:
4510 ImmN = N->getOperand(N->getNumOperands()-1);
4511 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4514 case X86ISD::PSHUFLW:
4515 ImmN = N->getOperand(N->getNumOperands()-1);
4516 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4520 case X86ISD::MOVSD: {
4521 // The index 0 always comes from the first element of the second source,
4522 // this is why MOVSS and MOVSD are used in the first place. The other
4523 // elements come from the other positions of the first source vector.
4524 unsigned OpNum = (Index == 0) ? 1 : 0;
4525 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4528 case X86ISD::VPERMILP:
4529 ImmN = N->getOperand(N->getNumOperands()-1);
4530 DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4533 case X86ISD::VPERM2X128:
4534 ImmN = N->getOperand(N->getNumOperands()-1);
4535 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4538 case X86ISD::MOVDDUP:
4539 case X86ISD::MOVLHPD:
4540 case X86ISD::MOVLPD:
4541 case X86ISD::MOVLPS:
4542 case X86ISD::MOVSHDUP:
4543 case X86ISD::MOVSLDUP:
4544 case X86ISD::PALIGN:
4545 return SDValue(); // Not yet implemented.
4547 assert(0 && "unknown target shuffle node");
4551 Index = ShuffleMask[Index];
4553 return DAG.getUNDEF(VT.getVectorElementType());
4555 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4556 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4560 // Actual nodes that may contain scalar elements
4561 if (Opcode == ISD::BITCAST) {
4562 V = V.getOperand(0);
4563 EVT SrcVT = V.getValueType();
4564 unsigned NumElems = VT.getVectorNumElements();
4566 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4570 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4571 return (Index == 0) ? V.getOperand(0)
4572 : DAG.getUNDEF(VT.getVectorElementType());
4574 if (V.getOpcode() == ISD::BUILD_VECTOR)
4575 return V.getOperand(Index);
4580 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4581 /// shuffle operation which come from a consecutively from a zero. The
4582 /// search can start in two different directions, from left or right.
4584 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4585 bool ZerosFromLeft, SelectionDAG &DAG) {
4588 while (i < NumElems) {
4589 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4590 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4591 if (!(Elt.getNode() &&
4592 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4600 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4601 /// MaskE correspond consecutively to elements from one of the vector operands,
4602 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4604 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4605 int OpIdx, int NumElems, unsigned &OpNum) {
4606 bool SeenV1 = false;
4607 bool SeenV2 = false;
4609 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4610 int Idx = SVOp->getMaskElt(i);
4611 // Ignore undef indicies
4620 // Only accept consecutive elements from the same vector
4621 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4625 OpNum = SeenV1 ? 0 : 1;
4629 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4630 /// logical left shift of a vector.
4631 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4632 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4633 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4634 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4635 false /* check zeros from right */, DAG);
4641 // Considering the elements in the mask that are not consecutive zeros,
4642 // check if they consecutively come from only one of the source vectors.
4644 // V1 = {X, A, B, C} 0
4646 // vector_shuffle V1, V2 <1, 2, 3, X>
4648 if (!isShuffleMaskConsecutive(SVOp,
4649 0, // Mask Start Index
4650 NumElems-NumZeros-1, // Mask End Index
4651 NumZeros, // Where to start looking in the src vector
4652 NumElems, // Number of elements in vector
4653 OpSrc)) // Which source operand ?
4658 ShVal = SVOp->getOperand(OpSrc);
4662 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4663 /// logical left shift of a vector.
4664 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4665 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4666 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4667 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4668 true /* check zeros from left */, DAG);
4674 // Considering the elements in the mask that are not consecutive zeros,
4675 // check if they consecutively come from only one of the source vectors.
4677 // 0 { A, B, X, X } = V2
4679 // vector_shuffle V1, V2 <X, X, 4, 5>
4681 if (!isShuffleMaskConsecutive(SVOp,
4682 NumZeros, // Mask Start Index
4683 NumElems-1, // Mask End Index
4684 0, // Where to start looking in the src vector
4685 NumElems, // Number of elements in vector
4686 OpSrc)) // Which source operand ?
4691 ShVal = SVOp->getOperand(OpSrc);
4695 /// isVectorShift - Returns true if the shuffle can be implemented as a
4696 /// logical left or right shift of a vector.
4697 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4698 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4699 // Although the logic below support any bitwidth size, there are no
4700 // shift instructions which handle more than 128-bit vectors.
4701 if (SVOp->getValueType(0).getSizeInBits() > 128)
4704 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4705 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4711 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4713 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4714 unsigned NumNonZero, unsigned NumZero,
4716 const TargetLowering &TLI) {
4720 DebugLoc dl = Op.getDebugLoc();
4723 for (unsigned i = 0; i < 16; ++i) {
4724 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4725 if (ThisIsNonZero && First) {
4727 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4729 V = DAG.getUNDEF(MVT::v8i16);
4734 SDValue ThisElt(0, 0), LastElt(0, 0);
4735 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4736 if (LastIsNonZero) {
4737 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4738 MVT::i16, Op.getOperand(i-1));
4740 if (ThisIsNonZero) {
4741 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4742 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4743 ThisElt, DAG.getConstant(8, MVT::i8));
4745 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4749 if (ThisElt.getNode())
4750 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4751 DAG.getIntPtrConstant(i/2));
4755 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4758 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4760 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4761 unsigned NumNonZero, unsigned NumZero,
4763 const TargetLowering &TLI) {
4767 DebugLoc dl = Op.getDebugLoc();
4770 for (unsigned i = 0; i < 8; ++i) {
4771 bool isNonZero = (NonZeros & (1 << i)) != 0;
4775 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4777 V = DAG.getUNDEF(MVT::v8i16);
4780 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4781 MVT::v8i16, V, Op.getOperand(i),
4782 DAG.getIntPtrConstant(i));
4789 /// getVShift - Return a vector logical shift node.
4791 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4792 unsigned NumBits, SelectionDAG &DAG,
4793 const TargetLowering &TLI, DebugLoc dl) {
4794 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4795 EVT ShVT = MVT::v2i64;
4796 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4797 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4798 return DAG.getNode(ISD::BITCAST, dl, VT,
4799 DAG.getNode(Opc, dl, ShVT, SrcOp,
4800 DAG.getConstant(NumBits,
4801 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4805 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4806 SelectionDAG &DAG) const {
4808 // Check if the scalar load can be widened into a vector load. And if
4809 // the address is "base + cst" see if the cst can be "absorbed" into
4810 // the shuffle mask.
4811 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4812 SDValue Ptr = LD->getBasePtr();
4813 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4815 EVT PVT = LD->getValueType(0);
4816 if (PVT != MVT::i32 && PVT != MVT::f32)
4821 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4822 FI = FINode->getIndex();
4824 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4825 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4826 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4827 Offset = Ptr.getConstantOperandVal(1);
4828 Ptr = Ptr.getOperand(0);
4833 // FIXME: 256-bit vector instructions don't require a strict alignment,
4834 // improve this code to support it better.
4835 unsigned RequiredAlign = VT.getSizeInBits()/8;
4836 SDValue Chain = LD->getChain();
4837 // Make sure the stack object alignment is at least 16 or 32.
4838 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4839 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4840 if (MFI->isFixedObjectIndex(FI)) {
4841 // Can't change the alignment. FIXME: It's possible to compute
4842 // the exact stack offset and reference FI + adjust offset instead.
4843 // If someone *really* cares about this. That's the way to implement it.
4846 MFI->setObjectAlignment(FI, RequiredAlign);
4850 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4851 // Ptr + (Offset & ~15).
4854 if ((Offset % RequiredAlign) & 3)
4856 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4858 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4859 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4861 int EltNo = (Offset - StartOffset) >> 2;
4862 int NumElems = VT.getVectorNumElements();
4864 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4865 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4866 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4867 LD->getPointerInfo().getWithOffset(StartOffset),
4868 false, false, false, 0);
4870 // Canonicalize it to a v4i32 or v8i32 shuffle.
4871 SmallVector<int, 8> Mask;
4872 for (int i = 0; i < NumElems; ++i)
4873 Mask.push_back(EltNo);
4875 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4876 return DAG.getNode(ISD::BITCAST, dl, NVT,
4877 DAG.getVectorShuffle(CanonVT, dl, V1,
4878 DAG.getUNDEF(CanonVT),&Mask[0]));
4884 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4885 /// vector of type 'VT', see if the elements can be replaced by a single large
4886 /// load which has the same value as a build_vector whose operands are 'elts'.
4888 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4890 /// FIXME: we'd also like to handle the case where the last elements are zero
4891 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4892 /// There's even a handy isZeroNode for that purpose.
4893 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4894 DebugLoc &DL, SelectionDAG &DAG) {
4895 EVT EltVT = VT.getVectorElementType();
4896 unsigned NumElems = Elts.size();
4898 LoadSDNode *LDBase = NULL;
4899 unsigned LastLoadedElt = -1U;
4901 // For each element in the initializer, see if we've found a load or an undef.
4902 // If we don't find an initial load element, or later load elements are
4903 // non-consecutive, bail out.
4904 for (unsigned i = 0; i < NumElems; ++i) {
4905 SDValue Elt = Elts[i];
4907 if (!Elt.getNode() ||
4908 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4911 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4913 LDBase = cast<LoadSDNode>(Elt.getNode());
4917 if (Elt.getOpcode() == ISD::UNDEF)
4920 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4921 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4926 // If we have found an entire vector of loads and undefs, then return a large
4927 // load of the entire vector width starting at the base pointer. If we found
4928 // consecutive loads for the low half, generate a vzext_load node.
4929 if (LastLoadedElt == NumElems - 1) {
4930 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4931 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4932 LDBase->getPointerInfo(),
4933 LDBase->isVolatile(), LDBase->isNonTemporal(),
4934 LDBase->isInvariant(), 0);
4935 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4936 LDBase->getPointerInfo(),
4937 LDBase->isVolatile(), LDBase->isNonTemporal(),
4938 LDBase->isInvariant(), LDBase->getAlignment());
4939 } else if (NumElems == 4 && LastLoadedElt == 1 &&
4940 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4941 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4942 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4944 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4945 LDBase->getPointerInfo(),
4946 LDBase->getAlignment(),
4947 false/*isVolatile*/, true/*ReadMem*/,
4949 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4954 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4955 /// a vbroadcast node. We support two patterns:
4956 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4957 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4959 /// The scalar load node is returned when a pattern is found,
4960 /// or SDValue() otherwise.
4961 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
4962 EVT VT = Op.getValueType();
4965 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4966 V = V.getOperand(0);
4968 //A suspected load to be broadcasted.
4971 switch (V.getOpcode()) {
4973 // Unknown pattern found.
4976 case ISD::BUILD_VECTOR: {
4977 // The BUILD_VECTOR node must be a splat.
4978 if (!isSplatVector(V.getNode()))
4981 Ld = V.getOperand(0);
4983 // The suspected load node has several users. Make sure that all
4984 // of its users are from the BUILD_VECTOR node.
4985 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4990 case ISD::VECTOR_SHUFFLE: {
4991 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4993 // Shuffles must have a splat mask where the first element is
4995 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4998 SDValue Sc = Op.getOperand(0);
4999 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5002 Ld = Sc.getOperand(0);
5004 // The scalar_to_vector node and the suspected
5005 // load node must have exactly one user.
5006 if (!Sc.hasOneUse() || !Ld.hasOneUse())
5012 // The scalar source must be a normal load.
5013 if (!ISD::isNormalLoad(Ld.getNode()))
5016 bool Is256 = VT.getSizeInBits() == 256;
5017 bool Is128 = VT.getSizeInBits() == 128;
5018 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5021 // VBroadcast to YMM
5022 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
5023 ScalarSize == 32 || ScalarSize == 64 ))
5026 // VBroadcast to XMM
5027 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
5028 ScalarSize == 16 || ScalarSize == 64 ))
5032 // VBroadcast to YMM
5033 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5036 // VBroadcast to XMM
5037 if (Is128 && (ScalarSize == 32))
5041 // Unsupported broadcast.
5046 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5047 DebugLoc dl = Op.getDebugLoc();
5049 EVT VT = Op.getValueType();
5050 EVT ExtVT = VT.getVectorElementType();
5051 unsigned NumElems = Op.getNumOperands();
5053 // Vectors containing all zeros can be matched by pxor and xorps later
5054 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5055 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5056 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5057 if (Op.getValueType() == MVT::v4i32 ||
5058 Op.getValueType() == MVT::v8i32)
5061 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5064 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5065 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5066 // vpcmpeqd on 256-bit vectors.
5067 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5068 if (Op.getValueType() == MVT::v4i32 ||
5069 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5072 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5075 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5076 if (Subtarget->hasAVX() && LD.getNode())
5077 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5079 unsigned EVTBits = ExtVT.getSizeInBits();
5081 unsigned NumZero = 0;
5082 unsigned NumNonZero = 0;
5083 unsigned NonZeros = 0;
5084 bool IsAllConstants = true;
5085 SmallSet<SDValue, 8> Values;
5086 for (unsigned i = 0; i < NumElems; ++i) {
5087 SDValue Elt = Op.getOperand(i);
5088 if (Elt.getOpcode() == ISD::UNDEF)
5091 if (Elt.getOpcode() != ISD::Constant &&
5092 Elt.getOpcode() != ISD::ConstantFP)
5093 IsAllConstants = false;
5094 if (X86::isZeroNode(Elt))
5097 NonZeros |= (1 << i);
5102 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5103 if (NumNonZero == 0)
5104 return DAG.getUNDEF(VT);
5106 // Special case for single non-zero, non-undef, element.
5107 if (NumNonZero == 1) {
5108 unsigned Idx = CountTrailingZeros_32(NonZeros);
5109 SDValue Item = Op.getOperand(Idx);
5111 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5112 // the value are obviously zero, truncate the value to i32 and do the
5113 // insertion that way. Only do this if the value is non-constant or if the
5114 // value is a constant being inserted into element 0. It is cheaper to do
5115 // a constant pool load than it is to do a movd + shuffle.
5116 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5117 (!IsAllConstants || Idx == 0)) {
5118 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5120 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5121 EVT VecVT = MVT::v4i32;
5122 unsigned VecElts = 4;
5124 // Truncate the value (which may itself be a constant) to i32, and
5125 // convert it to a vector with movd (S2V+shuffle to zero extend).
5126 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5127 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5128 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5129 Subtarget->hasXMMInt(), DAG);
5131 // Now we have our 32-bit value zero extended in the low element of
5132 // a vector. If Idx != 0, swizzle it into place.
5134 SmallVector<int, 4> Mask;
5135 Mask.push_back(Idx);
5136 for (unsigned i = 1; i != VecElts; ++i)
5138 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5139 DAG.getUNDEF(Item.getValueType()),
5142 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5146 // If we have a constant or non-constant insertion into the low element of
5147 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5148 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5149 // depending on what the source datatype is.
5152 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5153 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5154 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5155 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5156 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5157 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5159 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5160 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5161 unsigned NumBits = VT.getSizeInBits();
5162 assert((NumBits == 128 || NumBits == 256) &&
5163 "Expected an SSE or AVX value type!");
5164 EVT MiddleVT = NumBits == 128 ? MVT::v4i32 : MVT::v8i32;
5165 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5166 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5167 Subtarget->hasXMMInt(), DAG);
5168 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5172 // Is it a vector logical left shift?
5173 if (NumElems == 2 && Idx == 1 &&
5174 X86::isZeroNode(Op.getOperand(0)) &&
5175 !X86::isZeroNode(Op.getOperand(1))) {
5176 unsigned NumBits = VT.getSizeInBits();
5177 return getVShift(true, VT,
5178 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5179 VT, Op.getOperand(1)),
5180 NumBits/2, DAG, *this, dl);
5183 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5186 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5187 // is a non-constant being inserted into an element other than the low one,
5188 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5189 // movd/movss) to move this into the low element, then shuffle it into
5191 if (EVTBits == 32) {
5192 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5194 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5195 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5196 Subtarget->hasXMMInt(), DAG);
5197 SmallVector<int, 8> MaskVec;
5198 for (unsigned i = 0; i < NumElems; i++)
5199 MaskVec.push_back(i == Idx ? 0 : 1);
5200 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5204 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5205 if (Values.size() == 1) {
5206 if (EVTBits == 32) {
5207 // Instead of a shuffle like this:
5208 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5209 // Check if it's possible to issue this instead.
5210 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5211 unsigned Idx = CountTrailingZeros_32(NonZeros);
5212 SDValue Item = Op.getOperand(Idx);
5213 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5214 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5219 // A vector full of immediates; various special cases are already
5220 // handled, so this is best done with a single constant-pool load.
5224 // For AVX-length vectors, build the individual 128-bit pieces and use
5225 // shuffles to put them in place.
5226 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5227 SmallVector<SDValue, 32> V;
5228 for (unsigned i = 0; i < NumElems; ++i)
5229 V.push_back(Op.getOperand(i));
5231 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5233 // Build both the lower and upper subvector.
5234 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5235 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5238 // Recreate the wider vector with the lower and upper part.
5239 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5240 DAG.getConstant(0, MVT::i32), DAG, dl);
5241 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5245 // Let legalizer expand 2-wide build_vectors.
5246 if (EVTBits == 64) {
5247 if (NumNonZero == 1) {
5248 // One half is zero or undef.
5249 unsigned Idx = CountTrailingZeros_32(NonZeros);
5250 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5251 Op.getOperand(Idx));
5252 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5253 Subtarget->hasXMMInt(), DAG);
5258 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5259 if (EVTBits == 8 && NumElems == 16) {
5260 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5262 if (V.getNode()) return V;
5265 if (EVTBits == 16 && NumElems == 8) {
5266 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5268 if (V.getNode()) return V;
5271 // If element VT is == 32 bits, turn it into a number of shuffles.
5272 SmallVector<SDValue, 8> V;
5274 if (NumElems == 4 && NumZero > 0) {
5275 for (unsigned i = 0; i < 4; ++i) {
5276 bool isZero = !(NonZeros & (1 << i));
5278 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5280 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5283 for (unsigned i = 0; i < 2; ++i) {
5284 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5287 V[i] = V[i*2]; // Must be a zero vector.
5290 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5293 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5296 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5301 SmallVector<int, 8> MaskVec;
5302 bool Reverse = (NonZeros & 0x3) == 2;
5303 for (unsigned i = 0; i < 2; ++i)
5304 MaskVec.push_back(Reverse ? 1-i : i);
5305 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5306 for (unsigned i = 0; i < 2; ++i)
5307 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5308 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5311 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5312 // Check for a build vector of consecutive loads.
5313 for (unsigned i = 0; i < NumElems; ++i)
5314 V[i] = Op.getOperand(i);
5316 // Check for elements which are consecutive loads.
5317 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5321 // For SSE 4.1, use insertps to put the high elements into the low element.
5322 if (getSubtarget()->hasSSE41orAVX()) {
5324 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5325 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5327 Result = DAG.getUNDEF(VT);
5329 for (unsigned i = 1; i < NumElems; ++i) {
5330 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5331 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5332 Op.getOperand(i), DAG.getIntPtrConstant(i));
5337 // Otherwise, expand into a number of unpckl*, start by extending each of
5338 // our (non-undef) elements to the full vector width with the element in the
5339 // bottom slot of the vector (which generates no code for SSE).
5340 for (unsigned i = 0; i < NumElems; ++i) {
5341 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5342 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5344 V[i] = DAG.getUNDEF(VT);
5347 // Next, we iteratively mix elements, e.g. for v4f32:
5348 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5349 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5350 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5351 unsigned EltStride = NumElems >> 1;
5352 while (EltStride != 0) {
5353 for (unsigned i = 0; i < EltStride; ++i) {
5354 // If V[i+EltStride] is undef and this is the first round of mixing,
5355 // then it is safe to just drop this shuffle: V[i] is already in the
5356 // right place, the one element (since it's the first round) being
5357 // inserted as undef can be dropped. This isn't safe for successive
5358 // rounds because they will permute elements within both vectors.
5359 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5360 EltStride == NumElems/2)
5363 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5372 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5373 // them in a MMX register. This is better than doing a stack convert.
5374 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5375 DebugLoc dl = Op.getDebugLoc();
5376 EVT ResVT = Op.getValueType();
5378 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5379 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5381 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5382 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5383 InVec = Op.getOperand(1);
5384 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5385 unsigned NumElts = ResVT.getVectorNumElements();
5386 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5387 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5388 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5390 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5391 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5392 Mask[0] = 0; Mask[1] = 2;
5393 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5395 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5398 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5399 // to create 256-bit vectors from two other 128-bit ones.
5400 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5401 DebugLoc dl = Op.getDebugLoc();
5402 EVT ResVT = Op.getValueType();
5404 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5406 SDValue V1 = Op.getOperand(0);
5407 SDValue V2 = Op.getOperand(1);
5408 unsigned NumElems = ResVT.getVectorNumElements();
5410 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5411 DAG.getConstant(0, MVT::i32), DAG, dl);
5412 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5417 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5418 EVT ResVT = Op.getValueType();
5420 assert(Op.getNumOperands() == 2);
5421 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5422 "Unsupported CONCAT_VECTORS for value type");
5424 // We support concatenate two MMX registers and place them in a MMX register.
5425 // This is better than doing a stack convert.
5426 if (ResVT.is128BitVector())
5427 return LowerMMXCONCAT_VECTORS(Op, DAG);
5429 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5430 // from two other 128-bit ones.
5431 return LowerAVXCONCAT_VECTORS(Op, DAG);
5434 // v8i16 shuffles - Prefer shuffles in the following order:
5435 // 1. [all] pshuflw, pshufhw, optional move
5436 // 2. [ssse3] 1 x pshufb
5437 // 3. [ssse3] 2 x pshufb + 1 x por
5438 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5440 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5441 SelectionDAG &DAG) const {
5442 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5443 SDValue V1 = SVOp->getOperand(0);
5444 SDValue V2 = SVOp->getOperand(1);
5445 DebugLoc dl = SVOp->getDebugLoc();
5446 SmallVector<int, 8> MaskVals;
5448 // Determine if more than 1 of the words in each of the low and high quadwords
5449 // of the result come from the same quadword of one of the two inputs. Undef
5450 // mask values count as coming from any quadword, for better codegen.
5451 unsigned LoQuad[] = { 0, 0, 0, 0 };
5452 unsigned HiQuad[] = { 0, 0, 0, 0 };
5453 BitVector InputQuads(4);
5454 for (unsigned i = 0; i < 8; ++i) {
5455 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5456 int EltIdx = SVOp->getMaskElt(i);
5457 MaskVals.push_back(EltIdx);
5466 InputQuads.set(EltIdx / 4);
5469 int BestLoQuad = -1;
5470 unsigned MaxQuad = 1;
5471 for (unsigned i = 0; i < 4; ++i) {
5472 if (LoQuad[i] > MaxQuad) {
5474 MaxQuad = LoQuad[i];
5478 int BestHiQuad = -1;
5480 for (unsigned i = 0; i < 4; ++i) {
5481 if (HiQuad[i] > MaxQuad) {
5483 MaxQuad = HiQuad[i];
5487 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5488 // of the two input vectors, shuffle them into one input vector so only a
5489 // single pshufb instruction is necessary. If There are more than 2 input
5490 // quads, disable the next transformation since it does not help SSSE3.
5491 bool V1Used = InputQuads[0] || InputQuads[1];
5492 bool V2Used = InputQuads[2] || InputQuads[3];
5493 if (Subtarget->hasSSSE3orAVX()) {
5494 if (InputQuads.count() == 2 && V1Used && V2Used) {
5495 BestLoQuad = InputQuads.find_first();
5496 BestHiQuad = InputQuads.find_next(BestLoQuad);
5498 if (InputQuads.count() > 2) {
5504 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5505 // the shuffle mask. If a quad is scored as -1, that means that it contains
5506 // words from all 4 input quadwords.
5508 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5509 SmallVector<int, 8> MaskV;
5510 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5511 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5512 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5513 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5514 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5515 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5517 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5518 // source words for the shuffle, to aid later transformations.
5519 bool AllWordsInNewV = true;
5520 bool InOrder[2] = { true, true };
5521 for (unsigned i = 0; i != 8; ++i) {
5522 int idx = MaskVals[i];
5524 InOrder[i/4] = false;
5525 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5527 AllWordsInNewV = false;
5531 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5532 if (AllWordsInNewV) {
5533 for (int i = 0; i != 8; ++i) {
5534 int idx = MaskVals[i];
5537 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5538 if ((idx != i) && idx < 4)
5540 if ((idx != i) && idx > 3)
5549 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5550 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5551 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5552 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5553 unsigned TargetMask = 0;
5554 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5555 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5556 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5557 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5558 V1 = NewV.getOperand(0);
5559 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5563 // If we have SSSE3, and all words of the result are from 1 input vector,
5564 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5565 // is present, fall back to case 4.
5566 if (Subtarget->hasSSSE3orAVX()) {
5567 SmallVector<SDValue,16> pshufbMask;
5569 // If we have elements from both input vectors, set the high bit of the
5570 // shuffle mask element to zero out elements that come from V2 in the V1
5571 // mask, and elements that come from V1 in the V2 mask, so that the two
5572 // results can be OR'd together.
5573 bool TwoInputs = V1Used && V2Used;
5574 for (unsigned i = 0; i != 8; ++i) {
5575 int EltIdx = MaskVals[i] * 2;
5576 if (TwoInputs && (EltIdx >= 16)) {
5577 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5578 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5581 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5582 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5584 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5585 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5586 DAG.getNode(ISD::BUILD_VECTOR, dl,
5587 MVT::v16i8, &pshufbMask[0], 16));
5589 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5591 // Calculate the shuffle mask for the second input, shuffle it, and
5592 // OR it with the first shuffled input.
5594 for (unsigned i = 0; i != 8; ++i) {
5595 int EltIdx = MaskVals[i] * 2;
5597 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5598 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5601 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5602 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5604 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5605 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5606 DAG.getNode(ISD::BUILD_VECTOR, dl,
5607 MVT::v16i8, &pshufbMask[0], 16));
5608 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5609 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5612 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5613 // and update MaskVals with new element order.
5614 BitVector InOrder(8);
5615 if (BestLoQuad >= 0) {
5616 SmallVector<int, 8> MaskV;
5617 for (int i = 0; i != 4; ++i) {
5618 int idx = MaskVals[i];
5620 MaskV.push_back(-1);
5622 } else if ((idx / 4) == BestLoQuad) {
5623 MaskV.push_back(idx & 3);
5626 MaskV.push_back(-1);
5629 for (unsigned i = 4; i != 8; ++i)
5631 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5634 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5635 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5637 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5641 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5642 // and update MaskVals with the new element order.
5643 if (BestHiQuad >= 0) {
5644 SmallVector<int, 8> MaskV;
5645 for (unsigned i = 0; i != 4; ++i)
5647 for (unsigned i = 4; i != 8; ++i) {
5648 int idx = MaskVals[i];
5650 MaskV.push_back(-1);
5652 } else if ((idx / 4) == BestHiQuad) {
5653 MaskV.push_back((idx & 3) + 4);
5656 MaskV.push_back(-1);
5659 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5662 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5663 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5665 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5669 // In case BestHi & BestLo were both -1, which means each quadword has a word
5670 // from each of the four input quadwords, calculate the InOrder bitvector now
5671 // before falling through to the insert/extract cleanup.
5672 if (BestLoQuad == -1 && BestHiQuad == -1) {
5674 for (int i = 0; i != 8; ++i)
5675 if (MaskVals[i] < 0 || MaskVals[i] == i)
5679 // The other elements are put in the right place using pextrw and pinsrw.
5680 for (unsigned i = 0; i != 8; ++i) {
5683 int EltIdx = MaskVals[i];
5686 SDValue ExtOp = (EltIdx < 8)
5687 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5688 DAG.getIntPtrConstant(EltIdx))
5689 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5690 DAG.getIntPtrConstant(EltIdx - 8));
5691 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5692 DAG.getIntPtrConstant(i));
5697 // v16i8 shuffles - Prefer shuffles in the following order:
5698 // 1. [ssse3] 1 x pshufb
5699 // 2. [ssse3] 2 x pshufb + 1 x por
5700 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5702 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5704 const X86TargetLowering &TLI) {
5705 SDValue V1 = SVOp->getOperand(0);
5706 SDValue V2 = SVOp->getOperand(1);
5707 DebugLoc dl = SVOp->getDebugLoc();
5708 SmallVector<int, 16> MaskVals;
5709 SVOp->getMask(MaskVals);
5711 // If we have SSSE3, case 1 is generated when all result bytes come from
5712 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5713 // present, fall back to case 3.
5714 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5717 for (unsigned i = 0; i < 16; ++i) {
5718 int EltIdx = MaskVals[i];
5727 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5728 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5729 SmallVector<SDValue,16> pshufbMask;
5731 // If all result elements are from one input vector, then only translate
5732 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5734 // Otherwise, we have elements from both input vectors, and must zero out
5735 // elements that come from V2 in the first mask, and V1 in the second mask
5736 // so that we can OR them together.
5737 bool TwoInputs = !(V1Only || V2Only);
5738 for (unsigned i = 0; i != 16; ++i) {
5739 int EltIdx = MaskVals[i];
5740 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5741 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5744 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5746 // If all the elements are from V2, assign it to V1 and return after
5747 // building the first pshufb.
5750 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5751 DAG.getNode(ISD::BUILD_VECTOR, dl,
5752 MVT::v16i8, &pshufbMask[0], 16));
5756 // Calculate the shuffle mask for the second input, shuffle it, and
5757 // OR it with the first shuffled input.
5759 for (unsigned i = 0; i != 16; ++i) {
5760 int EltIdx = MaskVals[i];
5762 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5765 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5767 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5768 DAG.getNode(ISD::BUILD_VECTOR, dl,
5769 MVT::v16i8, &pshufbMask[0], 16));
5770 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5773 // No SSSE3 - Calculate in place words and then fix all out of place words
5774 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5775 // the 16 different words that comprise the two doublequadword input vectors.
5776 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5777 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5778 SDValue NewV = V2Only ? V2 : V1;
5779 for (int i = 0; i != 8; ++i) {
5780 int Elt0 = MaskVals[i*2];
5781 int Elt1 = MaskVals[i*2+1];
5783 // This word of the result is all undef, skip it.
5784 if (Elt0 < 0 && Elt1 < 0)
5787 // This word of the result is already in the correct place, skip it.
5788 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5790 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5793 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5794 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5797 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5798 // using a single extract together, load it and store it.
5799 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5800 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5801 DAG.getIntPtrConstant(Elt1 / 2));
5802 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5803 DAG.getIntPtrConstant(i));
5807 // If Elt1 is defined, extract it from the appropriate source. If the
5808 // source byte is not also odd, shift the extracted word left 8 bits
5809 // otherwise clear the bottom 8 bits if we need to do an or.
5811 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5812 DAG.getIntPtrConstant(Elt1 / 2));
5813 if ((Elt1 & 1) == 0)
5814 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5816 TLI.getShiftAmountTy(InsElt.getValueType())));
5818 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5819 DAG.getConstant(0xFF00, MVT::i16));
5821 // If Elt0 is defined, extract it from the appropriate source. If the
5822 // source byte is not also even, shift the extracted word right 8 bits. If
5823 // Elt1 was also defined, OR the extracted values together before
5824 // inserting them in the result.
5826 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5827 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5828 if ((Elt0 & 1) != 0)
5829 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5831 TLI.getShiftAmountTy(InsElt0.getValueType())));
5833 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5834 DAG.getConstant(0x00FF, MVT::i16));
5835 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5838 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5839 DAG.getIntPtrConstant(i));
5841 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5844 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5845 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5846 /// done when every pair / quad of shuffle mask elements point to elements in
5847 /// the right sequence. e.g.
5848 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5850 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5851 SelectionDAG &DAG, DebugLoc dl) {
5852 EVT VT = SVOp->getValueType(0);
5853 SDValue V1 = SVOp->getOperand(0);
5854 SDValue V2 = SVOp->getOperand(1);
5855 unsigned NumElems = VT.getVectorNumElements();
5856 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5858 switch (VT.getSimpleVT().SimpleTy) {
5859 default: assert(false && "Unexpected!");
5860 case MVT::v4f32: NewVT = MVT::v2f64; break;
5861 case MVT::v4i32: NewVT = MVT::v2i64; break;
5862 case MVT::v8i16: NewVT = MVT::v4i32; break;
5863 case MVT::v16i8: NewVT = MVT::v4i32; break;
5866 int Scale = NumElems / NewWidth;
5867 SmallVector<int, 8> MaskVec;
5868 for (unsigned i = 0; i < NumElems; i += Scale) {
5870 for (int j = 0; j < Scale; ++j) {
5871 int EltIdx = SVOp->getMaskElt(i+j);
5875 StartIdx = EltIdx - (EltIdx % Scale);
5876 if (EltIdx != StartIdx + j)
5880 MaskVec.push_back(-1);
5882 MaskVec.push_back(StartIdx / Scale);
5885 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5886 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5887 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5890 /// getVZextMovL - Return a zero-extending vector move low node.
5892 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5893 SDValue SrcOp, SelectionDAG &DAG,
5894 const X86Subtarget *Subtarget, DebugLoc dl) {
5895 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5896 LoadSDNode *LD = NULL;
5897 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5898 LD = dyn_cast<LoadSDNode>(SrcOp);
5900 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5902 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5903 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5904 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5905 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5906 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5908 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5909 return DAG.getNode(ISD::BITCAST, dl, VT,
5910 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5911 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5919 return DAG.getNode(ISD::BITCAST, dl, VT,
5920 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5921 DAG.getNode(ISD::BITCAST, dl,
5925 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5926 /// shuffle node referes to only one lane in the sources.
5927 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5928 EVT VT = SVOp->getValueType(0);
5929 int NumElems = VT.getVectorNumElements();
5930 int HalfSize = NumElems/2;
5931 SmallVector<int, 16> M;
5933 bool MatchA = false, MatchB = false;
5935 for (int l = 0; l < NumElems*2; l += HalfSize) {
5936 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5942 for (int l = 0; l < NumElems*2; l += HalfSize) {
5943 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5949 return MatchA && MatchB;
5952 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5953 /// which could not be matched by any known target speficic shuffle
5955 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5956 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5957 // If each half of a vector shuffle node referes to only one lane in the
5958 // source vectors, extract each used 128-bit lane and shuffle them using
5959 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5960 // the work to the legalizer.
5961 DebugLoc dl = SVOp->getDebugLoc();
5962 EVT VT = SVOp->getValueType(0);
5963 int NumElems = VT.getVectorNumElements();
5964 int HalfSize = NumElems/2;
5966 // Extract the reference for each half
5967 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5968 int FstVecOpNum = 0, SndVecOpNum = 0;
5969 for (int i = 0; i < HalfSize; ++i) {
5970 int Elt = SVOp->getMaskElt(i);
5971 if (SVOp->getMaskElt(i) < 0)
5973 FstVecOpNum = Elt/NumElems;
5974 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5977 for (int i = HalfSize; i < NumElems; ++i) {
5978 int Elt = SVOp->getMaskElt(i);
5979 if (SVOp->getMaskElt(i) < 0)
5981 SndVecOpNum = Elt/NumElems;
5982 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5986 // Extract the subvectors
5987 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5988 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5989 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5990 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5992 // Generate 128-bit shuffles
5993 SmallVector<int, 16> MaskV1, MaskV2;
5994 for (int i = 0; i < HalfSize; ++i) {
5995 int Elt = SVOp->getMaskElt(i);
5996 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5998 for (int i = HalfSize; i < NumElems; ++i) {
5999 int Elt = SVOp->getMaskElt(i);
6000 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6003 EVT NVT = V1.getValueType();
6004 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6005 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6007 // Concatenate the result back
6008 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6009 DAG.getConstant(0, MVT::i32), DAG, dl);
6010 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6017 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6018 /// 4 elements, and match them with several different shuffle types.
6020 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6021 SDValue V1 = SVOp->getOperand(0);
6022 SDValue V2 = SVOp->getOperand(1);
6023 DebugLoc dl = SVOp->getDebugLoc();
6024 EVT VT = SVOp->getValueType(0);
6026 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6028 SmallVector<std::pair<int, int>, 8> Locs;
6030 SmallVector<int, 8> Mask1(4U, -1);
6031 SmallVector<int, 8> PermMask;
6032 SVOp->getMask(PermMask);
6036 for (unsigned i = 0; i != 4; ++i) {
6037 int Idx = PermMask[i];
6039 Locs[i] = std::make_pair(-1, -1);
6041 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6043 Locs[i] = std::make_pair(0, NumLo);
6047 Locs[i] = std::make_pair(1, NumHi);
6049 Mask1[2+NumHi] = Idx;
6055 if (NumLo <= 2 && NumHi <= 2) {
6056 // If no more than two elements come from either vector. This can be
6057 // implemented with two shuffles. First shuffle gather the elements.
6058 // The second shuffle, which takes the first shuffle as both of its
6059 // vector operands, put the elements into the right order.
6060 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6062 SmallVector<int, 8> Mask2(4U, -1);
6064 for (unsigned i = 0; i != 4; ++i) {
6065 if (Locs[i].first == -1)
6068 unsigned Idx = (i < 2) ? 0 : 4;
6069 Idx += Locs[i].first * 2 + Locs[i].second;
6074 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6075 } else if (NumLo == 3 || NumHi == 3) {
6076 // Otherwise, we must have three elements from one vector, call it X, and
6077 // one element from the other, call it Y. First, use a shufps to build an
6078 // intermediate vector with the one element from Y and the element from X
6079 // that will be in the same half in the final destination (the indexes don't
6080 // matter). Then, use a shufps to build the final vector, taking the half
6081 // containing the element from Y from the intermediate, and the other half
6084 // Normalize it so the 3 elements come from V1.
6085 CommuteVectorShuffleMask(PermMask, 4);
6089 // Find the element from V2.
6091 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6092 int Val = PermMask[HiIndex];
6099 Mask1[0] = PermMask[HiIndex];
6101 Mask1[2] = PermMask[HiIndex^1];
6103 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6106 Mask1[0] = PermMask[0];
6107 Mask1[1] = PermMask[1];
6108 Mask1[2] = HiIndex & 1 ? 6 : 4;
6109 Mask1[3] = HiIndex & 1 ? 4 : 6;
6110 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6112 Mask1[0] = HiIndex & 1 ? 2 : 0;
6113 Mask1[1] = HiIndex & 1 ? 0 : 2;
6114 Mask1[2] = PermMask[2];
6115 Mask1[3] = PermMask[3];
6120 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6124 // Break it into (shuffle shuffle_hi, shuffle_lo).
6127 SmallVector<int,8> LoMask(4U, -1);
6128 SmallVector<int,8> HiMask(4U, -1);
6130 SmallVector<int,8> *MaskPtr = &LoMask;
6131 unsigned MaskIdx = 0;
6134 for (unsigned i = 0; i != 4; ++i) {
6141 int Idx = PermMask[i];
6143 Locs[i] = std::make_pair(-1, -1);
6144 } else if (Idx < 4) {
6145 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6146 (*MaskPtr)[LoIdx] = Idx;
6149 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6150 (*MaskPtr)[HiIdx] = Idx;
6155 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6156 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6157 SmallVector<int, 8> MaskOps;
6158 for (unsigned i = 0; i != 4; ++i) {
6159 if (Locs[i].first == -1) {
6160 MaskOps.push_back(-1);
6162 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6163 MaskOps.push_back(Idx);
6166 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6169 static bool MayFoldVectorLoad(SDValue V) {
6170 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6171 V = V.getOperand(0);
6172 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6173 V = V.getOperand(0);
6174 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6175 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6176 // BUILD_VECTOR (load), undef
6177 V = V.getOperand(0);
6183 // FIXME: the version above should always be used. Since there's
6184 // a bug where several vector shuffles can't be folded because the
6185 // DAG is not updated during lowering and a node claims to have two
6186 // uses while it only has one, use this version, and let isel match
6187 // another instruction if the load really happens to have more than
6188 // one use. Remove this version after this bug get fixed.
6189 // rdar://8434668, PR8156
6190 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6191 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6192 V = V.getOperand(0);
6193 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6194 V = V.getOperand(0);
6195 if (ISD::isNormalLoad(V.getNode()))
6200 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6201 /// a vector extract, and if both can be later optimized into a single load.
6202 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6203 /// here because otherwise a target specific shuffle node is going to be
6204 /// emitted for this shuffle, and the optimization not done.
6205 /// FIXME: This is probably not the best approach, but fix the problem
6206 /// until the right path is decided.
6208 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6209 const TargetLowering &TLI) {
6210 EVT VT = V.getValueType();
6211 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6213 // Be sure that the vector shuffle is present in a pattern like this:
6214 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6218 SDNode *N = *V.getNode()->use_begin();
6219 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6222 SDValue EltNo = N->getOperand(1);
6223 if (!isa<ConstantSDNode>(EltNo))
6226 // If the bit convert changed the number of elements, it is unsafe
6227 // to examine the mask.
6228 bool HasShuffleIntoBitcast = false;
6229 if (V.getOpcode() == ISD::BITCAST) {
6230 EVT SrcVT = V.getOperand(0).getValueType();
6231 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6233 V = V.getOperand(0);
6234 HasShuffleIntoBitcast = true;
6237 // Select the input vector, guarding against out of range extract vector.
6238 unsigned NumElems = VT.getVectorNumElements();
6239 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6240 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6241 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6243 // Skip one more bit_convert if necessary
6244 if (V.getOpcode() == ISD::BITCAST)
6245 V = V.getOperand(0);
6247 if (ISD::isNormalLoad(V.getNode())) {
6248 // Is the original load suitable?
6249 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6251 // FIXME: avoid the multi-use bug that is preventing lots of
6252 // of foldings to be detected, this is still wrong of course, but
6253 // give the temporary desired behavior, and if it happens that
6254 // the load has real more uses, during isel it will not fold, and
6255 // will generate poor code.
6256 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6259 if (!HasShuffleIntoBitcast)
6262 // If there's a bitcast before the shuffle, check if the load type and
6263 // alignment is valid.
6264 unsigned Align = LN0->getAlignment();
6266 TLI.getTargetData()->getABITypeAlignment(
6267 VT.getTypeForEVT(*DAG.getContext()));
6269 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6277 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6278 EVT VT = Op.getValueType();
6280 // Canonizalize to v2f64.
6281 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6282 return DAG.getNode(ISD::BITCAST, dl, VT,
6283 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6288 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6290 SDValue V1 = Op.getOperand(0);
6291 SDValue V2 = Op.getOperand(1);
6292 EVT VT = Op.getValueType();
6294 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6296 if (HasXMMInt && VT == MVT::v2f64)
6297 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6299 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6300 return DAG.getNode(ISD::BITCAST, dl, VT,
6301 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6302 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6303 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6307 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6308 SDValue V1 = Op.getOperand(0);
6309 SDValue V2 = Op.getOperand(1);
6310 EVT VT = Op.getValueType();
6312 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6313 "unsupported shuffle type");
6315 if (V2.getOpcode() == ISD::UNDEF)
6319 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6322 static inline unsigned getSHUFPOpcode(EVT VT) {
6323 switch(VT.getSimpleVT().SimpleTy) {
6324 case MVT::v8i32: // Use fp unit for int unpack.
6326 case MVT::v4i32: // Use fp unit for int unpack.
6327 case MVT::v4f32: return X86ISD::SHUFPS;
6328 case MVT::v4i64: // Use fp unit for int unpack.
6330 case MVT::v2i64: // Use fp unit for int unpack.
6331 case MVT::v2f64: return X86ISD::SHUFPD;
6333 llvm_unreachable("Unknown type for shufp*");
6339 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6340 SDValue V1 = Op.getOperand(0);
6341 SDValue V2 = Op.getOperand(1);
6342 EVT VT = Op.getValueType();
6343 unsigned NumElems = VT.getVectorNumElements();
6345 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6346 // operand of these instructions is only memory, so check if there's a
6347 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6349 bool CanFoldLoad = false;
6351 // Trivial case, when V2 comes from a load.
6352 if (MayFoldVectorLoad(V2))
6355 // When V1 is a load, it can be folded later into a store in isel, example:
6356 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6358 // (MOVLPSmr addr:$src1, VR128:$src2)
6359 // So, recognize this potential and also use MOVLPS or MOVLPD
6360 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6363 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6365 if (HasXMMInt && NumElems == 2)
6366 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6369 // If we don't care about the second element, procede to use movss.
6370 if (SVOp->getMaskElt(1) != -1)
6371 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6374 // movl and movlp will both match v2i64, but v2i64 is never matched by
6375 // movl earlier because we make it strict to avoid messing with the movlp load
6376 // folding logic (see the code above getMOVLP call). Match it here then,
6377 // this is horrible, but will stay like this until we move all shuffle
6378 // matching to x86 specific nodes. Note that for the 1st condition all
6379 // types are matched with movsd.
6381 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6382 // as to remove this logic from here, as much as possible
6383 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6384 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6385 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6388 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6390 // Invert the operand order and use SHUFPS to match it.
6391 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6392 X86::getShuffleSHUFImmediate(SVOp), DAG);
6396 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6397 const TargetLowering &TLI,
6398 const X86Subtarget *Subtarget) {
6399 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6400 EVT VT = Op.getValueType();
6401 DebugLoc dl = Op.getDebugLoc();
6402 SDValue V1 = Op.getOperand(0);
6403 SDValue V2 = Op.getOperand(1);
6405 if (isZeroShuffle(SVOp))
6406 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6408 // Handle splat operations
6409 if (SVOp->isSplat()) {
6410 unsigned NumElem = VT.getVectorNumElements();
6411 int Size = VT.getSizeInBits();
6412 // Special case, this is the only place now where it's allowed to return
6413 // a vector_shuffle operation without using a target specific node, because
6414 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6415 // this be moved to DAGCombine instead?
6416 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6419 // Use vbroadcast whenever the splat comes from a foldable load
6420 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6421 if (Subtarget->hasAVX() && LD.getNode())
6422 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6424 // Handle splats by matching through known shuffle masks
6425 if ((Size == 128 && NumElem <= 4) ||
6426 (Size == 256 && NumElem < 8))
6429 // All remaning splats are promoted to target supported vector shuffles.
6430 return PromoteSplat(SVOp, DAG);
6433 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6435 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6436 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6437 if (NewOp.getNode())
6438 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6439 } else if ((VT == MVT::v4i32 ||
6440 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6441 // FIXME: Figure out a cleaner way to do this.
6442 // Try to make use of movq to zero out the top part.
6443 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6444 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6445 if (NewOp.getNode()) {
6446 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6447 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6448 DAG, Subtarget, dl);
6450 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6451 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6452 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6453 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6454 DAG, Subtarget, dl);
6461 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6462 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6463 SDValue V1 = Op.getOperand(0);
6464 SDValue V2 = Op.getOperand(1);
6465 EVT VT = Op.getValueType();
6466 DebugLoc dl = Op.getDebugLoc();
6467 unsigned NumElems = VT.getVectorNumElements();
6468 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6469 bool V1IsSplat = false;
6470 bool V2IsSplat = false;
6471 bool HasXMMInt = Subtarget->hasXMMInt();
6472 bool HasAVX = Subtarget->hasAVX();
6473 bool HasAVX2 = Subtarget->hasAVX2();
6474 MachineFunction &MF = DAG.getMachineFunction();
6475 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6477 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6479 assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6481 // Vector shuffle lowering takes 3 steps:
6483 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6484 // narrowing and commutation of operands should be handled.
6485 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6487 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6488 // so the shuffle can be broken into other shuffles and the legalizer can
6489 // try the lowering again.
6491 // The general idea is that no vector_shuffle operation should be left to
6492 // be matched during isel, all of them must be converted to a target specific
6495 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6496 // narrowing and commutation of operands should be handled. The actual code
6497 // doesn't include all of those, work in progress...
6498 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6499 if (NewOp.getNode())
6502 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6503 // unpckh_undef). Only use pshufd if speed is more important than size.
6504 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp, HasAVX2))
6505 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6506 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp, HasAVX2))
6507 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6509 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6510 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6511 return getMOVDDup(Op, dl, V1, DAG);
6513 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6514 return getMOVHighToLow(Op, dl, DAG);
6516 // Use to match splats
6517 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6518 (VT == MVT::v2f64 || VT == MVT::v2i64))
6519 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6521 if (X86::isPSHUFDMask(SVOp)) {
6522 // The actual implementation will match the mask in the if above and then
6523 // during isel it can match several different instructions, not only pshufd
6524 // as its name says, sad but true, emulate the behavior for now...
6525 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6526 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6528 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6530 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6531 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6533 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6537 // Check if this can be converted into a logical shift.
6538 bool isLeft = false;
6541 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6542 if (isShift && ShVal.hasOneUse()) {
6543 // If the shifted value has multiple uses, it may be cheaper to use
6544 // v_set0 + movlhps or movhlps, etc.
6545 EVT EltVT = VT.getVectorElementType();
6546 ShAmt *= EltVT.getSizeInBits();
6547 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6550 if (X86::isMOVLMask(SVOp)) {
6551 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6552 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6553 if (!X86::isMOVLPMask(SVOp)) {
6554 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6555 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6557 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6558 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6562 // FIXME: fold these into legal mask.
6563 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6564 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6566 if (X86::isMOVHLPSMask(SVOp))
6567 return getMOVHighToLow(Op, dl, DAG);
6569 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6570 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6572 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6573 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6575 if (X86::isMOVLPMask(SVOp))
6576 return getMOVLP(Op, dl, DAG, HasXMMInt);
6578 if (ShouldXformToMOVHLPS(SVOp) ||
6579 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6580 return CommuteVectorShuffle(SVOp, DAG);
6583 // No better options. Use a vshl / vsrl.
6584 EVT EltVT = VT.getVectorElementType();
6585 ShAmt *= EltVT.getSizeInBits();
6586 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6589 bool Commuted = false;
6590 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6591 // 1,1,1,1 -> v8i16 though.
6592 V1IsSplat = isSplatVector(V1.getNode());
6593 V2IsSplat = isSplatVector(V2.getNode());
6595 // Canonicalize the splat or undef, if present, to be on the RHS.
6596 if (V1IsSplat && !V2IsSplat) {
6597 Op = CommuteVectorShuffle(SVOp, DAG);
6598 SVOp = cast<ShuffleVectorSDNode>(Op);
6599 V1 = SVOp->getOperand(0);
6600 V2 = SVOp->getOperand(1);
6601 std::swap(V1IsSplat, V2IsSplat);
6605 SmallVector<int, 32> M;
6608 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6609 // Shuffling low element of v1 into undef, just return v1.
6612 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6613 // the instruction selector will not match, so get a canonical MOVL with
6614 // swapped operands to undo the commute.
6615 return getMOVL(DAG, dl, VT, V2, V1);
6618 if (isUNPCKLMask(M, VT, HasAVX2))
6619 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6621 if (isUNPCKHMask(M, VT, HasAVX2))
6622 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6625 // Normalize mask so all entries that point to V2 points to its first
6626 // element then try to match unpck{h|l} again. If match, return a
6627 // new vector_shuffle with the corrected mask.
6628 SDValue NewMask = NormalizeMask(SVOp, DAG);
6629 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6630 if (NSVOp != SVOp) {
6631 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6633 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6640 // Commute is back and try unpck* again.
6641 // FIXME: this seems wrong.
6642 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6643 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6645 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6646 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6648 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6649 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6652 // Normalize the node to match x86 shuffle ops if needed
6653 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true) ||
6654 isVSHUFPYMask(M, VT, HasAVX, /* Commuted */ true)))
6655 return CommuteVectorShuffle(SVOp, DAG);
6657 // The checks below are all present in isShuffleMaskLegal, but they are
6658 // inlined here right now to enable us to directly emit target specific
6659 // nodes, and remove one by one until they don't return Op anymore.
6661 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6662 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6663 getShufflePALIGNRImmediate(SVOp),
6666 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6667 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6668 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6669 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6672 if (isPSHUFHWMask(M, VT))
6673 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6674 X86::getShufflePSHUFHWImmediate(SVOp),
6677 if (isPSHUFLWMask(M, VT))
6678 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6679 X86::getShufflePSHUFLWImmediate(SVOp),
6682 if (isSHUFPMask(M, VT))
6683 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6684 X86::getShuffleSHUFImmediate(SVOp), DAG);
6686 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6687 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6688 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6689 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6691 //===--------------------------------------------------------------------===//
6692 // Generate target specific nodes for 128 or 256-bit shuffles only
6693 // supported in the AVX instruction set.
6696 // Handle VMOVDDUPY permutations
6697 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6698 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6700 // Handle VPERMILPS/D* permutations
6701 if (isVPERMILPMask(M, VT, HasAVX))
6702 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6703 getShuffleVPERMILPImmediate(SVOp), DAG);
6705 // Handle VPERM2F128/VPERM2I128 permutations
6706 if (isVPERM2X128Mask(M, VT, HasAVX))
6707 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6708 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6710 // Handle VSHUFPS/DY permutations
6711 if (isVSHUFPYMask(M, VT, HasAVX))
6712 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6713 getShuffleVSHUFPYImmediate(SVOp), DAG);
6715 //===--------------------------------------------------------------------===//
6716 // Since no target specific shuffle was selected for this generic one,
6717 // lower it into other known shuffles. FIXME: this isn't true yet, but
6718 // this is the plan.
6721 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6722 if (VT == MVT::v8i16) {
6723 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6724 if (NewOp.getNode())
6728 if (VT == MVT::v16i8) {
6729 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6730 if (NewOp.getNode())
6734 // Handle all 128-bit wide vectors with 4 elements, and match them with
6735 // several different shuffle types.
6736 if (NumElems == 4 && VT.getSizeInBits() == 128)
6737 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6739 // Handle general 256-bit shuffles
6740 if (VT.is256BitVector())
6741 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6747 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6748 SelectionDAG &DAG) const {
6749 EVT VT = Op.getValueType();
6750 DebugLoc dl = Op.getDebugLoc();
6752 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6755 if (VT.getSizeInBits() == 8) {
6756 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6757 Op.getOperand(0), Op.getOperand(1));
6758 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6759 DAG.getValueType(VT));
6760 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6761 } else if (VT.getSizeInBits() == 16) {
6762 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6763 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6765 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6766 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6767 DAG.getNode(ISD::BITCAST, dl,
6771 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6772 Op.getOperand(0), Op.getOperand(1));
6773 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6774 DAG.getValueType(VT));
6775 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6776 } else if (VT == MVT::f32) {
6777 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6778 // the result back to FR32 register. It's only worth matching if the
6779 // result has a single use which is a store or a bitcast to i32. And in
6780 // the case of a store, it's not worth it if the index is a constant 0,
6781 // because a MOVSSmr can be used instead, which is smaller and faster.
6782 if (!Op.hasOneUse())
6784 SDNode *User = *Op.getNode()->use_begin();
6785 if ((User->getOpcode() != ISD::STORE ||
6786 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6787 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6788 (User->getOpcode() != ISD::BITCAST ||
6789 User->getValueType(0) != MVT::i32))
6791 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6792 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6795 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6796 } else if (VT == MVT::i32 || VT == MVT::i64) {
6797 // ExtractPS/pextrq works with constant index.
6798 if (isa<ConstantSDNode>(Op.getOperand(1)))
6806 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6807 SelectionDAG &DAG) const {
6808 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6811 SDValue Vec = Op.getOperand(0);
6812 EVT VecVT = Vec.getValueType();
6814 // If this is a 256-bit vector result, first extract the 128-bit vector and
6815 // then extract the element from the 128-bit vector.
6816 if (VecVT.getSizeInBits() == 256) {
6817 DebugLoc dl = Op.getNode()->getDebugLoc();
6818 unsigned NumElems = VecVT.getVectorNumElements();
6819 SDValue Idx = Op.getOperand(1);
6820 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6822 // Get the 128-bit vector.
6823 bool Upper = IdxVal >= NumElems/2;
6824 Vec = Extract128BitVector(Vec,
6825 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6827 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6828 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6831 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6833 if (Subtarget->hasSSE41orAVX()) {
6834 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6839 EVT VT = Op.getValueType();
6840 DebugLoc dl = Op.getDebugLoc();
6841 // TODO: handle v16i8.
6842 if (VT.getSizeInBits() == 16) {
6843 SDValue Vec = Op.getOperand(0);
6844 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6846 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6847 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6848 DAG.getNode(ISD::BITCAST, dl,
6851 // Transform it so it match pextrw which produces a 32-bit result.
6852 EVT EltVT = MVT::i32;
6853 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6854 Op.getOperand(0), Op.getOperand(1));
6855 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6856 DAG.getValueType(VT));
6857 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6858 } else if (VT.getSizeInBits() == 32) {
6859 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6863 // SHUFPS the element to the lowest double word, then movss.
6864 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6865 EVT VVT = Op.getOperand(0).getValueType();
6866 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6867 DAG.getUNDEF(VVT), Mask);
6868 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6869 DAG.getIntPtrConstant(0));
6870 } else if (VT.getSizeInBits() == 64) {
6871 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6872 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6873 // to match extract_elt for f64.
6874 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6878 // UNPCKHPD the element to the lowest double word, then movsd.
6879 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6880 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6881 int Mask[2] = { 1, -1 };
6882 EVT VVT = Op.getOperand(0).getValueType();
6883 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6884 DAG.getUNDEF(VVT), Mask);
6885 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6886 DAG.getIntPtrConstant(0));
6893 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6894 SelectionDAG &DAG) const {
6895 EVT VT = Op.getValueType();
6896 EVT EltVT = VT.getVectorElementType();
6897 DebugLoc dl = Op.getDebugLoc();
6899 SDValue N0 = Op.getOperand(0);
6900 SDValue N1 = Op.getOperand(1);
6901 SDValue N2 = Op.getOperand(2);
6903 if (VT.getSizeInBits() == 256)
6906 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6907 isa<ConstantSDNode>(N2)) {
6909 if (VT == MVT::v8i16)
6910 Opc = X86ISD::PINSRW;
6911 else if (VT == MVT::v16i8)
6912 Opc = X86ISD::PINSRB;
6914 Opc = X86ISD::PINSRB;
6916 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6918 if (N1.getValueType() != MVT::i32)
6919 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6920 if (N2.getValueType() != MVT::i32)
6921 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6922 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6923 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6924 // Bits [7:6] of the constant are the source select. This will always be
6925 // zero here. The DAG Combiner may combine an extract_elt index into these
6926 // bits. For example (insert (extract, 3), 2) could be matched by putting
6927 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6928 // Bits [5:4] of the constant are the destination select. This is the
6929 // value of the incoming immediate.
6930 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6931 // combine either bitwise AND or insert of float 0.0 to set these bits.
6932 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6933 // Create this as a scalar to vector..
6934 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6935 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6936 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
6937 isa<ConstantSDNode>(N2)) {
6938 // PINSR* works with constant index.
6945 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6946 EVT VT = Op.getValueType();
6947 EVT EltVT = VT.getVectorElementType();
6949 DebugLoc dl = Op.getDebugLoc();
6950 SDValue N0 = Op.getOperand(0);
6951 SDValue N1 = Op.getOperand(1);
6952 SDValue N2 = Op.getOperand(2);
6954 // If this is a 256-bit vector result, first extract the 128-bit vector,
6955 // insert the element into the extracted half and then place it back.
6956 if (VT.getSizeInBits() == 256) {
6957 if (!isa<ConstantSDNode>(N2))
6960 // Get the desired 128-bit vector half.
6961 unsigned NumElems = VT.getVectorNumElements();
6962 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6963 bool Upper = IdxVal >= NumElems/2;
6964 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6965 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6967 // Insert the element into the desired half.
6968 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6969 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6971 // Insert the changed part back to the 256-bit vector
6972 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6975 if (Subtarget->hasSSE41orAVX())
6976 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6978 if (EltVT == MVT::i8)
6981 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6982 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6983 // as its second argument.
6984 if (N1.getValueType() != MVT::i32)
6985 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6986 if (N2.getValueType() != MVT::i32)
6987 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6988 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6994 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6995 LLVMContext *Context = DAG.getContext();
6996 DebugLoc dl = Op.getDebugLoc();
6997 EVT OpVT = Op.getValueType();
6999 // If this is a 256-bit vector result, first insert into a 128-bit
7000 // vector and then insert into the 256-bit vector.
7001 if (OpVT.getSizeInBits() > 128) {
7002 // Insert into a 128-bit vector.
7003 EVT VT128 = EVT::getVectorVT(*Context,
7004 OpVT.getVectorElementType(),
7005 OpVT.getVectorNumElements() / 2);
7007 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7009 // Insert the 128-bit vector.
7010 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7011 DAG.getConstant(0, MVT::i32),
7015 if (Op.getValueType() == MVT::v1i64 &&
7016 Op.getOperand(0).getValueType() == MVT::i64)
7017 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7019 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7020 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7021 "Expected an SSE type!");
7022 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7023 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7026 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7027 // a simple subregister reference or explicit instructions to grab
7028 // upper bits of a vector.
7030 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7031 if (Subtarget->hasAVX()) {
7032 DebugLoc dl = Op.getNode()->getDebugLoc();
7033 SDValue Vec = Op.getNode()->getOperand(0);
7034 SDValue Idx = Op.getNode()->getOperand(1);
7036 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7037 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7038 return Extract128BitVector(Vec, Idx, DAG, dl);
7044 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7045 // simple superregister reference or explicit instructions to insert
7046 // the upper bits of a vector.
7048 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7049 if (Subtarget->hasAVX()) {
7050 DebugLoc dl = Op.getNode()->getDebugLoc();
7051 SDValue Vec = Op.getNode()->getOperand(0);
7052 SDValue SubVec = Op.getNode()->getOperand(1);
7053 SDValue Idx = Op.getNode()->getOperand(2);
7055 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7056 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7057 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7063 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7064 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7065 // one of the above mentioned nodes. It has to be wrapped because otherwise
7066 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7067 // be used to form addressing mode. These wrapped nodes will be selected
7070 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7071 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7073 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7075 unsigned char OpFlag = 0;
7076 unsigned WrapperKind = X86ISD::Wrapper;
7077 CodeModel::Model M = getTargetMachine().getCodeModel();
7079 if (Subtarget->isPICStyleRIPRel() &&
7080 (M == CodeModel::Small || M == CodeModel::Kernel))
7081 WrapperKind = X86ISD::WrapperRIP;
7082 else if (Subtarget->isPICStyleGOT())
7083 OpFlag = X86II::MO_GOTOFF;
7084 else if (Subtarget->isPICStyleStubPIC())
7085 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7087 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7089 CP->getOffset(), OpFlag);
7090 DebugLoc DL = CP->getDebugLoc();
7091 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7092 // With PIC, the address is actually $g + Offset.
7094 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7095 DAG.getNode(X86ISD::GlobalBaseReg,
7096 DebugLoc(), getPointerTy()),
7103 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7104 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7106 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7108 unsigned char OpFlag = 0;
7109 unsigned WrapperKind = X86ISD::Wrapper;
7110 CodeModel::Model M = getTargetMachine().getCodeModel();
7112 if (Subtarget->isPICStyleRIPRel() &&
7113 (M == CodeModel::Small || M == CodeModel::Kernel))
7114 WrapperKind = X86ISD::WrapperRIP;
7115 else if (Subtarget->isPICStyleGOT())
7116 OpFlag = X86II::MO_GOTOFF;
7117 else if (Subtarget->isPICStyleStubPIC())
7118 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7120 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7122 DebugLoc DL = JT->getDebugLoc();
7123 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7125 // With PIC, the address is actually $g + Offset.
7127 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7128 DAG.getNode(X86ISD::GlobalBaseReg,
7129 DebugLoc(), getPointerTy()),
7136 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7137 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7139 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7141 unsigned char OpFlag = 0;
7142 unsigned WrapperKind = X86ISD::Wrapper;
7143 CodeModel::Model M = getTargetMachine().getCodeModel();
7145 if (Subtarget->isPICStyleRIPRel() &&
7146 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7147 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7148 OpFlag = X86II::MO_GOTPCREL;
7149 WrapperKind = X86ISD::WrapperRIP;
7150 } else if (Subtarget->isPICStyleGOT()) {
7151 OpFlag = X86II::MO_GOT;
7152 } else if (Subtarget->isPICStyleStubPIC()) {
7153 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7154 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7155 OpFlag = X86II::MO_DARWIN_NONLAZY;
7158 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7160 DebugLoc DL = Op.getDebugLoc();
7161 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7164 // With PIC, the address is actually $g + Offset.
7165 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7166 !Subtarget->is64Bit()) {
7167 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7168 DAG.getNode(X86ISD::GlobalBaseReg,
7169 DebugLoc(), getPointerTy()),
7173 // For symbols that require a load from a stub to get the address, emit the
7175 if (isGlobalStubReference(OpFlag))
7176 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7177 MachinePointerInfo::getGOT(), false, false, false, 0);
7183 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7184 // Create the TargetBlockAddressAddress node.
7185 unsigned char OpFlags =
7186 Subtarget->ClassifyBlockAddressReference();
7187 CodeModel::Model M = getTargetMachine().getCodeModel();
7188 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7189 DebugLoc dl = Op.getDebugLoc();
7190 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7191 /*isTarget=*/true, OpFlags);
7193 if (Subtarget->isPICStyleRIPRel() &&
7194 (M == CodeModel::Small || M == CodeModel::Kernel))
7195 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7197 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7199 // With PIC, the address is actually $g + Offset.
7200 if (isGlobalRelativeToPICBase(OpFlags)) {
7201 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7202 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7210 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7212 SelectionDAG &DAG) const {
7213 // Create the TargetGlobalAddress node, folding in the constant
7214 // offset if it is legal.
7215 unsigned char OpFlags =
7216 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7217 CodeModel::Model M = getTargetMachine().getCodeModel();
7219 if (OpFlags == X86II::MO_NO_FLAG &&
7220 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7221 // A direct static reference to a global.
7222 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7225 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7228 if (Subtarget->isPICStyleRIPRel() &&
7229 (M == CodeModel::Small || M == CodeModel::Kernel))
7230 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7232 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7234 // With PIC, the address is actually $g + Offset.
7235 if (isGlobalRelativeToPICBase(OpFlags)) {
7236 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7237 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7241 // For globals that require a load from a stub to get the address, emit the
7243 if (isGlobalStubReference(OpFlags))
7244 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7245 MachinePointerInfo::getGOT(), false, false, false, 0);
7247 // If there was a non-zero offset that we didn't fold, create an explicit
7250 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7251 DAG.getConstant(Offset, getPointerTy()));
7257 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7258 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7259 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7260 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7264 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7265 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7266 unsigned char OperandFlags) {
7267 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7268 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7269 DebugLoc dl = GA->getDebugLoc();
7270 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7271 GA->getValueType(0),
7275 SDValue Ops[] = { Chain, TGA, *InFlag };
7276 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7278 SDValue Ops[] = { Chain, TGA };
7279 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7282 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7283 MFI->setAdjustsStack(true);
7285 SDValue Flag = Chain.getValue(1);
7286 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7289 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7291 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7294 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7295 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7296 DAG.getNode(X86ISD::GlobalBaseReg,
7297 DebugLoc(), PtrVT), InFlag);
7298 InFlag = Chain.getValue(1);
7300 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7303 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7305 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7307 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7308 X86::RAX, X86II::MO_TLSGD);
7311 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7312 // "local exec" model.
7313 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7314 const EVT PtrVT, TLSModel::Model model,
7316 DebugLoc dl = GA->getDebugLoc();
7318 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7319 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7320 is64Bit ? 257 : 256));
7322 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7323 DAG.getIntPtrConstant(0),
7324 MachinePointerInfo(Ptr),
7325 false, false, false, 0);
7327 unsigned char OperandFlags = 0;
7328 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7330 unsigned WrapperKind = X86ISD::Wrapper;
7331 if (model == TLSModel::LocalExec) {
7332 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7333 } else if (is64Bit) {
7334 assert(model == TLSModel::InitialExec);
7335 OperandFlags = X86II::MO_GOTTPOFF;
7336 WrapperKind = X86ISD::WrapperRIP;
7338 assert(model == TLSModel::InitialExec);
7339 OperandFlags = X86II::MO_INDNTPOFF;
7342 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7344 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7345 GA->getValueType(0),
7346 GA->getOffset(), OperandFlags);
7347 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7349 if (model == TLSModel::InitialExec)
7350 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7351 MachinePointerInfo::getGOT(), false, false, false, 0);
7353 // The address of the thread local variable is the add of the thread
7354 // pointer with the offset of the variable.
7355 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7359 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7361 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7362 const GlobalValue *GV = GA->getGlobal();
7364 if (Subtarget->isTargetELF()) {
7365 // TODO: implement the "local dynamic" model
7366 // TODO: implement the "initial exec"model for pic executables
7368 // If GV is an alias then use the aliasee for determining
7369 // thread-localness.
7370 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7371 GV = GA->resolveAliasedGlobal(false);
7373 TLSModel::Model model
7374 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7377 case TLSModel::GeneralDynamic:
7378 case TLSModel::LocalDynamic: // not implemented
7379 if (Subtarget->is64Bit())
7380 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7381 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7383 case TLSModel::InitialExec:
7384 case TLSModel::LocalExec:
7385 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7386 Subtarget->is64Bit());
7388 } else if (Subtarget->isTargetDarwin()) {
7389 // Darwin only has one model of TLS. Lower to that.
7390 unsigned char OpFlag = 0;
7391 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7392 X86ISD::WrapperRIP : X86ISD::Wrapper;
7394 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7396 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7397 !Subtarget->is64Bit();
7399 OpFlag = X86II::MO_TLVP_PIC_BASE;
7401 OpFlag = X86II::MO_TLVP;
7402 DebugLoc DL = Op.getDebugLoc();
7403 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7404 GA->getValueType(0),
7405 GA->getOffset(), OpFlag);
7406 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7408 // With PIC32, the address is actually $g + Offset.
7410 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7411 DAG.getNode(X86ISD::GlobalBaseReg,
7412 DebugLoc(), getPointerTy()),
7415 // Lowering the machine isd will make sure everything is in the right
7417 SDValue Chain = DAG.getEntryNode();
7418 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7419 SDValue Args[] = { Chain, Offset };
7420 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7422 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7423 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7424 MFI->setAdjustsStack(true);
7426 // And our return value (tls address) is in the standard call return value
7428 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7429 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7434 "TLS not implemented for this target.");
7436 llvm_unreachable("Unreachable");
7441 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7442 /// take a 2 x i32 value to shift plus a shift amount.
7443 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7444 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7445 EVT VT = Op.getValueType();
7446 unsigned VTBits = VT.getSizeInBits();
7447 DebugLoc dl = Op.getDebugLoc();
7448 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7449 SDValue ShOpLo = Op.getOperand(0);
7450 SDValue ShOpHi = Op.getOperand(1);
7451 SDValue ShAmt = Op.getOperand(2);
7452 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7453 DAG.getConstant(VTBits - 1, MVT::i8))
7454 : DAG.getConstant(0, VT);
7457 if (Op.getOpcode() == ISD::SHL_PARTS) {
7458 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7459 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7461 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7462 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7465 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7466 DAG.getConstant(VTBits, MVT::i8));
7467 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7468 AndNode, DAG.getConstant(0, MVT::i8));
7471 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7472 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7473 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7475 if (Op.getOpcode() == ISD::SHL_PARTS) {
7476 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7477 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7479 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7480 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7483 SDValue Ops[2] = { Lo, Hi };
7484 return DAG.getMergeValues(Ops, 2, dl);
7487 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7488 SelectionDAG &DAG) const {
7489 EVT SrcVT = Op.getOperand(0).getValueType();
7491 if (SrcVT.isVector())
7494 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7495 "Unknown SINT_TO_FP to lower!");
7497 // These are really Legal; return the operand so the caller accepts it as
7499 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7501 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7502 Subtarget->is64Bit()) {
7506 DebugLoc dl = Op.getDebugLoc();
7507 unsigned Size = SrcVT.getSizeInBits()/8;
7508 MachineFunction &MF = DAG.getMachineFunction();
7509 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7510 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7511 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7513 MachinePointerInfo::getFixedStack(SSFI),
7515 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7518 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7520 SelectionDAG &DAG) const {
7522 DebugLoc DL = Op.getDebugLoc();
7524 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7526 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7528 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7530 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7532 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7533 MachineMemOperand *MMO;
7535 int SSFI = FI->getIndex();
7537 DAG.getMachineFunction()
7538 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7539 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7541 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7542 StackSlot = StackSlot.getOperand(1);
7544 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7545 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7547 Tys, Ops, array_lengthof(Ops),
7551 Chain = Result.getValue(1);
7552 SDValue InFlag = Result.getValue(2);
7554 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7555 // shouldn't be necessary except that RFP cannot be live across
7556 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7557 MachineFunction &MF = DAG.getMachineFunction();
7558 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7559 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7560 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7561 Tys = DAG.getVTList(MVT::Other);
7563 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7565 MachineMemOperand *MMO =
7566 DAG.getMachineFunction()
7567 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7568 MachineMemOperand::MOStore, SSFISize, SSFISize);
7570 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7571 Ops, array_lengthof(Ops),
7572 Op.getValueType(), MMO);
7573 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7574 MachinePointerInfo::getFixedStack(SSFI),
7575 false, false, false, 0);
7581 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7582 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7583 SelectionDAG &DAG) const {
7584 // This algorithm is not obvious. Here it is in C code, more or less:
7586 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7587 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7588 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7590 // Copy ints to xmm registers.
7591 __m128i xh = _mm_cvtsi32_si128( hi );
7592 __m128i xl = _mm_cvtsi32_si128( lo );
7594 // Combine into low half of a single xmm register.
7595 __m128i x = _mm_unpacklo_epi32( xh, xl );
7599 // Merge in appropriate exponents to give the integer bits the right
7601 x = _mm_unpacklo_epi32( x, exp );
7603 // Subtract away the biases to deal with the IEEE-754 double precision
7605 d = _mm_sub_pd( (__m128d) x, bias );
7607 // All conversions up to here are exact. The correctly rounded result is
7608 // calculated using the current rounding mode using the following
7610 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7611 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7612 // store doesn't really need to be here (except
7613 // maybe to zero the other double)
7618 DebugLoc dl = Op.getDebugLoc();
7619 LLVMContext *Context = DAG.getContext();
7621 // Build some magic constants.
7622 SmallVector<Constant*,4> CV0;
7623 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7624 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7625 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7626 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7627 Constant *C0 = ConstantVector::get(CV0);
7628 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7630 SmallVector<Constant*,2> CV1;
7632 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7634 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7635 Constant *C1 = ConstantVector::get(CV1);
7636 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7638 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7639 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7641 DAG.getIntPtrConstant(1)));
7642 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7643 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7645 DAG.getIntPtrConstant(0)));
7646 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7647 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7648 MachinePointerInfo::getConstantPool(),
7649 false, false, false, 16);
7650 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7651 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7652 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7653 MachinePointerInfo::getConstantPool(),
7654 false, false, false, 16);
7655 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7657 // Add the halves; easiest way is to swap them into another reg first.
7658 int ShufMask[2] = { 1, -1 };
7659 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7660 DAG.getUNDEF(MVT::v2f64), ShufMask);
7661 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7662 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7663 DAG.getIntPtrConstant(0));
7666 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7667 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7668 SelectionDAG &DAG) const {
7669 DebugLoc dl = Op.getDebugLoc();
7670 // FP constant to bias correct the final result.
7671 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7674 // Load the 32-bit value into an XMM register.
7675 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7678 // Zero out the upper parts of the register.
7679 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7682 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7683 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7684 DAG.getIntPtrConstant(0));
7686 // Or the load with the bias.
7687 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7688 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7689 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7691 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7692 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7693 MVT::v2f64, Bias)));
7694 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7695 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7696 DAG.getIntPtrConstant(0));
7698 // Subtract the bias.
7699 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7701 // Handle final rounding.
7702 EVT DestVT = Op.getValueType();
7704 if (DestVT.bitsLT(MVT::f64)) {
7705 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7706 DAG.getIntPtrConstant(0));
7707 } else if (DestVT.bitsGT(MVT::f64)) {
7708 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7711 // Handle final rounding.
7715 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7716 SelectionDAG &DAG) const {
7717 SDValue N0 = Op.getOperand(0);
7718 DebugLoc dl = Op.getDebugLoc();
7720 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7721 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7722 // the optimization here.
7723 if (DAG.SignBitIsZero(N0))
7724 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7726 EVT SrcVT = N0.getValueType();
7727 EVT DstVT = Op.getValueType();
7728 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7729 return LowerUINT_TO_FP_i64(Op, DAG);
7730 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7731 return LowerUINT_TO_FP_i32(Op, DAG);
7733 // Make a 64-bit buffer, and use it to build an FILD.
7734 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7735 if (SrcVT == MVT::i32) {
7736 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7737 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7738 getPointerTy(), StackSlot, WordOff);
7739 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7740 StackSlot, MachinePointerInfo(),
7742 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7743 OffsetSlot, MachinePointerInfo(),
7745 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7749 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7750 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7751 StackSlot, MachinePointerInfo(),
7753 // For i64 source, we need to add the appropriate power of 2 if the input
7754 // was negative. This is the same as the optimization in
7755 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7756 // we must be careful to do the computation in x87 extended precision, not
7757 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7758 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7759 MachineMemOperand *MMO =
7760 DAG.getMachineFunction()
7761 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7762 MachineMemOperand::MOLoad, 8, 8);
7764 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7765 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7766 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7769 APInt FF(32, 0x5F800000ULL);
7771 // Check whether the sign bit is set.
7772 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7773 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7776 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7777 SDValue FudgePtr = DAG.getConstantPool(
7778 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7781 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7782 SDValue Zero = DAG.getIntPtrConstant(0);
7783 SDValue Four = DAG.getIntPtrConstant(4);
7784 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7786 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7788 // Load the value out, extending it from f32 to f80.
7789 // FIXME: Avoid the extend by constructing the right constant pool?
7790 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7791 FudgePtr, MachinePointerInfo::getConstantPool(),
7792 MVT::f32, false, false, 4);
7793 // Extend everything to 80 bits to force it to be done on x87.
7794 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7795 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7798 std::pair<SDValue,SDValue> X86TargetLowering::
7799 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7800 DebugLoc DL = Op.getDebugLoc();
7802 EVT DstTy = Op.getValueType();
7805 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7809 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7810 DstTy.getSimpleVT() >= MVT::i16 &&
7811 "Unknown FP_TO_SINT to lower!");
7813 // These are really Legal.
7814 if (DstTy == MVT::i32 &&
7815 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7816 return std::make_pair(SDValue(), SDValue());
7817 if (Subtarget->is64Bit() &&
7818 DstTy == MVT::i64 &&
7819 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7820 return std::make_pair(SDValue(), SDValue());
7822 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7824 MachineFunction &MF = DAG.getMachineFunction();
7825 unsigned MemSize = DstTy.getSizeInBits()/8;
7826 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7827 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7832 switch (DstTy.getSimpleVT().SimpleTy) {
7833 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7834 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7835 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7836 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7839 SDValue Chain = DAG.getEntryNode();
7840 SDValue Value = Op.getOperand(0);
7841 EVT TheVT = Op.getOperand(0).getValueType();
7842 if (isScalarFPTypeInSSEReg(TheVT)) {
7843 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7844 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7845 MachinePointerInfo::getFixedStack(SSFI),
7847 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7849 Chain, StackSlot, DAG.getValueType(TheVT)
7852 MachineMemOperand *MMO =
7853 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7854 MachineMemOperand::MOLoad, MemSize, MemSize);
7855 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7857 Chain = Value.getValue(1);
7858 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7859 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7862 MachineMemOperand *MMO =
7863 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7864 MachineMemOperand::MOStore, MemSize, MemSize);
7866 // Build the FP_TO_INT*_IN_MEM
7867 SDValue Ops[] = { Chain, Value, StackSlot };
7868 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7869 Ops, 3, DstTy, MMO);
7871 return std::make_pair(FIST, StackSlot);
7874 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7875 SelectionDAG &DAG) const {
7876 if (Op.getValueType().isVector())
7879 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7880 SDValue FIST = Vals.first, StackSlot = Vals.second;
7881 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7882 if (FIST.getNode() == 0) return Op;
7885 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7886 FIST, StackSlot, MachinePointerInfo(),
7887 false, false, false, 0);
7890 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7891 SelectionDAG &DAG) const {
7892 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7893 SDValue FIST = Vals.first, StackSlot = Vals.second;
7894 assert(FIST.getNode() && "Unexpected failure");
7897 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7898 FIST, StackSlot, MachinePointerInfo(),
7899 false, false, false, 0);
7902 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7903 SelectionDAG &DAG) const {
7904 LLVMContext *Context = DAG.getContext();
7905 DebugLoc dl = Op.getDebugLoc();
7906 EVT VT = Op.getValueType();
7909 EltVT = VT.getVectorElementType();
7910 SmallVector<Constant*,4> CV;
7911 if (EltVT == MVT::f64) {
7912 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7915 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7918 Constant *C = ConstantVector::get(CV);
7919 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7920 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7921 MachinePointerInfo::getConstantPool(),
7922 false, false, false, 16);
7923 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7926 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7927 LLVMContext *Context = DAG.getContext();
7928 DebugLoc dl = Op.getDebugLoc();
7929 EVT VT = Op.getValueType();
7931 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7932 if (VT.isVector()) {
7933 EltVT = VT.getVectorElementType();
7934 NumElts = VT.getVectorNumElements();
7936 SmallVector<Constant*,8> CV;
7937 if (EltVT == MVT::f64) {
7938 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7939 CV.assign(NumElts, C);
7941 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7942 CV.assign(NumElts, C);
7944 Constant *C = ConstantVector::get(CV);
7945 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7946 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7947 MachinePointerInfo::getConstantPool(),
7948 false, false, false, 16);
7949 if (VT.isVector()) {
7950 MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7951 return DAG.getNode(ISD::BITCAST, dl, VT,
7952 DAG.getNode(ISD::XOR, dl, XORVT,
7953 DAG.getNode(ISD::BITCAST, dl, XORVT,
7955 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7957 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7961 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7962 LLVMContext *Context = DAG.getContext();
7963 SDValue Op0 = Op.getOperand(0);
7964 SDValue Op1 = Op.getOperand(1);
7965 DebugLoc dl = Op.getDebugLoc();
7966 EVT VT = Op.getValueType();
7967 EVT SrcVT = Op1.getValueType();
7969 // If second operand is smaller, extend it first.
7970 if (SrcVT.bitsLT(VT)) {
7971 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7974 // And if it is bigger, shrink it first.
7975 if (SrcVT.bitsGT(VT)) {
7976 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7980 // At this point the operands and the result should have the same
7981 // type, and that won't be f80 since that is not custom lowered.
7983 // First get the sign bit of second operand.
7984 SmallVector<Constant*,4> CV;
7985 if (SrcVT == MVT::f64) {
7986 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7987 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7989 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7990 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7991 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7992 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7994 Constant *C = ConstantVector::get(CV);
7995 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7996 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7997 MachinePointerInfo::getConstantPool(),
7998 false, false, false, 16);
7999 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8001 // Shift sign bit right or left if the two operands have different types.
8002 if (SrcVT.bitsGT(VT)) {
8003 // Op0 is MVT::f32, Op1 is MVT::f64.
8004 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8005 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8006 DAG.getConstant(32, MVT::i32));
8007 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8008 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8009 DAG.getIntPtrConstant(0));
8012 // Clear first operand sign bit.
8014 if (VT == MVT::f64) {
8015 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8016 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8018 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8019 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8020 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8021 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8023 C = ConstantVector::get(CV);
8024 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8025 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8026 MachinePointerInfo::getConstantPool(),
8027 false, false, false, 16);
8028 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8030 // Or the value with the sign bit.
8031 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8034 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8035 SDValue N0 = Op.getOperand(0);
8036 DebugLoc dl = Op.getDebugLoc();
8037 EVT VT = Op.getValueType();
8039 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8040 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8041 DAG.getConstant(1, VT));
8042 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8045 /// Emit nodes that will be selected as "test Op0,Op0", or something
8047 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8048 SelectionDAG &DAG) const {
8049 DebugLoc dl = Op.getDebugLoc();
8051 // CF and OF aren't always set the way we want. Determine which
8052 // of these we need.
8053 bool NeedCF = false;
8054 bool NeedOF = false;
8057 case X86::COND_A: case X86::COND_AE:
8058 case X86::COND_B: case X86::COND_BE:
8061 case X86::COND_G: case X86::COND_GE:
8062 case X86::COND_L: case X86::COND_LE:
8063 case X86::COND_O: case X86::COND_NO:
8068 // See if we can use the EFLAGS value from the operand instead of
8069 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8070 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8071 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8072 // Emit a CMP with 0, which is the TEST pattern.
8073 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8074 DAG.getConstant(0, Op.getValueType()));
8076 unsigned Opcode = 0;
8077 unsigned NumOperands = 0;
8078 switch (Op.getNode()->getOpcode()) {
8080 // Due to an isel shortcoming, be conservative if this add is likely to be
8081 // selected as part of a load-modify-store instruction. When the root node
8082 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8083 // uses of other nodes in the match, such as the ADD in this case. This
8084 // leads to the ADD being left around and reselected, with the result being
8085 // two adds in the output. Alas, even if none our users are stores, that
8086 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8087 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8088 // climbing the DAG back to the root, and it doesn't seem to be worth the
8090 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8091 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8092 if (UI->getOpcode() != ISD::CopyToReg &&
8093 UI->getOpcode() != ISD::SETCC &&
8094 UI->getOpcode() != ISD::STORE)
8097 if (ConstantSDNode *C =
8098 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8099 // An add of one will be selected as an INC.
8100 if (C->getAPIntValue() == 1) {
8101 Opcode = X86ISD::INC;
8106 // An add of negative one (subtract of one) will be selected as a DEC.
8107 if (C->getAPIntValue().isAllOnesValue()) {
8108 Opcode = X86ISD::DEC;
8114 // Otherwise use a regular EFLAGS-setting add.
8115 Opcode = X86ISD::ADD;
8119 // If the primary and result isn't used, don't bother using X86ISD::AND,
8120 // because a TEST instruction will be better.
8121 bool NonFlagUse = false;
8122 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8123 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8125 unsigned UOpNo = UI.getOperandNo();
8126 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8127 // Look pass truncate.
8128 UOpNo = User->use_begin().getOperandNo();
8129 User = *User->use_begin();
8132 if (User->getOpcode() != ISD::BRCOND &&
8133 User->getOpcode() != ISD::SETCC &&
8134 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8147 // Due to the ISEL shortcoming noted above, be conservative if this op is
8148 // likely to be selected as part of a load-modify-store instruction.
8149 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8150 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8151 if (UI->getOpcode() == ISD::STORE)
8154 // Otherwise use a regular EFLAGS-setting instruction.
8155 switch (Op.getNode()->getOpcode()) {
8156 default: llvm_unreachable("unexpected operator!");
8157 case ISD::SUB: Opcode = X86ISD::SUB; break;
8158 case ISD::OR: Opcode = X86ISD::OR; break;
8159 case ISD::XOR: Opcode = X86ISD::XOR; break;
8160 case ISD::AND: Opcode = X86ISD::AND; break;
8172 return SDValue(Op.getNode(), 1);
8179 // Emit a CMP with 0, which is the TEST pattern.
8180 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8181 DAG.getConstant(0, Op.getValueType()));
8183 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8184 SmallVector<SDValue, 4> Ops;
8185 for (unsigned i = 0; i != NumOperands; ++i)
8186 Ops.push_back(Op.getOperand(i));
8188 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8189 DAG.ReplaceAllUsesWith(Op, New);
8190 return SDValue(New.getNode(), 1);
8193 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8195 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8196 SelectionDAG &DAG) const {
8197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8198 if (C->getAPIntValue() == 0)
8199 return EmitTest(Op0, X86CC, DAG);
8201 DebugLoc dl = Op0.getDebugLoc();
8202 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8205 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8206 /// if it's possible.
8207 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8208 DebugLoc dl, SelectionDAG &DAG) const {
8209 SDValue Op0 = And.getOperand(0);
8210 SDValue Op1 = And.getOperand(1);
8211 if (Op0.getOpcode() == ISD::TRUNCATE)
8212 Op0 = Op0.getOperand(0);
8213 if (Op1.getOpcode() == ISD::TRUNCATE)
8214 Op1 = Op1.getOperand(0);
8217 if (Op1.getOpcode() == ISD::SHL)
8218 std::swap(Op0, Op1);
8219 if (Op0.getOpcode() == ISD::SHL) {
8220 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8221 if (And00C->getZExtValue() == 1) {
8222 // If we looked past a truncate, check that it's only truncating away
8224 unsigned BitWidth = Op0.getValueSizeInBits();
8225 unsigned AndBitWidth = And.getValueSizeInBits();
8226 if (BitWidth > AndBitWidth) {
8227 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8228 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8229 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8233 RHS = Op0.getOperand(1);
8235 } else if (Op1.getOpcode() == ISD::Constant) {
8236 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8237 uint64_t AndRHSVal = AndRHS->getZExtValue();
8238 SDValue AndLHS = Op0;
8240 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8241 LHS = AndLHS.getOperand(0);
8242 RHS = AndLHS.getOperand(1);
8245 // Use BT if the immediate can't be encoded in a TEST instruction.
8246 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8248 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8252 if (LHS.getNode()) {
8253 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8254 // instruction. Since the shift amount is in-range-or-undefined, we know
8255 // that doing a bittest on the i32 value is ok. We extend to i32 because
8256 // the encoding for the i16 version is larger than the i32 version.
8257 // Also promote i16 to i32 for performance / code size reason.
8258 if (LHS.getValueType() == MVT::i8 ||
8259 LHS.getValueType() == MVT::i16)
8260 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8262 // If the operand types disagree, extend the shift amount to match. Since
8263 // BT ignores high bits (like shifts) we can use anyextend.
8264 if (LHS.getValueType() != RHS.getValueType())
8265 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8267 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8268 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8269 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8270 DAG.getConstant(Cond, MVT::i8), BT);
8276 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8278 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8280 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8281 SDValue Op0 = Op.getOperand(0);
8282 SDValue Op1 = Op.getOperand(1);
8283 DebugLoc dl = Op.getDebugLoc();
8284 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8286 // Optimize to BT if possible.
8287 // Lower (X & (1 << N)) == 0 to BT(X, N).
8288 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8289 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8290 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8291 Op1.getOpcode() == ISD::Constant &&
8292 cast<ConstantSDNode>(Op1)->isNullValue() &&
8293 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8294 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8295 if (NewSetCC.getNode())
8299 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8301 if (Op1.getOpcode() == ISD::Constant &&
8302 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8303 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8304 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8306 // If the input is a setcc, then reuse the input setcc or use a new one with
8307 // the inverted condition.
8308 if (Op0.getOpcode() == X86ISD::SETCC) {
8309 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8310 bool Invert = (CC == ISD::SETNE) ^
8311 cast<ConstantSDNode>(Op1)->isNullValue();
8312 if (!Invert) return Op0;
8314 CCode = X86::GetOppositeBranchCondition(CCode);
8315 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8316 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8320 bool isFP = Op1.getValueType().isFloatingPoint();
8321 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8322 if (X86CC == X86::COND_INVALID)
8325 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8326 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8327 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8330 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8331 // ones, and then concatenate the result back.
8332 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8333 EVT VT = Op.getValueType();
8335 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8336 "Unsupported value type for operation");
8338 int NumElems = VT.getVectorNumElements();
8339 DebugLoc dl = Op.getDebugLoc();
8340 SDValue CC = Op.getOperand(2);
8341 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8342 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8344 // Extract the LHS vectors
8345 SDValue LHS = Op.getOperand(0);
8346 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8347 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8349 // Extract the RHS vectors
8350 SDValue RHS = Op.getOperand(1);
8351 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8352 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8354 // Issue the operation on the smaller types and concatenate the result back
8355 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8356 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8357 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8358 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8359 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8363 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8365 SDValue Op0 = Op.getOperand(0);
8366 SDValue Op1 = Op.getOperand(1);
8367 SDValue CC = Op.getOperand(2);
8368 EVT VT = Op.getValueType();
8369 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8370 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8371 DebugLoc dl = Op.getDebugLoc();
8375 EVT EltVT = Op0.getValueType().getVectorElementType();
8376 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8378 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8381 // SSE Condition code mapping:
8390 switch (SetCCOpcode) {
8393 case ISD::SETEQ: SSECC = 0; break;
8395 case ISD::SETGT: Swap = true; // Fallthrough
8397 case ISD::SETOLT: SSECC = 1; break;
8399 case ISD::SETGE: Swap = true; // Fallthrough
8401 case ISD::SETOLE: SSECC = 2; break;
8402 case ISD::SETUO: SSECC = 3; break;
8404 case ISD::SETNE: SSECC = 4; break;
8405 case ISD::SETULE: Swap = true;
8406 case ISD::SETUGE: SSECC = 5; break;
8407 case ISD::SETULT: Swap = true;
8408 case ISD::SETUGT: SSECC = 6; break;
8409 case ISD::SETO: SSECC = 7; break;
8412 std::swap(Op0, Op1);
8414 // In the two special cases we can't handle, emit two comparisons.
8416 if (SetCCOpcode == ISD::SETUEQ) {
8418 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8419 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8420 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8421 } else if (SetCCOpcode == ISD::SETONE) {
8423 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8424 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8425 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8427 llvm_unreachable("Illegal FP comparison");
8429 // Handle all other FP comparisons here.
8430 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8433 // Break 256-bit integer vector compare into smaller ones.
8434 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8435 return Lower256IntVSETCC(Op, DAG);
8437 // We are handling one of the integer comparisons here. Since SSE only has
8438 // GT and EQ comparisons for integer, swapping operands and multiple
8439 // operations may be required for some comparisons.
8440 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8441 bool Swap = false, Invert = false, FlipSigns = false;
8443 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8445 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8446 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8447 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8448 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8451 switch (SetCCOpcode) {
8453 case ISD::SETNE: Invert = true;
8454 case ISD::SETEQ: Opc = EQOpc; break;
8455 case ISD::SETLT: Swap = true;
8456 case ISD::SETGT: Opc = GTOpc; break;
8457 case ISD::SETGE: Swap = true;
8458 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8459 case ISD::SETULT: Swap = true;
8460 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8461 case ISD::SETUGE: Swap = true;
8462 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8465 std::swap(Op0, Op1);
8467 // Check that the operation in question is available (most are plain SSE2,
8468 // but PCMPGTQ and PCMPEQQ have different requirements).
8469 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8471 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8474 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8475 // bits of the inputs before performing those operations.
8477 EVT EltVT = VT.getVectorElementType();
8478 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8480 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8481 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8483 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8484 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8487 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8489 // If the logical-not of the result is required, perform that now.
8491 Result = DAG.getNOT(dl, Result, VT);
8496 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8497 static bool isX86LogicalCmp(SDValue Op) {
8498 unsigned Opc = Op.getNode()->getOpcode();
8499 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8501 if (Op.getResNo() == 1 &&
8502 (Opc == X86ISD::ADD ||
8503 Opc == X86ISD::SUB ||
8504 Opc == X86ISD::ADC ||
8505 Opc == X86ISD::SBB ||
8506 Opc == X86ISD::SMUL ||
8507 Opc == X86ISD::UMUL ||
8508 Opc == X86ISD::INC ||
8509 Opc == X86ISD::DEC ||
8510 Opc == X86ISD::OR ||
8511 Opc == X86ISD::XOR ||
8512 Opc == X86ISD::AND))
8515 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8521 static bool isZero(SDValue V) {
8522 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8523 return C && C->isNullValue();
8526 static bool isAllOnes(SDValue V) {
8527 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8528 return C && C->isAllOnesValue();
8531 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8532 bool addTest = true;
8533 SDValue Cond = Op.getOperand(0);
8534 SDValue Op1 = Op.getOperand(1);
8535 SDValue Op2 = Op.getOperand(2);
8536 DebugLoc DL = Op.getDebugLoc();
8539 if (Cond.getOpcode() == ISD::SETCC) {
8540 SDValue NewCond = LowerSETCC(Cond, DAG);
8541 if (NewCond.getNode())
8545 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8546 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8547 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8548 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8549 if (Cond.getOpcode() == X86ISD::SETCC &&
8550 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8551 isZero(Cond.getOperand(1).getOperand(1))) {
8552 SDValue Cmp = Cond.getOperand(1);
8554 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8556 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8557 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8558 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8560 SDValue CmpOp0 = Cmp.getOperand(0);
8561 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8562 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8564 SDValue Res = // Res = 0 or -1.
8565 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8566 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8568 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8569 Res = DAG.getNOT(DL, Res, Res.getValueType());
8571 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8572 if (N2C == 0 || !N2C->isNullValue())
8573 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8578 // Look past (and (setcc_carry (cmp ...)), 1).
8579 if (Cond.getOpcode() == ISD::AND &&
8580 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8581 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8582 if (C && C->getAPIntValue() == 1)
8583 Cond = Cond.getOperand(0);
8586 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8587 // setting operand in place of the X86ISD::SETCC.
8588 unsigned CondOpcode = Cond.getOpcode();
8589 if (CondOpcode == X86ISD::SETCC ||
8590 CondOpcode == X86ISD::SETCC_CARRY) {
8591 CC = Cond.getOperand(0);
8593 SDValue Cmp = Cond.getOperand(1);
8594 unsigned Opc = Cmp.getOpcode();
8595 EVT VT = Op.getValueType();
8597 bool IllegalFPCMov = false;
8598 if (VT.isFloatingPoint() && !VT.isVector() &&
8599 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8600 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8602 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8603 Opc == X86ISD::BT) { // FIXME
8607 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8608 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8609 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8610 Cond.getOperand(0).getValueType() != MVT::i8)) {
8611 SDValue LHS = Cond.getOperand(0);
8612 SDValue RHS = Cond.getOperand(1);
8616 switch (CondOpcode) {
8617 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8618 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8619 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8620 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8621 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8622 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8623 default: llvm_unreachable("unexpected overflowing operator");
8625 if (CondOpcode == ISD::UMULO)
8626 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8629 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8631 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8633 if (CondOpcode == ISD::UMULO)
8634 Cond = X86Op.getValue(2);
8636 Cond = X86Op.getValue(1);
8638 CC = DAG.getConstant(X86Cond, MVT::i8);
8643 // Look pass the truncate.
8644 if (Cond.getOpcode() == ISD::TRUNCATE)
8645 Cond = Cond.getOperand(0);
8647 // We know the result of AND is compared against zero. Try to match
8649 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8650 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8651 if (NewSetCC.getNode()) {
8652 CC = NewSetCC.getOperand(0);
8653 Cond = NewSetCC.getOperand(1);
8660 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8661 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8664 // a < b ? -1 : 0 -> RES = ~setcc_carry
8665 // a < b ? 0 : -1 -> RES = setcc_carry
8666 // a >= b ? -1 : 0 -> RES = setcc_carry
8667 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8668 if (Cond.getOpcode() == X86ISD::CMP) {
8669 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8671 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8672 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8673 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8674 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8675 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8676 return DAG.getNOT(DL, Res, Res.getValueType());
8681 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8682 // condition is true.
8683 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8684 SDValue Ops[] = { Op2, Op1, CC, Cond };
8685 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8688 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8689 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8690 // from the AND / OR.
8691 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8692 Opc = Op.getOpcode();
8693 if (Opc != ISD::OR && Opc != ISD::AND)
8695 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8696 Op.getOperand(0).hasOneUse() &&
8697 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8698 Op.getOperand(1).hasOneUse());
8701 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8702 // 1 and that the SETCC node has a single use.
8703 static bool isXor1OfSetCC(SDValue Op) {
8704 if (Op.getOpcode() != ISD::XOR)
8706 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8707 if (N1C && N1C->getAPIntValue() == 1) {
8708 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8709 Op.getOperand(0).hasOneUse();
8714 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8715 bool addTest = true;
8716 SDValue Chain = Op.getOperand(0);
8717 SDValue Cond = Op.getOperand(1);
8718 SDValue Dest = Op.getOperand(2);
8719 DebugLoc dl = Op.getDebugLoc();
8721 bool Inverted = false;
8723 if (Cond.getOpcode() == ISD::SETCC) {
8724 // Check for setcc([su]{add,sub,mul}o == 0).
8725 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8726 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8727 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8728 Cond.getOperand(0).getResNo() == 1 &&
8729 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8730 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8731 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8732 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8733 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8734 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8736 Cond = Cond.getOperand(0);
8738 SDValue NewCond = LowerSETCC(Cond, DAG);
8739 if (NewCond.getNode())
8744 // FIXME: LowerXALUO doesn't handle these!!
8745 else if (Cond.getOpcode() == X86ISD::ADD ||
8746 Cond.getOpcode() == X86ISD::SUB ||
8747 Cond.getOpcode() == X86ISD::SMUL ||
8748 Cond.getOpcode() == X86ISD::UMUL)
8749 Cond = LowerXALUO(Cond, DAG);
8752 // Look pass (and (setcc_carry (cmp ...)), 1).
8753 if (Cond.getOpcode() == ISD::AND &&
8754 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8755 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8756 if (C && C->getAPIntValue() == 1)
8757 Cond = Cond.getOperand(0);
8760 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8761 // setting operand in place of the X86ISD::SETCC.
8762 unsigned CondOpcode = Cond.getOpcode();
8763 if (CondOpcode == X86ISD::SETCC ||
8764 CondOpcode == X86ISD::SETCC_CARRY) {
8765 CC = Cond.getOperand(0);
8767 SDValue Cmp = Cond.getOperand(1);
8768 unsigned Opc = Cmp.getOpcode();
8769 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8770 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8774 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8778 // These can only come from an arithmetic instruction with overflow,
8779 // e.g. SADDO, UADDO.
8780 Cond = Cond.getNode()->getOperand(1);
8786 CondOpcode = Cond.getOpcode();
8787 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8788 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8789 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8790 Cond.getOperand(0).getValueType() != MVT::i8)) {
8791 SDValue LHS = Cond.getOperand(0);
8792 SDValue RHS = Cond.getOperand(1);
8796 switch (CondOpcode) {
8797 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8798 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8799 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8800 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8801 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8802 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8803 default: llvm_unreachable("unexpected overflowing operator");
8806 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8807 if (CondOpcode == ISD::UMULO)
8808 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8811 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8813 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8815 if (CondOpcode == ISD::UMULO)
8816 Cond = X86Op.getValue(2);
8818 Cond = X86Op.getValue(1);
8820 CC = DAG.getConstant(X86Cond, MVT::i8);
8824 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8825 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8826 if (CondOpc == ISD::OR) {
8827 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8828 // two branches instead of an explicit OR instruction with a
8830 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8831 isX86LogicalCmp(Cmp)) {
8832 CC = Cond.getOperand(0).getOperand(0);
8833 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8834 Chain, Dest, CC, Cmp);
8835 CC = Cond.getOperand(1).getOperand(0);
8839 } else { // ISD::AND
8840 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8841 // two branches instead of an explicit AND instruction with a
8842 // separate test. However, we only do this if this block doesn't
8843 // have a fall-through edge, because this requires an explicit
8844 // jmp when the condition is false.
8845 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8846 isX86LogicalCmp(Cmp) &&
8847 Op.getNode()->hasOneUse()) {
8848 X86::CondCode CCode =
8849 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8850 CCode = X86::GetOppositeBranchCondition(CCode);
8851 CC = DAG.getConstant(CCode, MVT::i8);
8852 SDNode *User = *Op.getNode()->use_begin();
8853 // Look for an unconditional branch following this conditional branch.
8854 // We need this because we need to reverse the successors in order
8855 // to implement FCMP_OEQ.
8856 if (User->getOpcode() == ISD::BR) {
8857 SDValue FalseBB = User->getOperand(1);
8859 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8860 assert(NewBR == User);
8864 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8865 Chain, Dest, CC, Cmp);
8866 X86::CondCode CCode =
8867 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8868 CCode = X86::GetOppositeBranchCondition(CCode);
8869 CC = DAG.getConstant(CCode, MVT::i8);
8875 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8876 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8877 // It should be transformed during dag combiner except when the condition
8878 // is set by a arithmetics with overflow node.
8879 X86::CondCode CCode =
8880 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8881 CCode = X86::GetOppositeBranchCondition(CCode);
8882 CC = DAG.getConstant(CCode, MVT::i8);
8883 Cond = Cond.getOperand(0).getOperand(1);
8885 } else if (Cond.getOpcode() == ISD::SETCC &&
8886 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8887 // For FCMP_OEQ, we can emit
8888 // two branches instead of an explicit AND instruction with a
8889 // separate test. However, we only do this if this block doesn't
8890 // have a fall-through edge, because this requires an explicit
8891 // jmp when the condition is false.
8892 if (Op.getNode()->hasOneUse()) {
8893 SDNode *User = *Op.getNode()->use_begin();
8894 // Look for an unconditional branch following this conditional branch.
8895 // We need this because we need to reverse the successors in order
8896 // to implement FCMP_OEQ.
8897 if (User->getOpcode() == ISD::BR) {
8898 SDValue FalseBB = User->getOperand(1);
8900 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8901 assert(NewBR == User);
8905 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8906 Cond.getOperand(0), Cond.getOperand(1));
8907 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8908 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8909 Chain, Dest, CC, Cmp);
8910 CC = DAG.getConstant(X86::COND_P, MVT::i8);
8915 } else if (Cond.getOpcode() == ISD::SETCC &&
8916 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8917 // For FCMP_UNE, we can emit
8918 // two branches instead of an explicit AND instruction with a
8919 // separate test. However, we only do this if this block doesn't
8920 // have a fall-through edge, because this requires an explicit
8921 // jmp when the condition is false.
8922 if (Op.getNode()->hasOneUse()) {
8923 SDNode *User = *Op.getNode()->use_begin();
8924 // Look for an unconditional branch following this conditional branch.
8925 // We need this because we need to reverse the successors in order
8926 // to implement FCMP_UNE.
8927 if (User->getOpcode() == ISD::BR) {
8928 SDValue FalseBB = User->getOperand(1);
8930 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8931 assert(NewBR == User);
8934 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8935 Cond.getOperand(0), Cond.getOperand(1));
8936 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8937 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8938 Chain, Dest, CC, Cmp);
8939 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8949 // Look pass the truncate.
8950 if (Cond.getOpcode() == ISD::TRUNCATE)
8951 Cond = Cond.getOperand(0);
8953 // We know the result of AND is compared against zero. Try to match
8955 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8956 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8957 if (NewSetCC.getNode()) {
8958 CC = NewSetCC.getOperand(0);
8959 Cond = NewSetCC.getOperand(1);
8966 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8967 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8969 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8970 Chain, Dest, CC, Cond);
8974 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8975 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8976 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8977 // that the guard pages used by the OS virtual memory manager are allocated in
8978 // correct sequence.
8980 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8981 SelectionDAG &DAG) const {
8982 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8983 getTargetMachine().Options.EnableSegmentedStacks) &&
8984 "This should be used only on Windows targets or when segmented stacks "
8986 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8987 DebugLoc dl = Op.getDebugLoc();
8990 SDValue Chain = Op.getOperand(0);
8991 SDValue Size = Op.getOperand(1);
8992 // FIXME: Ensure alignment here
8994 bool Is64Bit = Subtarget->is64Bit();
8995 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8997 if (getTargetMachine().Options.EnableSegmentedStacks) {
8998 MachineFunction &MF = DAG.getMachineFunction();
8999 MachineRegisterInfo &MRI = MF.getRegInfo();
9002 // The 64 bit implementation of segmented stacks needs to clobber both r10
9003 // r11. This makes it impossible to use it along with nested parameters.
9004 const Function *F = MF.getFunction();
9006 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9008 if (I->hasNestAttr())
9009 report_fatal_error("Cannot use segmented stacks with functions that "
9010 "have nested arguments.");
9013 const TargetRegisterClass *AddrRegClass =
9014 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9015 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9016 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9017 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9018 DAG.getRegister(Vreg, SPTy));
9019 SDValue Ops1[2] = { Value, Chain };
9020 return DAG.getMergeValues(Ops1, 2, dl);
9023 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9025 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9026 Flag = Chain.getValue(1);
9027 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9029 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9030 Flag = Chain.getValue(1);
9032 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9034 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9035 return DAG.getMergeValues(Ops1, 2, dl);
9039 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9040 MachineFunction &MF = DAG.getMachineFunction();
9041 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9043 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9044 DebugLoc DL = Op.getDebugLoc();
9046 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9047 // vastart just stores the address of the VarArgsFrameIndex slot into the
9048 // memory location argument.
9049 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9051 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9052 MachinePointerInfo(SV), false, false, 0);
9056 // gp_offset (0 - 6 * 8)
9057 // fp_offset (48 - 48 + 8 * 16)
9058 // overflow_arg_area (point to parameters coming in memory).
9060 SmallVector<SDValue, 8> MemOps;
9061 SDValue FIN = Op.getOperand(1);
9063 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9064 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9066 FIN, MachinePointerInfo(SV), false, false, 0);
9067 MemOps.push_back(Store);
9070 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9071 FIN, DAG.getIntPtrConstant(4));
9072 Store = DAG.getStore(Op.getOperand(0), DL,
9073 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9075 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9076 MemOps.push_back(Store);
9078 // Store ptr to overflow_arg_area
9079 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9080 FIN, DAG.getIntPtrConstant(4));
9081 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9083 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9084 MachinePointerInfo(SV, 8),
9086 MemOps.push_back(Store);
9088 // Store ptr to reg_save_area.
9089 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9090 FIN, DAG.getIntPtrConstant(8));
9091 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9093 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9094 MachinePointerInfo(SV, 16), false, false, 0);
9095 MemOps.push_back(Store);
9096 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9097 &MemOps[0], MemOps.size());
9100 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9101 assert(Subtarget->is64Bit() &&
9102 "LowerVAARG only handles 64-bit va_arg!");
9103 assert((Subtarget->isTargetLinux() ||
9104 Subtarget->isTargetDarwin()) &&
9105 "Unhandled target in LowerVAARG");
9106 assert(Op.getNode()->getNumOperands() == 4);
9107 SDValue Chain = Op.getOperand(0);
9108 SDValue SrcPtr = Op.getOperand(1);
9109 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9110 unsigned Align = Op.getConstantOperandVal(3);
9111 DebugLoc dl = Op.getDebugLoc();
9113 EVT ArgVT = Op.getNode()->getValueType(0);
9114 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9115 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9118 // Decide which area this value should be read from.
9119 // TODO: Implement the AMD64 ABI in its entirety. This simple
9120 // selection mechanism works only for the basic types.
9121 if (ArgVT == MVT::f80) {
9122 llvm_unreachable("va_arg for f80 not yet implemented");
9123 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9124 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9125 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9126 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9128 llvm_unreachable("Unhandled argument type in LowerVAARG");
9132 // Sanity Check: Make sure using fp_offset makes sense.
9133 assert(!getTargetMachine().Options.UseSoftFloat &&
9134 !(DAG.getMachineFunction()
9135 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9136 Subtarget->hasXMM());
9139 // Insert VAARG_64 node into the DAG
9140 // VAARG_64 returns two values: Variable Argument Address, Chain
9141 SmallVector<SDValue, 11> InstOps;
9142 InstOps.push_back(Chain);
9143 InstOps.push_back(SrcPtr);
9144 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9145 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9146 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9147 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9148 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9149 VTs, &InstOps[0], InstOps.size(),
9151 MachinePointerInfo(SV),
9156 Chain = VAARG.getValue(1);
9158 // Load the next argument and return it
9159 return DAG.getLoad(ArgVT, dl,
9162 MachinePointerInfo(),
9163 false, false, false, 0);
9166 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9167 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9168 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9169 SDValue Chain = Op.getOperand(0);
9170 SDValue DstPtr = Op.getOperand(1);
9171 SDValue SrcPtr = Op.getOperand(2);
9172 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9173 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9174 DebugLoc DL = Op.getDebugLoc();
9176 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9177 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9179 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9183 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9184 DebugLoc dl = Op.getDebugLoc();
9185 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9187 default: return SDValue(); // Don't custom lower most intrinsics.
9188 // Comparison intrinsics.
9189 case Intrinsic::x86_sse_comieq_ss:
9190 case Intrinsic::x86_sse_comilt_ss:
9191 case Intrinsic::x86_sse_comile_ss:
9192 case Intrinsic::x86_sse_comigt_ss:
9193 case Intrinsic::x86_sse_comige_ss:
9194 case Intrinsic::x86_sse_comineq_ss:
9195 case Intrinsic::x86_sse_ucomieq_ss:
9196 case Intrinsic::x86_sse_ucomilt_ss:
9197 case Intrinsic::x86_sse_ucomile_ss:
9198 case Intrinsic::x86_sse_ucomigt_ss:
9199 case Intrinsic::x86_sse_ucomige_ss:
9200 case Intrinsic::x86_sse_ucomineq_ss:
9201 case Intrinsic::x86_sse2_comieq_sd:
9202 case Intrinsic::x86_sse2_comilt_sd:
9203 case Intrinsic::x86_sse2_comile_sd:
9204 case Intrinsic::x86_sse2_comigt_sd:
9205 case Intrinsic::x86_sse2_comige_sd:
9206 case Intrinsic::x86_sse2_comineq_sd:
9207 case Intrinsic::x86_sse2_ucomieq_sd:
9208 case Intrinsic::x86_sse2_ucomilt_sd:
9209 case Intrinsic::x86_sse2_ucomile_sd:
9210 case Intrinsic::x86_sse2_ucomigt_sd:
9211 case Intrinsic::x86_sse2_ucomige_sd:
9212 case Intrinsic::x86_sse2_ucomineq_sd: {
9214 ISD::CondCode CC = ISD::SETCC_INVALID;
9217 case Intrinsic::x86_sse_comieq_ss:
9218 case Intrinsic::x86_sse2_comieq_sd:
9222 case Intrinsic::x86_sse_comilt_ss:
9223 case Intrinsic::x86_sse2_comilt_sd:
9227 case Intrinsic::x86_sse_comile_ss:
9228 case Intrinsic::x86_sse2_comile_sd:
9232 case Intrinsic::x86_sse_comigt_ss:
9233 case Intrinsic::x86_sse2_comigt_sd:
9237 case Intrinsic::x86_sse_comige_ss:
9238 case Intrinsic::x86_sse2_comige_sd:
9242 case Intrinsic::x86_sse_comineq_ss:
9243 case Intrinsic::x86_sse2_comineq_sd:
9247 case Intrinsic::x86_sse_ucomieq_ss:
9248 case Intrinsic::x86_sse2_ucomieq_sd:
9249 Opc = X86ISD::UCOMI;
9252 case Intrinsic::x86_sse_ucomilt_ss:
9253 case Intrinsic::x86_sse2_ucomilt_sd:
9254 Opc = X86ISD::UCOMI;
9257 case Intrinsic::x86_sse_ucomile_ss:
9258 case Intrinsic::x86_sse2_ucomile_sd:
9259 Opc = X86ISD::UCOMI;
9262 case Intrinsic::x86_sse_ucomigt_ss:
9263 case Intrinsic::x86_sse2_ucomigt_sd:
9264 Opc = X86ISD::UCOMI;
9267 case Intrinsic::x86_sse_ucomige_ss:
9268 case Intrinsic::x86_sse2_ucomige_sd:
9269 Opc = X86ISD::UCOMI;
9272 case Intrinsic::x86_sse_ucomineq_ss:
9273 case Intrinsic::x86_sse2_ucomineq_sd:
9274 Opc = X86ISD::UCOMI;
9279 SDValue LHS = Op.getOperand(1);
9280 SDValue RHS = Op.getOperand(2);
9281 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9282 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9283 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9284 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9285 DAG.getConstant(X86CC, MVT::i8), Cond);
9286 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9288 // Arithmetic intrinsics.
9289 case Intrinsic::x86_sse3_hadd_ps:
9290 case Intrinsic::x86_sse3_hadd_pd:
9291 case Intrinsic::x86_avx_hadd_ps_256:
9292 case Intrinsic::x86_avx_hadd_pd_256:
9293 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9294 Op.getOperand(1), Op.getOperand(2));
9295 case Intrinsic::x86_sse3_hsub_ps:
9296 case Intrinsic::x86_sse3_hsub_pd:
9297 case Intrinsic::x86_avx_hsub_ps_256:
9298 case Intrinsic::x86_avx_hsub_pd_256:
9299 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9300 Op.getOperand(1), Op.getOperand(2));
9301 case Intrinsic::x86_avx2_psllv_d:
9302 case Intrinsic::x86_avx2_psllv_q:
9303 case Intrinsic::x86_avx2_psllv_d_256:
9304 case Intrinsic::x86_avx2_psllv_q_256:
9305 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9306 Op.getOperand(1), Op.getOperand(2));
9307 case Intrinsic::x86_avx2_psrlv_d:
9308 case Intrinsic::x86_avx2_psrlv_q:
9309 case Intrinsic::x86_avx2_psrlv_d_256:
9310 case Intrinsic::x86_avx2_psrlv_q_256:
9311 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9312 Op.getOperand(1), Op.getOperand(2));
9313 case Intrinsic::x86_avx2_psrav_d:
9314 case Intrinsic::x86_avx2_psrav_d_256:
9315 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9316 Op.getOperand(1), Op.getOperand(2));
9318 // ptest and testp intrinsics. The intrinsic these come from are designed to
9319 // return an integer value, not just an instruction so lower it to the ptest
9320 // or testp pattern and a setcc for the result.
9321 case Intrinsic::x86_sse41_ptestz:
9322 case Intrinsic::x86_sse41_ptestc:
9323 case Intrinsic::x86_sse41_ptestnzc:
9324 case Intrinsic::x86_avx_ptestz_256:
9325 case Intrinsic::x86_avx_ptestc_256:
9326 case Intrinsic::x86_avx_ptestnzc_256:
9327 case Intrinsic::x86_avx_vtestz_ps:
9328 case Intrinsic::x86_avx_vtestc_ps:
9329 case Intrinsic::x86_avx_vtestnzc_ps:
9330 case Intrinsic::x86_avx_vtestz_pd:
9331 case Intrinsic::x86_avx_vtestc_pd:
9332 case Intrinsic::x86_avx_vtestnzc_pd:
9333 case Intrinsic::x86_avx_vtestz_ps_256:
9334 case Intrinsic::x86_avx_vtestc_ps_256:
9335 case Intrinsic::x86_avx_vtestnzc_ps_256:
9336 case Intrinsic::x86_avx_vtestz_pd_256:
9337 case Intrinsic::x86_avx_vtestc_pd_256:
9338 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9339 bool IsTestPacked = false;
9342 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9343 case Intrinsic::x86_avx_vtestz_ps:
9344 case Intrinsic::x86_avx_vtestz_pd:
9345 case Intrinsic::x86_avx_vtestz_ps_256:
9346 case Intrinsic::x86_avx_vtestz_pd_256:
9347 IsTestPacked = true; // Fallthrough
9348 case Intrinsic::x86_sse41_ptestz:
9349 case Intrinsic::x86_avx_ptestz_256:
9351 X86CC = X86::COND_E;
9353 case Intrinsic::x86_avx_vtestc_ps:
9354 case Intrinsic::x86_avx_vtestc_pd:
9355 case Intrinsic::x86_avx_vtestc_ps_256:
9356 case Intrinsic::x86_avx_vtestc_pd_256:
9357 IsTestPacked = true; // Fallthrough
9358 case Intrinsic::x86_sse41_ptestc:
9359 case Intrinsic::x86_avx_ptestc_256:
9361 X86CC = X86::COND_B;
9363 case Intrinsic::x86_avx_vtestnzc_ps:
9364 case Intrinsic::x86_avx_vtestnzc_pd:
9365 case Intrinsic::x86_avx_vtestnzc_ps_256:
9366 case Intrinsic::x86_avx_vtestnzc_pd_256:
9367 IsTestPacked = true; // Fallthrough
9368 case Intrinsic::x86_sse41_ptestnzc:
9369 case Intrinsic::x86_avx_ptestnzc_256:
9371 X86CC = X86::COND_A;
9375 SDValue LHS = Op.getOperand(1);
9376 SDValue RHS = Op.getOperand(2);
9377 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9378 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9379 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9380 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9381 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9384 // Fix vector shift instructions where the last operand is a non-immediate
9386 case Intrinsic::x86_avx2_pslli_w:
9387 case Intrinsic::x86_avx2_pslli_d:
9388 case Intrinsic::x86_avx2_pslli_q:
9389 case Intrinsic::x86_avx2_psrli_w:
9390 case Intrinsic::x86_avx2_psrli_d:
9391 case Intrinsic::x86_avx2_psrli_q:
9392 case Intrinsic::x86_avx2_psrai_w:
9393 case Intrinsic::x86_avx2_psrai_d:
9394 case Intrinsic::x86_sse2_pslli_w:
9395 case Intrinsic::x86_sse2_pslli_d:
9396 case Intrinsic::x86_sse2_pslli_q:
9397 case Intrinsic::x86_sse2_psrli_w:
9398 case Intrinsic::x86_sse2_psrli_d:
9399 case Intrinsic::x86_sse2_psrli_q:
9400 case Intrinsic::x86_sse2_psrai_w:
9401 case Intrinsic::x86_sse2_psrai_d:
9402 case Intrinsic::x86_mmx_pslli_w:
9403 case Intrinsic::x86_mmx_pslli_d:
9404 case Intrinsic::x86_mmx_pslli_q:
9405 case Intrinsic::x86_mmx_psrli_w:
9406 case Intrinsic::x86_mmx_psrli_d:
9407 case Intrinsic::x86_mmx_psrli_q:
9408 case Intrinsic::x86_mmx_psrai_w:
9409 case Intrinsic::x86_mmx_psrai_d: {
9410 SDValue ShAmt = Op.getOperand(2);
9411 if (isa<ConstantSDNode>(ShAmt))
9414 unsigned NewIntNo = 0;
9415 EVT ShAmtVT = MVT::v4i32;
9417 case Intrinsic::x86_sse2_pslli_w:
9418 NewIntNo = Intrinsic::x86_sse2_psll_w;
9420 case Intrinsic::x86_sse2_pslli_d:
9421 NewIntNo = Intrinsic::x86_sse2_psll_d;
9423 case Intrinsic::x86_sse2_pslli_q:
9424 NewIntNo = Intrinsic::x86_sse2_psll_q;
9426 case Intrinsic::x86_sse2_psrli_w:
9427 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9429 case Intrinsic::x86_sse2_psrli_d:
9430 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9432 case Intrinsic::x86_sse2_psrli_q:
9433 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9435 case Intrinsic::x86_sse2_psrai_w:
9436 NewIntNo = Intrinsic::x86_sse2_psra_w;
9438 case Intrinsic::x86_sse2_psrai_d:
9439 NewIntNo = Intrinsic::x86_sse2_psra_d;
9441 case Intrinsic::x86_avx2_pslli_w:
9442 NewIntNo = Intrinsic::x86_avx2_psll_w;
9444 case Intrinsic::x86_avx2_pslli_d:
9445 NewIntNo = Intrinsic::x86_avx2_psll_d;
9447 case Intrinsic::x86_avx2_pslli_q:
9448 NewIntNo = Intrinsic::x86_avx2_psll_q;
9450 case Intrinsic::x86_avx2_psrli_w:
9451 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9453 case Intrinsic::x86_avx2_psrli_d:
9454 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9456 case Intrinsic::x86_avx2_psrli_q:
9457 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9459 case Intrinsic::x86_avx2_psrai_w:
9460 NewIntNo = Intrinsic::x86_avx2_psra_w;
9462 case Intrinsic::x86_avx2_psrai_d:
9463 NewIntNo = Intrinsic::x86_avx2_psra_d;
9466 ShAmtVT = MVT::v2i32;
9468 case Intrinsic::x86_mmx_pslli_w:
9469 NewIntNo = Intrinsic::x86_mmx_psll_w;
9471 case Intrinsic::x86_mmx_pslli_d:
9472 NewIntNo = Intrinsic::x86_mmx_psll_d;
9474 case Intrinsic::x86_mmx_pslli_q:
9475 NewIntNo = Intrinsic::x86_mmx_psll_q;
9477 case Intrinsic::x86_mmx_psrli_w:
9478 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9480 case Intrinsic::x86_mmx_psrli_d:
9481 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9483 case Intrinsic::x86_mmx_psrli_q:
9484 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9486 case Intrinsic::x86_mmx_psrai_w:
9487 NewIntNo = Intrinsic::x86_mmx_psra_w;
9489 case Intrinsic::x86_mmx_psrai_d:
9490 NewIntNo = Intrinsic::x86_mmx_psra_d;
9492 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9498 // The vector shift intrinsics with scalars uses 32b shift amounts but
9499 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9503 ShOps[1] = DAG.getConstant(0, MVT::i32);
9504 if (ShAmtVT == MVT::v4i32) {
9505 ShOps[2] = DAG.getUNDEF(MVT::i32);
9506 ShOps[3] = DAG.getUNDEF(MVT::i32);
9507 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9509 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9510 // FIXME this must be lowered to get rid of the invalid type.
9513 EVT VT = Op.getValueType();
9514 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9515 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9516 DAG.getConstant(NewIntNo, MVT::i32),
9517 Op.getOperand(1), ShAmt);
9522 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9523 SelectionDAG &DAG) const {
9524 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9525 MFI->setReturnAddressIsTaken(true);
9527 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9528 DebugLoc dl = Op.getDebugLoc();
9531 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9533 DAG.getConstant(TD->getPointerSize(),
9534 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9535 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9536 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9538 MachinePointerInfo(), false, false, false, 0);
9541 // Just load the return address.
9542 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9543 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9544 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9547 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9548 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9549 MFI->setFrameAddressIsTaken(true);
9551 EVT VT = Op.getValueType();
9552 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9553 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9554 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9555 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9557 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9558 MachinePointerInfo(),
9559 false, false, false, 0);
9563 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9564 SelectionDAG &DAG) const {
9565 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9568 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9569 MachineFunction &MF = DAG.getMachineFunction();
9570 SDValue Chain = Op.getOperand(0);
9571 SDValue Offset = Op.getOperand(1);
9572 SDValue Handler = Op.getOperand(2);
9573 DebugLoc dl = Op.getDebugLoc();
9575 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9576 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9578 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9580 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9581 DAG.getIntPtrConstant(TD->getPointerSize()));
9582 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9583 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9585 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9586 MF.getRegInfo().addLiveOut(StoreAddrReg);
9588 return DAG.getNode(X86ISD::EH_RETURN, dl,
9590 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9593 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9594 SelectionDAG &DAG) const {
9595 return Op.getOperand(0);
9598 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9599 SelectionDAG &DAG) const {
9600 SDValue Root = Op.getOperand(0);
9601 SDValue Trmp = Op.getOperand(1); // trampoline
9602 SDValue FPtr = Op.getOperand(2); // nested function
9603 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9604 DebugLoc dl = Op.getDebugLoc();
9606 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9608 if (Subtarget->is64Bit()) {
9609 SDValue OutChains[6];
9611 // Large code-model.
9612 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9613 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9615 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9616 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9618 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9620 // Load the pointer to the nested function into R11.
9621 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9622 SDValue Addr = Trmp;
9623 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9624 Addr, MachinePointerInfo(TrmpAddr),
9627 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9628 DAG.getConstant(2, MVT::i64));
9629 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9630 MachinePointerInfo(TrmpAddr, 2),
9633 // Load the 'nest' parameter value into R10.
9634 // R10 is specified in X86CallingConv.td
9635 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9636 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9637 DAG.getConstant(10, MVT::i64));
9638 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9639 Addr, MachinePointerInfo(TrmpAddr, 10),
9642 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9643 DAG.getConstant(12, MVT::i64));
9644 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9645 MachinePointerInfo(TrmpAddr, 12),
9648 // Jump to the nested function.
9649 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9650 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9651 DAG.getConstant(20, MVT::i64));
9652 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9653 Addr, MachinePointerInfo(TrmpAddr, 20),
9656 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9657 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9658 DAG.getConstant(22, MVT::i64));
9659 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9660 MachinePointerInfo(TrmpAddr, 22),
9663 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9665 const Function *Func =
9666 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9667 CallingConv::ID CC = Func->getCallingConv();
9672 llvm_unreachable("Unsupported calling convention");
9673 case CallingConv::C:
9674 case CallingConv::X86_StdCall: {
9675 // Pass 'nest' parameter in ECX.
9676 // Must be kept in sync with X86CallingConv.td
9679 // Check that ECX wasn't needed by an 'inreg' parameter.
9680 FunctionType *FTy = Func->getFunctionType();
9681 const AttrListPtr &Attrs = Func->getAttributes();
9683 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9684 unsigned InRegCount = 0;
9687 for (FunctionType::param_iterator I = FTy->param_begin(),
9688 E = FTy->param_end(); I != E; ++I, ++Idx)
9689 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9690 // FIXME: should only count parameters that are lowered to integers.
9691 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9693 if (InRegCount > 2) {
9694 report_fatal_error("Nest register in use - reduce number of inreg"
9700 case CallingConv::X86_FastCall:
9701 case CallingConv::X86_ThisCall:
9702 case CallingConv::Fast:
9703 // Pass 'nest' parameter in EAX.
9704 // Must be kept in sync with X86CallingConv.td
9709 SDValue OutChains[4];
9712 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9713 DAG.getConstant(10, MVT::i32));
9714 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9716 // This is storing the opcode for MOV32ri.
9717 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9718 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9719 OutChains[0] = DAG.getStore(Root, dl,
9720 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9721 Trmp, MachinePointerInfo(TrmpAddr),
9724 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9725 DAG.getConstant(1, MVT::i32));
9726 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9727 MachinePointerInfo(TrmpAddr, 1),
9730 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9731 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9732 DAG.getConstant(5, MVT::i32));
9733 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9734 MachinePointerInfo(TrmpAddr, 5),
9737 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9738 DAG.getConstant(6, MVT::i32));
9739 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9740 MachinePointerInfo(TrmpAddr, 6),
9743 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9747 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9748 SelectionDAG &DAG) const {
9750 The rounding mode is in bits 11:10 of FPSR, and has the following
9757 FLT_ROUNDS, on the other hand, expects the following:
9764 To perform the conversion, we do:
9765 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9768 MachineFunction &MF = DAG.getMachineFunction();
9769 const TargetMachine &TM = MF.getTarget();
9770 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9771 unsigned StackAlignment = TFI.getStackAlignment();
9772 EVT VT = Op.getValueType();
9773 DebugLoc DL = Op.getDebugLoc();
9775 // Save FP Control Word to stack slot
9776 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9777 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9780 MachineMemOperand *MMO =
9781 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9782 MachineMemOperand::MOStore, 2, 2);
9784 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9785 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9786 DAG.getVTList(MVT::Other),
9787 Ops, 2, MVT::i16, MMO);
9789 // Load FP Control Word from stack slot
9790 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9791 MachinePointerInfo(), false, false, false, 0);
9793 // Transform as necessary
9795 DAG.getNode(ISD::SRL, DL, MVT::i16,
9796 DAG.getNode(ISD::AND, DL, MVT::i16,
9797 CWD, DAG.getConstant(0x800, MVT::i16)),
9798 DAG.getConstant(11, MVT::i8));
9800 DAG.getNode(ISD::SRL, DL, MVT::i16,
9801 DAG.getNode(ISD::AND, DL, MVT::i16,
9802 CWD, DAG.getConstant(0x400, MVT::i16)),
9803 DAG.getConstant(9, MVT::i8));
9806 DAG.getNode(ISD::AND, DL, MVT::i16,
9807 DAG.getNode(ISD::ADD, DL, MVT::i16,
9808 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9809 DAG.getConstant(1, MVT::i16)),
9810 DAG.getConstant(3, MVT::i16));
9813 return DAG.getNode((VT.getSizeInBits() < 16 ?
9814 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9817 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9818 EVT VT = Op.getValueType();
9820 unsigned NumBits = VT.getSizeInBits();
9821 DebugLoc dl = Op.getDebugLoc();
9823 Op = Op.getOperand(0);
9824 if (VT == MVT::i8) {
9825 // Zero extend to i32 since there is not an i8 bsr.
9827 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9830 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9831 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9832 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9834 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9837 DAG.getConstant(NumBits+NumBits-1, OpVT),
9838 DAG.getConstant(X86::COND_E, MVT::i8),
9841 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9843 // Finally xor with NumBits-1.
9844 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9847 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9851 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
9852 SelectionDAG &DAG) const {
9853 EVT VT = Op.getValueType();
9855 unsigned NumBits = VT.getSizeInBits();
9856 DebugLoc dl = Op.getDebugLoc();
9858 Op = Op.getOperand(0);
9859 if (VT == MVT::i8) {
9860 // Zero extend to i32 since there is not an i8 bsr.
9862 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9865 // Issue a bsr (scan bits in reverse).
9866 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9867 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9869 // And xor with NumBits-1.
9870 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9873 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9877 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9878 EVT VT = Op.getValueType();
9880 unsigned NumBits = VT.getSizeInBits();
9881 DebugLoc dl = Op.getDebugLoc();
9883 Op = Op.getOperand(0);
9884 if (VT == MVT::i8) {
9886 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9889 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9890 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9891 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9893 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9896 DAG.getConstant(NumBits, OpVT),
9897 DAG.getConstant(X86::COND_E, MVT::i8),
9900 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9903 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9907 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9908 // ones, and then concatenate the result back.
9909 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9910 EVT VT = Op.getValueType();
9912 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9913 "Unsupported value type for operation");
9915 int NumElems = VT.getVectorNumElements();
9916 DebugLoc dl = Op.getDebugLoc();
9917 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9918 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9920 // Extract the LHS vectors
9921 SDValue LHS = Op.getOperand(0);
9922 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9923 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9925 // Extract the RHS vectors
9926 SDValue RHS = Op.getOperand(1);
9927 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9928 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9930 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9931 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9933 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9934 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9935 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9938 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9939 assert(Op.getValueType().getSizeInBits() == 256 &&
9940 Op.getValueType().isInteger() &&
9941 "Only handle AVX 256-bit vector integer operation");
9942 return Lower256IntArith(Op, DAG);
9945 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9946 assert(Op.getValueType().getSizeInBits() == 256 &&
9947 Op.getValueType().isInteger() &&
9948 "Only handle AVX 256-bit vector integer operation");
9949 return Lower256IntArith(Op, DAG);
9952 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9953 EVT VT = Op.getValueType();
9955 // Decompose 256-bit ops into smaller 128-bit ops.
9956 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9957 return Lower256IntArith(Op, DAG);
9959 DebugLoc dl = Op.getDebugLoc();
9961 SDValue A = Op.getOperand(0);
9962 SDValue B = Op.getOperand(1);
9964 if (VT == MVT::v4i64) {
9965 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9967 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9968 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9969 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9970 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9971 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9973 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9974 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9975 // return AloBlo + AloBhi + AhiBlo;
9977 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9978 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9979 A, DAG.getConstant(32, MVT::i32));
9980 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9981 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9982 B, DAG.getConstant(32, MVT::i32));
9983 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9984 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9986 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9987 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9989 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9990 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9992 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9993 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9994 AloBhi, DAG.getConstant(32, MVT::i32));
9995 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9996 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9997 AhiBlo, DAG.getConstant(32, MVT::i32));
9998 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9999 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10003 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10005 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10006 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10007 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10008 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10009 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10011 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10012 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10013 // return AloBlo + AloBhi + AhiBlo;
10015 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10016 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10017 A, DAG.getConstant(32, MVT::i32));
10018 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10019 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10020 B, DAG.getConstant(32, MVT::i32));
10021 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10022 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10024 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10025 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10027 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10028 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10030 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10031 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10032 AloBhi, DAG.getConstant(32, MVT::i32));
10033 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10034 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10035 AhiBlo, DAG.getConstant(32, MVT::i32));
10036 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10037 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10041 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10043 EVT VT = Op.getValueType();
10044 DebugLoc dl = Op.getDebugLoc();
10045 SDValue R = Op.getOperand(0);
10046 SDValue Amt = Op.getOperand(1);
10047 LLVMContext *Context = DAG.getContext();
10049 if (!Subtarget->hasXMMInt())
10052 // Optimize shl/srl/sra with constant shift amount.
10053 if (isSplatVector(Amt.getNode())) {
10054 SDValue SclrAmt = Amt->getOperand(0);
10055 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10056 uint64_t ShiftAmt = C->getZExtValue();
10058 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10059 // Make a large shift.
10061 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10062 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10063 R, DAG.getConstant(ShiftAmt, MVT::i32));
10064 // Zero out the rightmost bits.
10065 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10067 return DAG.getNode(ISD::AND, dl, VT, SHL,
10068 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10071 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10072 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10073 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10074 R, DAG.getConstant(ShiftAmt, MVT::i32));
10076 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10077 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10078 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10079 R, DAG.getConstant(ShiftAmt, MVT::i32));
10081 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10082 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10083 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10084 R, DAG.getConstant(ShiftAmt, MVT::i32));
10086 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10087 // Make a large shift.
10089 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10090 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10091 R, DAG.getConstant(ShiftAmt, MVT::i32));
10092 // Zero out the leftmost bits.
10093 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10095 return DAG.getNode(ISD::AND, dl, VT, SRL,
10096 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10099 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10100 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10101 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10102 R, DAG.getConstant(ShiftAmt, MVT::i32));
10104 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10105 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10106 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10107 R, DAG.getConstant(ShiftAmt, MVT::i32));
10109 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10110 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10111 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10112 R, DAG.getConstant(ShiftAmt, MVT::i32));
10114 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10115 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10116 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10117 R, DAG.getConstant(ShiftAmt, MVT::i32));
10119 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10120 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10121 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10122 R, DAG.getConstant(ShiftAmt, MVT::i32));
10124 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10125 if (ShiftAmt == 7) {
10126 // R s>> 7 === R s< 0
10127 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10128 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10131 // R s>> a === ((R u>> a) ^ m) - m
10132 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10133 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10135 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10136 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10137 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10141 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10142 if (Op.getOpcode() == ISD::SHL) {
10143 // Make a large shift.
10145 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10146 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10147 R, DAG.getConstant(ShiftAmt, MVT::i32));
10148 // Zero out the rightmost bits.
10149 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10151 return DAG.getNode(ISD::AND, dl, VT, SHL,
10152 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10154 if (Op.getOpcode() == ISD::SRL) {
10155 // Make a large shift.
10157 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10158 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10159 R, DAG.getConstant(ShiftAmt, MVT::i32));
10160 // Zero out the leftmost bits.
10161 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10163 return DAG.getNode(ISD::AND, dl, VT, SRL,
10164 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10166 if (Op.getOpcode() == ISD::SRA) {
10167 if (ShiftAmt == 7) {
10168 // R s>> 7 === R s< 0
10169 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10170 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10173 // R s>> a === ((R u>> a) ^ m) - m
10174 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10175 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10177 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10178 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10179 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10186 // Lower SHL with variable shift amount.
10187 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10188 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10189 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10190 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10192 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10194 std::vector<Constant*> CV(4, CI);
10195 Constant *C = ConstantVector::get(CV);
10196 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10197 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10198 MachinePointerInfo::getConstantPool(),
10199 false, false, false, 16);
10201 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10202 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10203 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10204 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10206 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10207 assert((Subtarget->hasSSE2() || Subtarget->hasAVX()) &&
10208 "Need SSE2 for pslli/pcmpeq.");
10211 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10212 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10213 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10215 // Turn 'a' into a mask suitable for VSELECT
10216 SDValue VSelM = DAG.getConstant(0x80, VT);
10217 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10218 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10219 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10222 SDValue CM1 = DAG.getConstant(0x0f, VT);
10223 SDValue CM2 = DAG.getConstant(0x3f, VT);
10225 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10226 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10227 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10228 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10229 DAG.getConstant(4, MVT::i32));
10230 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10233 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10234 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10235 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10236 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10239 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10240 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10241 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10242 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10243 DAG.getConstant(2, MVT::i32));
10244 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10247 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10248 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10249 OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10250 DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10253 // return VSELECT(r, r+r, a);
10254 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10255 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10259 // Decompose 256-bit shifts into smaller 128-bit shifts.
10260 if (VT.getSizeInBits() == 256) {
10261 int NumElems = VT.getVectorNumElements();
10262 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10263 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10265 // Extract the two vectors
10266 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10267 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10270 // Recreate the shift amount vectors
10271 SDValue Amt1, Amt2;
10272 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10273 // Constant shift amount
10274 SmallVector<SDValue, 4> Amt1Csts;
10275 SmallVector<SDValue, 4> Amt2Csts;
10276 for (int i = 0; i < NumElems/2; ++i)
10277 Amt1Csts.push_back(Amt->getOperand(i));
10278 for (int i = NumElems/2; i < NumElems; ++i)
10279 Amt2Csts.push_back(Amt->getOperand(i));
10281 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10282 &Amt1Csts[0], NumElems/2);
10283 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10284 &Amt2Csts[0], NumElems/2);
10286 // Variable shift amount
10287 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10288 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10292 // Issue new vector shifts for the smaller types
10293 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10294 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10296 // Concatenate the result back
10297 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10303 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10304 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10305 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10306 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10307 // has only one use.
10308 SDNode *N = Op.getNode();
10309 SDValue LHS = N->getOperand(0);
10310 SDValue RHS = N->getOperand(1);
10311 unsigned BaseOp = 0;
10313 DebugLoc DL = Op.getDebugLoc();
10314 switch (Op.getOpcode()) {
10315 default: llvm_unreachable("Unknown ovf instruction!");
10317 // A subtract of one will be selected as a INC. Note that INC doesn't
10318 // set CF, so we can't do this for UADDO.
10319 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10321 BaseOp = X86ISD::INC;
10322 Cond = X86::COND_O;
10325 BaseOp = X86ISD::ADD;
10326 Cond = X86::COND_O;
10329 BaseOp = X86ISD::ADD;
10330 Cond = X86::COND_B;
10333 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10334 // set CF, so we can't do this for USUBO.
10335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10337 BaseOp = X86ISD::DEC;
10338 Cond = X86::COND_O;
10341 BaseOp = X86ISD::SUB;
10342 Cond = X86::COND_O;
10345 BaseOp = X86ISD::SUB;
10346 Cond = X86::COND_B;
10349 BaseOp = X86ISD::SMUL;
10350 Cond = X86::COND_O;
10352 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10353 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10355 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10358 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10359 DAG.getConstant(X86::COND_O, MVT::i32),
10360 SDValue(Sum.getNode(), 2));
10362 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10366 // Also sets EFLAGS.
10367 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10368 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10371 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10372 DAG.getConstant(Cond, MVT::i32),
10373 SDValue(Sum.getNode(), 1));
10375 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10378 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10379 SelectionDAG &DAG) const {
10380 DebugLoc dl = Op.getDebugLoc();
10381 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10382 EVT VT = Op.getValueType();
10384 if (Subtarget->hasXMMInt() && VT.isVector()) {
10385 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10386 ExtraVT.getScalarType().getSizeInBits();
10387 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10389 unsigned SHLIntrinsicsID = 0;
10390 unsigned SRAIntrinsicsID = 0;
10391 switch (VT.getSimpleVT().SimpleTy) {
10395 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10396 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10399 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10400 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10404 if (!Subtarget->hasAVX())
10406 if (!Subtarget->hasAVX2()) {
10407 // needs to be split
10408 int NumElems = VT.getVectorNumElements();
10409 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10410 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10412 // Extract the LHS vectors
10413 SDValue LHS = Op.getOperand(0);
10414 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10415 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10417 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10418 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10420 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10421 int ExtraNumElems = ExtraVT.getVectorNumElements();
10422 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10424 SDValue Extra = DAG.getValueType(ExtraVT);
10426 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10427 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10429 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10431 if (VT == MVT::v8i32) {
10432 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10433 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10435 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10436 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10440 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10441 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10442 Op.getOperand(0), ShAmt);
10444 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10445 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10453 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10454 DebugLoc dl = Op.getDebugLoc();
10456 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10457 // There isn't any reason to disable it if the target processor supports it.
10458 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10459 SDValue Chain = Op.getOperand(0);
10460 SDValue Zero = DAG.getConstant(0, MVT::i32);
10462 DAG.getRegister(X86::ESP, MVT::i32), // Base
10463 DAG.getTargetConstant(1, MVT::i8), // Scale
10464 DAG.getRegister(0, MVT::i32), // Index
10465 DAG.getTargetConstant(0, MVT::i32), // Disp
10466 DAG.getRegister(0, MVT::i32), // Segment.
10471 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10472 array_lengthof(Ops));
10473 return SDValue(Res, 0);
10476 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10478 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10480 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10481 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10482 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10483 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10485 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10486 if (!Op1 && !Op2 && !Op3 && Op4)
10487 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10489 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10490 if (Op1 && !Op2 && !Op3 && !Op4)
10491 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10493 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10495 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10498 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10499 SelectionDAG &DAG) const {
10500 DebugLoc dl = Op.getDebugLoc();
10501 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10502 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10503 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10504 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10506 // The only fence that needs an instruction is a sequentially-consistent
10507 // cross-thread fence.
10508 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10509 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10510 // no-sse2). There isn't any reason to disable it if the target processor
10512 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10513 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10515 SDValue Chain = Op.getOperand(0);
10516 SDValue Zero = DAG.getConstant(0, MVT::i32);
10518 DAG.getRegister(X86::ESP, MVT::i32), // Base
10519 DAG.getTargetConstant(1, MVT::i8), // Scale
10520 DAG.getRegister(0, MVT::i32), // Index
10521 DAG.getTargetConstant(0, MVT::i32), // Disp
10522 DAG.getRegister(0, MVT::i32), // Segment.
10527 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10528 array_lengthof(Ops));
10529 return SDValue(Res, 0);
10532 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10533 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10537 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10538 EVT T = Op.getValueType();
10539 DebugLoc DL = Op.getDebugLoc();
10542 switch(T.getSimpleVT().SimpleTy) {
10544 assert(false && "Invalid value type!");
10545 case MVT::i8: Reg = X86::AL; size = 1; break;
10546 case MVT::i16: Reg = X86::AX; size = 2; break;
10547 case MVT::i32: Reg = X86::EAX; size = 4; break;
10549 assert(Subtarget->is64Bit() && "Node not type legal!");
10550 Reg = X86::RAX; size = 8;
10553 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10554 Op.getOperand(2), SDValue());
10555 SDValue Ops[] = { cpIn.getValue(0),
10558 DAG.getTargetConstant(size, MVT::i8),
10559 cpIn.getValue(1) };
10560 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10561 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10562 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10565 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10569 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10570 SelectionDAG &DAG) const {
10571 assert(Subtarget->is64Bit() && "Result not type legalized?");
10572 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10573 SDValue TheChain = Op.getOperand(0);
10574 DebugLoc dl = Op.getDebugLoc();
10575 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10576 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10577 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10579 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10580 DAG.getConstant(32, MVT::i8));
10582 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10585 return DAG.getMergeValues(Ops, 2, dl);
10588 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10589 SelectionDAG &DAG) const {
10590 EVT SrcVT = Op.getOperand(0).getValueType();
10591 EVT DstVT = Op.getValueType();
10592 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10593 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10594 assert((DstVT == MVT::i64 ||
10595 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10596 "Unexpected custom BITCAST");
10597 // i64 <=> MMX conversions are Legal.
10598 if (SrcVT==MVT::i64 && DstVT.isVector())
10600 if (DstVT==MVT::i64 && SrcVT.isVector())
10602 // MMX <=> MMX conversions are Legal.
10603 if (SrcVT.isVector() && DstVT.isVector())
10605 // All other conversions need to be expanded.
10609 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10610 SDNode *Node = Op.getNode();
10611 DebugLoc dl = Node->getDebugLoc();
10612 EVT T = Node->getValueType(0);
10613 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10614 DAG.getConstant(0, T), Node->getOperand(2));
10615 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10616 cast<AtomicSDNode>(Node)->getMemoryVT(),
10617 Node->getOperand(0),
10618 Node->getOperand(1), negOp,
10619 cast<AtomicSDNode>(Node)->getSrcValue(),
10620 cast<AtomicSDNode>(Node)->getAlignment(),
10621 cast<AtomicSDNode>(Node)->getOrdering(),
10622 cast<AtomicSDNode>(Node)->getSynchScope());
10625 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10626 SDNode *Node = Op.getNode();
10627 DebugLoc dl = Node->getDebugLoc();
10628 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10630 // Convert seq_cst store -> xchg
10631 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10632 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10633 // (The only way to get a 16-byte store is cmpxchg16b)
10634 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10635 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10636 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10637 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10638 cast<AtomicSDNode>(Node)->getMemoryVT(),
10639 Node->getOperand(0),
10640 Node->getOperand(1), Node->getOperand(2),
10641 cast<AtomicSDNode>(Node)->getMemOperand(),
10642 cast<AtomicSDNode>(Node)->getOrdering(),
10643 cast<AtomicSDNode>(Node)->getSynchScope());
10644 return Swap.getValue(1);
10646 // Other atomic stores have a simple pattern.
10650 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10651 EVT VT = Op.getNode()->getValueType(0);
10653 // Let legalize expand this if it isn't a legal type yet.
10654 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10657 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10660 bool ExtraOp = false;
10661 switch (Op.getOpcode()) {
10662 default: assert(0 && "Invalid code");
10663 case ISD::ADDC: Opc = X86ISD::ADD; break;
10664 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10665 case ISD::SUBC: Opc = X86ISD::SUB; break;
10666 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10670 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10672 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10673 Op.getOperand(1), Op.getOperand(2));
10676 /// LowerOperation - Provide custom lowering hooks for some operations.
10678 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10679 switch (Op.getOpcode()) {
10680 default: llvm_unreachable("Should not custom lower this!");
10681 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10682 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10683 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10684 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10685 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10686 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10687 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10688 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10689 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10690 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10691 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10692 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10693 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10694 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10695 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10696 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10697 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10698 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10699 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10700 case ISD::SHL_PARTS:
10701 case ISD::SRA_PARTS:
10702 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10703 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10704 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10705 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10706 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10707 case ISD::FABS: return LowerFABS(Op, DAG);
10708 case ISD::FNEG: return LowerFNEG(Op, DAG);
10709 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10710 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10711 case ISD::SETCC: return LowerSETCC(Op, DAG);
10712 case ISD::SELECT: return LowerSELECT(Op, DAG);
10713 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10714 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10715 case ISD::VASTART: return LowerVASTART(Op, DAG);
10716 case ISD::VAARG: return LowerVAARG(Op, DAG);
10717 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10718 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10719 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10720 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10721 case ISD::FRAME_TO_ARGS_OFFSET:
10722 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10723 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10724 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10725 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10726 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10727 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10728 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10729 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10730 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10731 case ISD::MUL: return LowerMUL(Op, DAG);
10734 case ISD::SHL: return LowerShift(Op, DAG);
10740 case ISD::UMULO: return LowerXALUO(Op, DAG);
10741 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10742 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10746 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10747 case ISD::ADD: return LowerADD(Op, DAG);
10748 case ISD::SUB: return LowerSUB(Op, DAG);
10752 static void ReplaceATOMIC_LOAD(SDNode *Node,
10753 SmallVectorImpl<SDValue> &Results,
10754 SelectionDAG &DAG) {
10755 DebugLoc dl = Node->getDebugLoc();
10756 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10758 // Convert wide load -> cmpxchg8b/cmpxchg16b
10759 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10760 // (The only way to get a 16-byte load is cmpxchg16b)
10761 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10762 SDValue Zero = DAG.getConstant(0, VT);
10763 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10764 Node->getOperand(0),
10765 Node->getOperand(1), Zero, Zero,
10766 cast<AtomicSDNode>(Node)->getMemOperand(),
10767 cast<AtomicSDNode>(Node)->getOrdering(),
10768 cast<AtomicSDNode>(Node)->getSynchScope());
10769 Results.push_back(Swap.getValue(0));
10770 Results.push_back(Swap.getValue(1));
10773 void X86TargetLowering::
10774 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10775 SelectionDAG &DAG, unsigned NewOp) const {
10776 DebugLoc dl = Node->getDebugLoc();
10777 assert (Node->getValueType(0) == MVT::i64 &&
10778 "Only know how to expand i64 atomics");
10780 SDValue Chain = Node->getOperand(0);
10781 SDValue In1 = Node->getOperand(1);
10782 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10783 Node->getOperand(2), DAG.getIntPtrConstant(0));
10784 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10785 Node->getOperand(2), DAG.getIntPtrConstant(1));
10786 SDValue Ops[] = { Chain, In1, In2L, In2H };
10787 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10789 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10790 cast<MemSDNode>(Node)->getMemOperand());
10791 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10792 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10793 Results.push_back(Result.getValue(2));
10796 /// ReplaceNodeResults - Replace a node with an illegal result type
10797 /// with a new node built out of custom code.
10798 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10799 SmallVectorImpl<SDValue>&Results,
10800 SelectionDAG &DAG) const {
10801 DebugLoc dl = N->getDebugLoc();
10802 switch (N->getOpcode()) {
10804 assert(false && "Do not know how to custom type legalize this operation!");
10806 case ISD::SIGN_EXTEND_INREG:
10811 // We don't want to expand or promote these.
10813 case ISD::FP_TO_SINT: {
10814 std::pair<SDValue,SDValue> Vals =
10815 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10816 SDValue FIST = Vals.first, StackSlot = Vals.second;
10817 if (FIST.getNode() != 0) {
10818 EVT VT = N->getValueType(0);
10819 // Return a load from the stack slot.
10820 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10821 MachinePointerInfo(),
10822 false, false, false, 0));
10826 case ISD::READCYCLECOUNTER: {
10827 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10828 SDValue TheChain = N->getOperand(0);
10829 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10830 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10832 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10834 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10835 SDValue Ops[] = { eax, edx };
10836 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10837 Results.push_back(edx.getValue(1));
10840 case ISD::ATOMIC_CMP_SWAP: {
10841 EVT T = N->getValueType(0);
10842 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10843 bool Regs64bit = T == MVT::i128;
10844 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10845 SDValue cpInL, cpInH;
10846 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10847 DAG.getConstant(0, HalfT));
10848 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10849 DAG.getConstant(1, HalfT));
10850 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10851 Regs64bit ? X86::RAX : X86::EAX,
10853 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10854 Regs64bit ? X86::RDX : X86::EDX,
10855 cpInH, cpInL.getValue(1));
10856 SDValue swapInL, swapInH;
10857 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10858 DAG.getConstant(0, HalfT));
10859 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10860 DAG.getConstant(1, HalfT));
10861 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10862 Regs64bit ? X86::RBX : X86::EBX,
10863 swapInL, cpInH.getValue(1));
10864 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10865 Regs64bit ? X86::RCX : X86::ECX,
10866 swapInH, swapInL.getValue(1));
10867 SDValue Ops[] = { swapInH.getValue(0),
10869 swapInH.getValue(1) };
10870 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10871 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10872 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10873 X86ISD::LCMPXCHG8_DAG;
10874 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10876 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10877 Regs64bit ? X86::RAX : X86::EAX,
10878 HalfT, Result.getValue(1));
10879 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10880 Regs64bit ? X86::RDX : X86::EDX,
10881 HalfT, cpOutL.getValue(2));
10882 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10883 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10884 Results.push_back(cpOutH.getValue(1));
10887 case ISD::ATOMIC_LOAD_ADD:
10888 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10890 case ISD::ATOMIC_LOAD_AND:
10891 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10893 case ISD::ATOMIC_LOAD_NAND:
10894 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10896 case ISD::ATOMIC_LOAD_OR:
10897 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10899 case ISD::ATOMIC_LOAD_SUB:
10900 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10902 case ISD::ATOMIC_LOAD_XOR:
10903 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10905 case ISD::ATOMIC_SWAP:
10906 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10908 case ISD::ATOMIC_LOAD:
10909 ReplaceATOMIC_LOAD(N, Results, DAG);
10913 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10915 default: return NULL;
10916 case X86ISD::BSF: return "X86ISD::BSF";
10917 case X86ISD::BSR: return "X86ISD::BSR";
10918 case X86ISD::SHLD: return "X86ISD::SHLD";
10919 case X86ISD::SHRD: return "X86ISD::SHRD";
10920 case X86ISD::FAND: return "X86ISD::FAND";
10921 case X86ISD::FOR: return "X86ISD::FOR";
10922 case X86ISD::FXOR: return "X86ISD::FXOR";
10923 case X86ISD::FSRL: return "X86ISD::FSRL";
10924 case X86ISD::FILD: return "X86ISD::FILD";
10925 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10926 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10927 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10928 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10929 case X86ISD::FLD: return "X86ISD::FLD";
10930 case X86ISD::FST: return "X86ISD::FST";
10931 case X86ISD::CALL: return "X86ISD::CALL";
10932 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10933 case X86ISD::BT: return "X86ISD::BT";
10934 case X86ISD::CMP: return "X86ISD::CMP";
10935 case X86ISD::COMI: return "X86ISD::COMI";
10936 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10937 case X86ISD::SETCC: return "X86ISD::SETCC";
10938 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10939 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10940 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10941 case X86ISD::CMOV: return "X86ISD::CMOV";
10942 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10943 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10944 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10945 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10946 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10947 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10948 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10949 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10950 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10951 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10952 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10953 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10954 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10955 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10956 case X86ISD::PSIGN: return "X86ISD::PSIGN";
10957 case X86ISD::BLENDV: return "X86ISD::BLENDV";
10958 case X86ISD::HADD: return "X86ISD::HADD";
10959 case X86ISD::HSUB: return "X86ISD::HSUB";
10960 case X86ISD::FHADD: return "X86ISD::FHADD";
10961 case X86ISD::FHSUB: return "X86ISD::FHSUB";
10962 case X86ISD::FMAX: return "X86ISD::FMAX";
10963 case X86ISD::FMIN: return "X86ISD::FMIN";
10964 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10965 case X86ISD::FRCP: return "X86ISD::FRCP";
10966 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10967 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10968 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10969 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10970 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10971 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10972 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10973 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10974 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10975 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10976 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10977 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10978 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10979 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10980 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10981 case X86ISD::VSHL: return "X86ISD::VSHL";
10982 case X86ISD::VSRL: return "X86ISD::VSRL";
10983 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10984 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10985 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10986 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10987 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10988 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10989 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10990 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10991 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10992 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10993 case X86ISD::ADD: return "X86ISD::ADD";
10994 case X86ISD::SUB: return "X86ISD::SUB";
10995 case X86ISD::ADC: return "X86ISD::ADC";
10996 case X86ISD::SBB: return "X86ISD::SBB";
10997 case X86ISD::SMUL: return "X86ISD::SMUL";
10998 case X86ISD::UMUL: return "X86ISD::UMUL";
10999 case X86ISD::INC: return "X86ISD::INC";
11000 case X86ISD::DEC: return "X86ISD::DEC";
11001 case X86ISD::OR: return "X86ISD::OR";
11002 case X86ISD::XOR: return "X86ISD::XOR";
11003 case X86ISD::AND: return "X86ISD::AND";
11004 case X86ISD::ANDN: return "X86ISD::ANDN";
11005 case X86ISD::BLSI: return "X86ISD::BLSI";
11006 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11007 case X86ISD::BLSR: return "X86ISD::BLSR";
11008 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11009 case X86ISD::PTEST: return "X86ISD::PTEST";
11010 case X86ISD::TESTP: return "X86ISD::TESTP";
11011 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11012 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11013 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11014 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
11015 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11016 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
11017 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
11018 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
11019 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11020 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11021 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11022 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11023 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11024 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11025 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11026 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11027 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
11028 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
11029 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11030 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11031 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11032 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11033 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11034 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11035 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11036 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11037 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11038 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11039 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11040 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11044 // isLegalAddressingMode - Return true if the addressing mode represented
11045 // by AM is legal for this target, for a load/store of the specified type.
11046 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11048 // X86 supports extremely general addressing modes.
11049 CodeModel::Model M = getTargetMachine().getCodeModel();
11050 Reloc::Model R = getTargetMachine().getRelocationModel();
11052 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11053 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11058 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11060 // If a reference to this global requires an extra load, we can't fold it.
11061 if (isGlobalStubReference(GVFlags))
11064 // If BaseGV requires a register for the PIC base, we cannot also have a
11065 // BaseReg specified.
11066 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11069 // If lower 4G is not available, then we must use rip-relative addressing.
11070 if ((M != CodeModel::Small || R != Reloc::Static) &&
11071 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11075 switch (AM.Scale) {
11081 // These scales always work.
11086 // These scales are formed with basereg+scalereg. Only accept if there is
11091 default: // Other stuff never works.
11099 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11100 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11102 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11103 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11104 if (NumBits1 <= NumBits2)
11109 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11110 if (!VT1.isInteger() || !VT2.isInteger())
11112 unsigned NumBits1 = VT1.getSizeInBits();
11113 unsigned NumBits2 = VT2.getSizeInBits();
11114 if (NumBits1 <= NumBits2)
11119 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11120 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11121 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11124 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11125 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11126 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11129 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11130 // i16 instructions are longer (0x66 prefix) and potentially slower.
11131 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11134 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11135 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11136 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11137 /// are assumed to be legal.
11139 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11141 // Very little shuffling can be done for 64-bit vectors right now.
11142 if (VT.getSizeInBits() == 64)
11145 // FIXME: pshufb, blends, shifts.
11146 return (VT.getVectorNumElements() == 2 ||
11147 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11148 isMOVLMask(M, VT) ||
11149 isSHUFPMask(M, VT) ||
11150 isPSHUFDMask(M, VT) ||
11151 isPSHUFHWMask(M, VT) ||
11152 isPSHUFLWMask(M, VT) ||
11153 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11154 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11155 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11156 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11157 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11161 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11163 unsigned NumElts = VT.getVectorNumElements();
11164 // FIXME: This collection of masks seems suspect.
11167 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11168 return (isMOVLMask(Mask, VT) ||
11169 isCommutedMOVLMask(Mask, VT, true) ||
11170 isSHUFPMask(Mask, VT) ||
11171 isSHUFPMask(Mask, VT, /* Commuted */ true));
11176 //===----------------------------------------------------------------------===//
11177 // X86 Scheduler Hooks
11178 //===----------------------------------------------------------------------===//
11180 // private utility function
11181 MachineBasicBlock *
11182 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11183 MachineBasicBlock *MBB,
11190 TargetRegisterClass *RC,
11191 bool invSrc) const {
11192 // For the atomic bitwise operator, we generate
11195 // ld t1 = [bitinstr.addr]
11196 // op t2 = t1, [bitinstr.val]
11198 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11200 // fallthrough -->nextMBB
11201 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11202 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11203 MachineFunction::iterator MBBIter = MBB;
11206 /// First build the CFG
11207 MachineFunction *F = MBB->getParent();
11208 MachineBasicBlock *thisMBB = MBB;
11209 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11210 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11211 F->insert(MBBIter, newMBB);
11212 F->insert(MBBIter, nextMBB);
11214 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11215 nextMBB->splice(nextMBB->begin(), thisMBB,
11216 llvm::next(MachineBasicBlock::iterator(bInstr)),
11218 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11220 // Update thisMBB to fall through to newMBB
11221 thisMBB->addSuccessor(newMBB);
11223 // newMBB jumps to itself and fall through to nextMBB
11224 newMBB->addSuccessor(nextMBB);
11225 newMBB->addSuccessor(newMBB);
11227 // Insert instructions into newMBB based on incoming instruction
11228 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11229 "unexpected number of operands");
11230 DebugLoc dl = bInstr->getDebugLoc();
11231 MachineOperand& destOper = bInstr->getOperand(0);
11232 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11233 int numArgs = bInstr->getNumOperands() - 1;
11234 for (int i=0; i < numArgs; ++i)
11235 argOpers[i] = &bInstr->getOperand(i+1);
11237 // x86 address has 4 operands: base, index, scale, and displacement
11238 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11239 int valArgIndx = lastAddrIndx + 1;
11241 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11242 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11243 for (int i=0; i <= lastAddrIndx; ++i)
11244 (*MIB).addOperand(*argOpers[i]);
11246 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11248 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11253 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11254 assert((argOpers[valArgIndx]->isReg() ||
11255 argOpers[valArgIndx]->isImm()) &&
11256 "invalid operand");
11257 if (argOpers[valArgIndx]->isReg())
11258 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11260 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11262 (*MIB).addOperand(*argOpers[valArgIndx]);
11264 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11267 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11268 for (int i=0; i <= lastAddrIndx; ++i)
11269 (*MIB).addOperand(*argOpers[i]);
11271 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11272 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11273 bInstr->memoperands_end());
11275 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11276 MIB.addReg(EAXreg);
11279 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11281 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11285 // private utility function: 64 bit atomics on 32 bit host.
11286 MachineBasicBlock *
11287 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11288 MachineBasicBlock *MBB,
11293 bool invSrc) const {
11294 // For the atomic bitwise operator, we generate
11295 // thisMBB (instructions are in pairs, except cmpxchg8b)
11296 // ld t1,t2 = [bitinstr.addr]
11298 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11299 // op t5, t6 <- out1, out2, [bitinstr.val]
11300 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11301 // mov ECX, EBX <- t5, t6
11302 // mov EAX, EDX <- t1, t2
11303 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11304 // mov t3, t4 <- EAX, EDX
11306 // result in out1, out2
11307 // fallthrough -->nextMBB
11309 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11310 const unsigned LoadOpc = X86::MOV32rm;
11311 const unsigned NotOpc = X86::NOT32r;
11312 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11313 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11314 MachineFunction::iterator MBBIter = MBB;
11317 /// First build the CFG
11318 MachineFunction *F = MBB->getParent();
11319 MachineBasicBlock *thisMBB = MBB;
11320 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11321 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11322 F->insert(MBBIter, newMBB);
11323 F->insert(MBBIter, nextMBB);
11325 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11326 nextMBB->splice(nextMBB->begin(), thisMBB,
11327 llvm::next(MachineBasicBlock::iterator(bInstr)),
11329 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11331 // Update thisMBB to fall through to newMBB
11332 thisMBB->addSuccessor(newMBB);
11334 // newMBB jumps to itself and fall through to nextMBB
11335 newMBB->addSuccessor(nextMBB);
11336 newMBB->addSuccessor(newMBB);
11338 DebugLoc dl = bInstr->getDebugLoc();
11339 // Insert instructions into newMBB based on incoming instruction
11340 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11341 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11342 "unexpected number of operands");
11343 MachineOperand& dest1Oper = bInstr->getOperand(0);
11344 MachineOperand& dest2Oper = bInstr->getOperand(1);
11345 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11346 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11347 argOpers[i] = &bInstr->getOperand(i+2);
11349 // We use some of the operands multiple times, so conservatively just
11350 // clear any kill flags that might be present.
11351 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11352 argOpers[i]->setIsKill(false);
11355 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11356 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11358 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11359 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11360 for (int i=0; i <= lastAddrIndx; ++i)
11361 (*MIB).addOperand(*argOpers[i]);
11362 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11363 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11364 // add 4 to displacement.
11365 for (int i=0; i <= lastAddrIndx-2; ++i)
11366 (*MIB).addOperand(*argOpers[i]);
11367 MachineOperand newOp3 = *(argOpers[3]);
11368 if (newOp3.isImm())
11369 newOp3.setImm(newOp3.getImm()+4);
11371 newOp3.setOffset(newOp3.getOffset()+4);
11372 (*MIB).addOperand(newOp3);
11373 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11375 // t3/4 are defined later, at the bottom of the loop
11376 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11377 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11378 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11379 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11380 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11381 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11383 // The subsequent operations should be using the destination registers of
11384 //the PHI instructions.
11386 t1 = F->getRegInfo().createVirtualRegister(RC);
11387 t2 = F->getRegInfo().createVirtualRegister(RC);
11388 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11389 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11391 t1 = dest1Oper.getReg();
11392 t2 = dest2Oper.getReg();
11395 int valArgIndx = lastAddrIndx + 1;
11396 assert((argOpers[valArgIndx]->isReg() ||
11397 argOpers[valArgIndx]->isImm()) &&
11398 "invalid operand");
11399 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11400 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11401 if (argOpers[valArgIndx]->isReg())
11402 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11404 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11405 if (regOpcL != X86::MOV32rr)
11407 (*MIB).addOperand(*argOpers[valArgIndx]);
11408 assert(argOpers[valArgIndx + 1]->isReg() ==
11409 argOpers[valArgIndx]->isReg());
11410 assert(argOpers[valArgIndx + 1]->isImm() ==
11411 argOpers[valArgIndx]->isImm());
11412 if (argOpers[valArgIndx + 1]->isReg())
11413 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11415 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11416 if (regOpcH != X86::MOV32rr)
11418 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11420 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11422 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11425 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11427 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11430 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11431 for (int i=0; i <= lastAddrIndx; ++i)
11432 (*MIB).addOperand(*argOpers[i]);
11434 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11435 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11436 bInstr->memoperands_end());
11438 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11439 MIB.addReg(X86::EAX);
11440 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11441 MIB.addReg(X86::EDX);
11444 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11446 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11450 // private utility function
11451 MachineBasicBlock *
11452 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11453 MachineBasicBlock *MBB,
11454 unsigned cmovOpc) const {
11455 // For the atomic min/max operator, we generate
11458 // ld t1 = [min/max.addr]
11459 // mov t2 = [min/max.val]
11461 // cmov[cond] t2 = t1
11463 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11465 // fallthrough -->nextMBB
11467 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11468 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11469 MachineFunction::iterator MBBIter = MBB;
11472 /// First build the CFG
11473 MachineFunction *F = MBB->getParent();
11474 MachineBasicBlock *thisMBB = MBB;
11475 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11476 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11477 F->insert(MBBIter, newMBB);
11478 F->insert(MBBIter, nextMBB);
11480 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11481 nextMBB->splice(nextMBB->begin(), thisMBB,
11482 llvm::next(MachineBasicBlock::iterator(mInstr)),
11484 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11486 // Update thisMBB to fall through to newMBB
11487 thisMBB->addSuccessor(newMBB);
11489 // newMBB jumps to newMBB and fall through to nextMBB
11490 newMBB->addSuccessor(nextMBB);
11491 newMBB->addSuccessor(newMBB);
11493 DebugLoc dl = mInstr->getDebugLoc();
11494 // Insert instructions into newMBB based on incoming instruction
11495 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11496 "unexpected number of operands");
11497 MachineOperand& destOper = mInstr->getOperand(0);
11498 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11499 int numArgs = mInstr->getNumOperands() - 1;
11500 for (int i=0; i < numArgs; ++i)
11501 argOpers[i] = &mInstr->getOperand(i+1);
11503 // x86 address has 4 operands: base, index, scale, and displacement
11504 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11505 int valArgIndx = lastAddrIndx + 1;
11507 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11508 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11509 for (int i=0; i <= lastAddrIndx; ++i)
11510 (*MIB).addOperand(*argOpers[i]);
11512 // We only support register and immediate values
11513 assert((argOpers[valArgIndx]->isReg() ||
11514 argOpers[valArgIndx]->isImm()) &&
11515 "invalid operand");
11517 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11518 if (argOpers[valArgIndx]->isReg())
11519 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11521 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11522 (*MIB).addOperand(*argOpers[valArgIndx]);
11524 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11527 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11532 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11533 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11537 // Cmp and exchange if none has modified the memory location
11538 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11539 for (int i=0; i <= lastAddrIndx; ++i)
11540 (*MIB).addOperand(*argOpers[i]);
11542 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11543 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11544 mInstr->memoperands_end());
11546 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11547 MIB.addReg(X86::EAX);
11550 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11552 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11556 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11557 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11558 // in the .td file.
11559 MachineBasicBlock *
11560 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11561 unsigned numArgs, bool memArg) const {
11562 assert(Subtarget->hasSSE42orAVX() &&
11563 "Target must have SSE4.2 or AVX features enabled");
11565 DebugLoc dl = MI->getDebugLoc();
11566 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11568 if (!Subtarget->hasAVX()) {
11570 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11572 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11575 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11577 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11580 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11581 for (unsigned i = 0; i < numArgs; ++i) {
11582 MachineOperand &Op = MI->getOperand(i+1);
11583 if (!(Op.isReg() && Op.isImplicit()))
11584 MIB.addOperand(Op);
11586 BuildMI(*BB, MI, dl,
11587 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11588 MI->getOperand(0).getReg())
11589 .addReg(X86::XMM0);
11591 MI->eraseFromParent();
11595 MachineBasicBlock *
11596 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11597 DebugLoc dl = MI->getDebugLoc();
11598 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11600 // Address into RAX/EAX, other two args into ECX, EDX.
11601 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11602 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11603 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11604 for (int i = 0; i < X86::AddrNumOperands; ++i)
11605 MIB.addOperand(MI->getOperand(i));
11607 unsigned ValOps = X86::AddrNumOperands;
11608 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11609 .addReg(MI->getOperand(ValOps).getReg());
11610 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11611 .addReg(MI->getOperand(ValOps+1).getReg());
11613 // The instruction doesn't actually take any operands though.
11614 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11616 MI->eraseFromParent(); // The pseudo is gone now.
11620 MachineBasicBlock *
11621 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11622 DebugLoc dl = MI->getDebugLoc();
11623 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11625 // First arg in ECX, the second in EAX.
11626 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11627 .addReg(MI->getOperand(0).getReg());
11628 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11629 .addReg(MI->getOperand(1).getReg());
11631 // The instruction doesn't actually take any operands though.
11632 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11634 MI->eraseFromParent(); // The pseudo is gone now.
11638 MachineBasicBlock *
11639 X86TargetLowering::EmitVAARG64WithCustomInserter(
11641 MachineBasicBlock *MBB) const {
11642 // Emit va_arg instruction on X86-64.
11644 // Operands to this pseudo-instruction:
11645 // 0 ) Output : destination address (reg)
11646 // 1-5) Input : va_list address (addr, i64mem)
11647 // 6 ) ArgSize : Size (in bytes) of vararg type
11648 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11649 // 8 ) Align : Alignment of type
11650 // 9 ) EFLAGS (implicit-def)
11652 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11653 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11655 unsigned DestReg = MI->getOperand(0).getReg();
11656 MachineOperand &Base = MI->getOperand(1);
11657 MachineOperand &Scale = MI->getOperand(2);
11658 MachineOperand &Index = MI->getOperand(3);
11659 MachineOperand &Disp = MI->getOperand(4);
11660 MachineOperand &Segment = MI->getOperand(5);
11661 unsigned ArgSize = MI->getOperand(6).getImm();
11662 unsigned ArgMode = MI->getOperand(7).getImm();
11663 unsigned Align = MI->getOperand(8).getImm();
11665 // Memory Reference
11666 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11667 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11668 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11670 // Machine Information
11671 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11672 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11673 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11674 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11675 DebugLoc DL = MI->getDebugLoc();
11677 // struct va_list {
11680 // i64 overflow_area (address)
11681 // i64 reg_save_area (address)
11683 // sizeof(va_list) = 24
11684 // alignment(va_list) = 8
11686 unsigned TotalNumIntRegs = 6;
11687 unsigned TotalNumXMMRegs = 8;
11688 bool UseGPOffset = (ArgMode == 1);
11689 bool UseFPOffset = (ArgMode == 2);
11690 unsigned MaxOffset = TotalNumIntRegs * 8 +
11691 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11693 /* Align ArgSize to a multiple of 8 */
11694 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11695 bool NeedsAlign = (Align > 8);
11697 MachineBasicBlock *thisMBB = MBB;
11698 MachineBasicBlock *overflowMBB;
11699 MachineBasicBlock *offsetMBB;
11700 MachineBasicBlock *endMBB;
11702 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11703 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11704 unsigned OffsetReg = 0;
11706 if (!UseGPOffset && !UseFPOffset) {
11707 // If we only pull from the overflow region, we don't create a branch.
11708 // We don't need to alter control flow.
11709 OffsetDestReg = 0; // unused
11710 OverflowDestReg = DestReg;
11713 overflowMBB = thisMBB;
11716 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11717 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11718 // If not, pull from overflow_area. (branch to overflowMBB)
11723 // offsetMBB overflowMBB
11728 // Registers for the PHI in endMBB
11729 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11730 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11732 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11733 MachineFunction *MF = MBB->getParent();
11734 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11735 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11736 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11738 MachineFunction::iterator MBBIter = MBB;
11741 // Insert the new basic blocks
11742 MF->insert(MBBIter, offsetMBB);
11743 MF->insert(MBBIter, overflowMBB);
11744 MF->insert(MBBIter, endMBB);
11746 // Transfer the remainder of MBB and its successor edges to endMBB.
11747 endMBB->splice(endMBB->begin(), thisMBB,
11748 llvm::next(MachineBasicBlock::iterator(MI)),
11750 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11752 // Make offsetMBB and overflowMBB successors of thisMBB
11753 thisMBB->addSuccessor(offsetMBB);
11754 thisMBB->addSuccessor(overflowMBB);
11756 // endMBB is a successor of both offsetMBB and overflowMBB
11757 offsetMBB->addSuccessor(endMBB);
11758 overflowMBB->addSuccessor(endMBB);
11760 // Load the offset value into a register
11761 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11762 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11766 .addDisp(Disp, UseFPOffset ? 4 : 0)
11767 .addOperand(Segment)
11768 .setMemRefs(MMOBegin, MMOEnd);
11770 // Check if there is enough room left to pull this argument.
11771 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11773 .addImm(MaxOffset + 8 - ArgSizeA8);
11775 // Branch to "overflowMBB" if offset >= max
11776 // Fall through to "offsetMBB" otherwise
11777 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11778 .addMBB(overflowMBB);
11781 // In offsetMBB, emit code to use the reg_save_area.
11783 assert(OffsetReg != 0);
11785 // Read the reg_save_area address.
11786 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11787 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11792 .addOperand(Segment)
11793 .setMemRefs(MMOBegin, MMOEnd);
11795 // Zero-extend the offset
11796 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11797 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11800 .addImm(X86::sub_32bit);
11802 // Add the offset to the reg_save_area to get the final address.
11803 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11804 .addReg(OffsetReg64)
11805 .addReg(RegSaveReg);
11807 // Compute the offset for the next argument
11808 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11809 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11811 .addImm(UseFPOffset ? 16 : 8);
11813 // Store it back into the va_list.
11814 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11818 .addDisp(Disp, UseFPOffset ? 4 : 0)
11819 .addOperand(Segment)
11820 .addReg(NextOffsetReg)
11821 .setMemRefs(MMOBegin, MMOEnd);
11824 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11829 // Emit code to use overflow area
11832 // Load the overflow_area address into a register.
11833 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11834 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11839 .addOperand(Segment)
11840 .setMemRefs(MMOBegin, MMOEnd);
11842 // If we need to align it, do so. Otherwise, just copy the address
11843 // to OverflowDestReg.
11845 // Align the overflow address
11846 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11847 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11849 // aligned_addr = (addr + (align-1)) & ~(align-1)
11850 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11851 .addReg(OverflowAddrReg)
11854 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11856 .addImm(~(uint64_t)(Align-1));
11858 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11859 .addReg(OverflowAddrReg);
11862 // Compute the next overflow address after this argument.
11863 // (the overflow address should be kept 8-byte aligned)
11864 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11865 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11866 .addReg(OverflowDestReg)
11867 .addImm(ArgSizeA8);
11869 // Store the new overflow address.
11870 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11875 .addOperand(Segment)
11876 .addReg(NextAddrReg)
11877 .setMemRefs(MMOBegin, MMOEnd);
11879 // If we branched, emit the PHI to the front of endMBB.
11881 BuildMI(*endMBB, endMBB->begin(), DL,
11882 TII->get(X86::PHI), DestReg)
11883 .addReg(OffsetDestReg).addMBB(offsetMBB)
11884 .addReg(OverflowDestReg).addMBB(overflowMBB);
11887 // Erase the pseudo instruction
11888 MI->eraseFromParent();
11893 MachineBasicBlock *
11894 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11896 MachineBasicBlock *MBB) const {
11897 // Emit code to save XMM registers to the stack. The ABI says that the
11898 // number of registers to save is given in %al, so it's theoretically
11899 // possible to do an indirect jump trick to avoid saving all of them,
11900 // however this code takes a simpler approach and just executes all
11901 // of the stores if %al is non-zero. It's less code, and it's probably
11902 // easier on the hardware branch predictor, and stores aren't all that
11903 // expensive anyway.
11905 // Create the new basic blocks. One block contains all the XMM stores,
11906 // and one block is the final destination regardless of whether any
11907 // stores were performed.
11908 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11909 MachineFunction *F = MBB->getParent();
11910 MachineFunction::iterator MBBIter = MBB;
11912 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11913 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11914 F->insert(MBBIter, XMMSaveMBB);
11915 F->insert(MBBIter, EndMBB);
11917 // Transfer the remainder of MBB and its successor edges to EndMBB.
11918 EndMBB->splice(EndMBB->begin(), MBB,
11919 llvm::next(MachineBasicBlock::iterator(MI)),
11921 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11923 // The original block will now fall through to the XMM save block.
11924 MBB->addSuccessor(XMMSaveMBB);
11925 // The XMMSaveMBB will fall through to the end block.
11926 XMMSaveMBB->addSuccessor(EndMBB);
11928 // Now add the instructions.
11929 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11930 DebugLoc DL = MI->getDebugLoc();
11932 unsigned CountReg = MI->getOperand(0).getReg();
11933 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11934 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11936 if (!Subtarget->isTargetWin64()) {
11937 // If %al is 0, branch around the XMM save block.
11938 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11939 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11940 MBB->addSuccessor(EndMBB);
11943 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11944 // In the XMM save block, save all the XMM argument registers.
11945 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11946 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11947 MachineMemOperand *MMO =
11948 F->getMachineMemOperand(
11949 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11950 MachineMemOperand::MOStore,
11951 /*Size=*/16, /*Align=*/16);
11952 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11953 .addFrameIndex(RegSaveFrameIndex)
11954 .addImm(/*Scale=*/1)
11955 .addReg(/*IndexReg=*/0)
11956 .addImm(/*Disp=*/Offset)
11957 .addReg(/*Segment=*/0)
11958 .addReg(MI->getOperand(i).getReg())
11959 .addMemOperand(MMO);
11962 MI->eraseFromParent(); // The pseudo instruction is gone now.
11967 MachineBasicBlock *
11968 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11969 MachineBasicBlock *BB) const {
11970 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11971 DebugLoc DL = MI->getDebugLoc();
11973 // To "insert" a SELECT_CC instruction, we actually have to insert the
11974 // diamond control-flow pattern. The incoming instruction knows the
11975 // destination vreg to set, the condition code register to branch on, the
11976 // true/false values to select between, and a branch opcode to use.
11977 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11978 MachineFunction::iterator It = BB;
11984 // cmpTY ccX, r1, r2
11986 // fallthrough --> copy0MBB
11987 MachineBasicBlock *thisMBB = BB;
11988 MachineFunction *F = BB->getParent();
11989 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11990 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11991 F->insert(It, copy0MBB);
11992 F->insert(It, sinkMBB);
11994 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11995 // live into the sink and copy blocks.
11996 if (!MI->killsRegister(X86::EFLAGS)) {
11997 copy0MBB->addLiveIn(X86::EFLAGS);
11998 sinkMBB->addLiveIn(X86::EFLAGS);
12001 // Transfer the remainder of BB and its successor edges to sinkMBB.
12002 sinkMBB->splice(sinkMBB->begin(), BB,
12003 llvm::next(MachineBasicBlock::iterator(MI)),
12005 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12007 // Add the true and fallthrough blocks as its successors.
12008 BB->addSuccessor(copy0MBB);
12009 BB->addSuccessor(sinkMBB);
12011 // Create the conditional branch instruction.
12013 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12014 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12017 // %FalseValue = ...
12018 // # fallthrough to sinkMBB
12019 copy0MBB->addSuccessor(sinkMBB);
12022 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12024 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12025 TII->get(X86::PHI), MI->getOperand(0).getReg())
12026 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12027 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12029 MI->eraseFromParent(); // The pseudo instruction is gone now.
12033 MachineBasicBlock *
12034 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12035 bool Is64Bit) const {
12036 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12037 DebugLoc DL = MI->getDebugLoc();
12038 MachineFunction *MF = BB->getParent();
12039 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12041 assert(getTargetMachine().Options.EnableSegmentedStacks);
12043 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12044 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12047 // ... [Till the alloca]
12048 // If stacklet is not large enough, jump to mallocMBB
12051 // Allocate by subtracting from RSP
12052 // Jump to continueMBB
12055 // Allocate by call to runtime
12059 // [rest of original BB]
12062 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12063 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12064 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12066 MachineRegisterInfo &MRI = MF->getRegInfo();
12067 const TargetRegisterClass *AddrRegClass =
12068 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12070 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12071 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12072 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12073 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12074 sizeVReg = MI->getOperand(1).getReg(),
12075 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12077 MachineFunction::iterator MBBIter = BB;
12080 MF->insert(MBBIter, bumpMBB);
12081 MF->insert(MBBIter, mallocMBB);
12082 MF->insert(MBBIter, continueMBB);
12084 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12085 (MachineBasicBlock::iterator(MI)), BB->end());
12086 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12088 // Add code to the main basic block to check if the stack limit has been hit,
12089 // and if so, jump to mallocMBB otherwise to bumpMBB.
12090 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12091 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12092 .addReg(tmpSPVReg).addReg(sizeVReg);
12093 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12094 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12095 .addReg(SPLimitVReg);
12096 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12098 // bumpMBB simply decreases the stack pointer, since we know the current
12099 // stacklet has enough space.
12100 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12101 .addReg(SPLimitVReg);
12102 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12103 .addReg(SPLimitVReg);
12104 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12106 // Calls into a routine in libgcc to allocate more space from the heap.
12108 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12110 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12111 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12113 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12115 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12116 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12117 .addExternalSymbol("__morestack_allocate_stack_space");
12121 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12124 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12125 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12126 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12128 // Set up the CFG correctly.
12129 BB->addSuccessor(bumpMBB);
12130 BB->addSuccessor(mallocMBB);
12131 mallocMBB->addSuccessor(continueMBB);
12132 bumpMBB->addSuccessor(continueMBB);
12134 // Take care of the PHI nodes.
12135 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12136 MI->getOperand(0).getReg())
12137 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12138 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12140 // Delete the original pseudo instruction.
12141 MI->eraseFromParent();
12144 return continueMBB;
12147 MachineBasicBlock *
12148 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12149 MachineBasicBlock *BB) const {
12150 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12151 DebugLoc DL = MI->getDebugLoc();
12153 assert(!Subtarget->isTargetEnvMacho());
12155 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12156 // non-trivial part is impdef of ESP.
12158 if (Subtarget->isTargetWin64()) {
12159 if (Subtarget->isTargetCygMing()) {
12160 // ___chkstk(Mingw64):
12161 // Clobbers R10, R11, RAX and EFLAGS.
12163 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12164 .addExternalSymbol("___chkstk")
12165 .addReg(X86::RAX, RegState::Implicit)
12166 .addReg(X86::RSP, RegState::Implicit)
12167 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12168 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12169 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12171 // __chkstk(MSVCRT): does not update stack pointer.
12172 // Clobbers R10, R11 and EFLAGS.
12173 // FIXME: RAX(allocated size) might be reused and not killed.
12174 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12175 .addExternalSymbol("__chkstk")
12176 .addReg(X86::RAX, RegState::Implicit)
12177 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12178 // RAX has the offset to subtracted from RSP.
12179 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12184 const char *StackProbeSymbol =
12185 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12187 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12188 .addExternalSymbol(StackProbeSymbol)
12189 .addReg(X86::EAX, RegState::Implicit)
12190 .addReg(X86::ESP, RegState::Implicit)
12191 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12192 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12193 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12196 MI->eraseFromParent(); // The pseudo instruction is gone now.
12200 MachineBasicBlock *
12201 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12202 MachineBasicBlock *BB) const {
12203 // This is pretty easy. We're taking the value that we received from
12204 // our load from the relocation, sticking it in either RDI (x86-64)
12205 // or EAX and doing an indirect call. The return value will then
12206 // be in the normal return register.
12207 const X86InstrInfo *TII
12208 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12209 DebugLoc DL = MI->getDebugLoc();
12210 MachineFunction *F = BB->getParent();
12212 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12213 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12215 if (Subtarget->is64Bit()) {
12216 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12217 TII->get(X86::MOV64rm), X86::RDI)
12219 .addImm(0).addReg(0)
12220 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12221 MI->getOperand(3).getTargetFlags())
12223 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12224 addDirectMem(MIB, X86::RDI);
12225 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12226 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12227 TII->get(X86::MOV32rm), X86::EAX)
12229 .addImm(0).addReg(0)
12230 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12231 MI->getOperand(3).getTargetFlags())
12233 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12234 addDirectMem(MIB, X86::EAX);
12236 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12237 TII->get(X86::MOV32rm), X86::EAX)
12238 .addReg(TII->getGlobalBaseReg(F))
12239 .addImm(0).addReg(0)
12240 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12241 MI->getOperand(3).getTargetFlags())
12243 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12244 addDirectMem(MIB, X86::EAX);
12247 MI->eraseFromParent(); // The pseudo instruction is gone now.
12251 MachineBasicBlock *
12252 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12253 MachineBasicBlock *BB) const {
12254 switch (MI->getOpcode()) {
12255 default: assert(0 && "Unexpected instr type to insert");
12256 case X86::TAILJMPd64:
12257 case X86::TAILJMPr64:
12258 case X86::TAILJMPm64:
12259 assert(0 && "TAILJMP64 would not be touched here.");
12260 case X86::TCRETURNdi64:
12261 case X86::TCRETURNri64:
12262 case X86::TCRETURNmi64:
12263 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12264 // On AMD64, additional defs should be added before register allocation.
12265 if (!Subtarget->isTargetWin64()) {
12266 MI->addRegisterDefined(X86::RSI);
12267 MI->addRegisterDefined(X86::RDI);
12268 MI->addRegisterDefined(X86::XMM6);
12269 MI->addRegisterDefined(X86::XMM7);
12270 MI->addRegisterDefined(X86::XMM8);
12271 MI->addRegisterDefined(X86::XMM9);
12272 MI->addRegisterDefined(X86::XMM10);
12273 MI->addRegisterDefined(X86::XMM11);
12274 MI->addRegisterDefined(X86::XMM12);
12275 MI->addRegisterDefined(X86::XMM13);
12276 MI->addRegisterDefined(X86::XMM14);
12277 MI->addRegisterDefined(X86::XMM15);
12280 case X86::WIN_ALLOCA:
12281 return EmitLoweredWinAlloca(MI, BB);
12282 case X86::SEG_ALLOCA_32:
12283 return EmitLoweredSegAlloca(MI, BB, false);
12284 case X86::SEG_ALLOCA_64:
12285 return EmitLoweredSegAlloca(MI, BB, true);
12286 case X86::TLSCall_32:
12287 case X86::TLSCall_64:
12288 return EmitLoweredTLSCall(MI, BB);
12289 case X86::CMOV_GR8:
12290 case X86::CMOV_FR32:
12291 case X86::CMOV_FR64:
12292 case X86::CMOV_V4F32:
12293 case X86::CMOV_V2F64:
12294 case X86::CMOV_V2I64:
12295 case X86::CMOV_V8F32:
12296 case X86::CMOV_V4F64:
12297 case X86::CMOV_V4I64:
12298 case X86::CMOV_GR16:
12299 case X86::CMOV_GR32:
12300 case X86::CMOV_RFP32:
12301 case X86::CMOV_RFP64:
12302 case X86::CMOV_RFP80:
12303 return EmitLoweredSelect(MI, BB);
12305 case X86::FP32_TO_INT16_IN_MEM:
12306 case X86::FP32_TO_INT32_IN_MEM:
12307 case X86::FP32_TO_INT64_IN_MEM:
12308 case X86::FP64_TO_INT16_IN_MEM:
12309 case X86::FP64_TO_INT32_IN_MEM:
12310 case X86::FP64_TO_INT64_IN_MEM:
12311 case X86::FP80_TO_INT16_IN_MEM:
12312 case X86::FP80_TO_INT32_IN_MEM:
12313 case X86::FP80_TO_INT64_IN_MEM: {
12314 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12315 DebugLoc DL = MI->getDebugLoc();
12317 // Change the floating point control register to use "round towards zero"
12318 // mode when truncating to an integer value.
12319 MachineFunction *F = BB->getParent();
12320 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12321 addFrameReference(BuildMI(*BB, MI, DL,
12322 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12324 // Load the old value of the high byte of the control word...
12326 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12327 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12330 // Set the high part to be round to zero...
12331 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12334 // Reload the modified control word now...
12335 addFrameReference(BuildMI(*BB, MI, DL,
12336 TII->get(X86::FLDCW16m)), CWFrameIdx);
12338 // Restore the memory image of control word to original value
12339 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12342 // Get the X86 opcode to use.
12344 switch (MI->getOpcode()) {
12345 default: llvm_unreachable("illegal opcode!");
12346 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12347 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12348 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12349 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12350 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12351 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12352 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12353 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12354 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12358 MachineOperand &Op = MI->getOperand(0);
12360 AM.BaseType = X86AddressMode::RegBase;
12361 AM.Base.Reg = Op.getReg();
12363 AM.BaseType = X86AddressMode::FrameIndexBase;
12364 AM.Base.FrameIndex = Op.getIndex();
12366 Op = MI->getOperand(1);
12368 AM.Scale = Op.getImm();
12369 Op = MI->getOperand(2);
12371 AM.IndexReg = Op.getImm();
12372 Op = MI->getOperand(3);
12373 if (Op.isGlobal()) {
12374 AM.GV = Op.getGlobal();
12376 AM.Disp = Op.getImm();
12378 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12379 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12381 // Reload the original control word now.
12382 addFrameReference(BuildMI(*BB, MI, DL,
12383 TII->get(X86::FLDCW16m)), CWFrameIdx);
12385 MI->eraseFromParent(); // The pseudo instruction is gone now.
12388 // String/text processing lowering.
12389 case X86::PCMPISTRM128REG:
12390 case X86::VPCMPISTRM128REG:
12391 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12392 case X86::PCMPISTRM128MEM:
12393 case X86::VPCMPISTRM128MEM:
12394 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12395 case X86::PCMPESTRM128REG:
12396 case X86::VPCMPESTRM128REG:
12397 return EmitPCMP(MI, BB, 5, false /* in mem */);
12398 case X86::PCMPESTRM128MEM:
12399 case X86::VPCMPESTRM128MEM:
12400 return EmitPCMP(MI, BB, 5, true /* in mem */);
12402 // Thread synchronization.
12404 return EmitMonitor(MI, BB);
12406 return EmitMwait(MI, BB);
12408 // Atomic Lowering.
12409 case X86::ATOMAND32:
12410 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12411 X86::AND32ri, X86::MOV32rm,
12413 X86::NOT32r, X86::EAX,
12414 X86::GR32RegisterClass);
12415 case X86::ATOMOR32:
12416 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12417 X86::OR32ri, X86::MOV32rm,
12419 X86::NOT32r, X86::EAX,
12420 X86::GR32RegisterClass);
12421 case X86::ATOMXOR32:
12422 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12423 X86::XOR32ri, X86::MOV32rm,
12425 X86::NOT32r, X86::EAX,
12426 X86::GR32RegisterClass);
12427 case X86::ATOMNAND32:
12428 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12429 X86::AND32ri, X86::MOV32rm,
12431 X86::NOT32r, X86::EAX,
12432 X86::GR32RegisterClass, true);
12433 case X86::ATOMMIN32:
12434 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12435 case X86::ATOMMAX32:
12436 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12437 case X86::ATOMUMIN32:
12438 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12439 case X86::ATOMUMAX32:
12440 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12442 case X86::ATOMAND16:
12443 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12444 X86::AND16ri, X86::MOV16rm,
12446 X86::NOT16r, X86::AX,
12447 X86::GR16RegisterClass);
12448 case X86::ATOMOR16:
12449 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12450 X86::OR16ri, X86::MOV16rm,
12452 X86::NOT16r, X86::AX,
12453 X86::GR16RegisterClass);
12454 case X86::ATOMXOR16:
12455 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12456 X86::XOR16ri, X86::MOV16rm,
12458 X86::NOT16r, X86::AX,
12459 X86::GR16RegisterClass);
12460 case X86::ATOMNAND16:
12461 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12462 X86::AND16ri, X86::MOV16rm,
12464 X86::NOT16r, X86::AX,
12465 X86::GR16RegisterClass, true);
12466 case X86::ATOMMIN16:
12467 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12468 case X86::ATOMMAX16:
12469 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12470 case X86::ATOMUMIN16:
12471 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12472 case X86::ATOMUMAX16:
12473 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12475 case X86::ATOMAND8:
12476 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12477 X86::AND8ri, X86::MOV8rm,
12479 X86::NOT8r, X86::AL,
12480 X86::GR8RegisterClass);
12482 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12483 X86::OR8ri, X86::MOV8rm,
12485 X86::NOT8r, X86::AL,
12486 X86::GR8RegisterClass);
12487 case X86::ATOMXOR8:
12488 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12489 X86::XOR8ri, X86::MOV8rm,
12491 X86::NOT8r, X86::AL,
12492 X86::GR8RegisterClass);
12493 case X86::ATOMNAND8:
12494 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12495 X86::AND8ri, X86::MOV8rm,
12497 X86::NOT8r, X86::AL,
12498 X86::GR8RegisterClass, true);
12499 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12500 // This group is for 64-bit host.
12501 case X86::ATOMAND64:
12502 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12503 X86::AND64ri32, X86::MOV64rm,
12505 X86::NOT64r, X86::RAX,
12506 X86::GR64RegisterClass);
12507 case X86::ATOMOR64:
12508 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12509 X86::OR64ri32, X86::MOV64rm,
12511 X86::NOT64r, X86::RAX,
12512 X86::GR64RegisterClass);
12513 case X86::ATOMXOR64:
12514 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12515 X86::XOR64ri32, X86::MOV64rm,
12517 X86::NOT64r, X86::RAX,
12518 X86::GR64RegisterClass);
12519 case X86::ATOMNAND64:
12520 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12521 X86::AND64ri32, X86::MOV64rm,
12523 X86::NOT64r, X86::RAX,
12524 X86::GR64RegisterClass, true);
12525 case X86::ATOMMIN64:
12526 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12527 case X86::ATOMMAX64:
12528 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12529 case X86::ATOMUMIN64:
12530 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12531 case X86::ATOMUMAX64:
12532 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12534 // This group does 64-bit operations on a 32-bit host.
12535 case X86::ATOMAND6432:
12536 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12537 X86::AND32rr, X86::AND32rr,
12538 X86::AND32ri, X86::AND32ri,
12540 case X86::ATOMOR6432:
12541 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12542 X86::OR32rr, X86::OR32rr,
12543 X86::OR32ri, X86::OR32ri,
12545 case X86::ATOMXOR6432:
12546 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12547 X86::XOR32rr, X86::XOR32rr,
12548 X86::XOR32ri, X86::XOR32ri,
12550 case X86::ATOMNAND6432:
12551 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12552 X86::AND32rr, X86::AND32rr,
12553 X86::AND32ri, X86::AND32ri,
12555 case X86::ATOMADD6432:
12556 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12557 X86::ADD32rr, X86::ADC32rr,
12558 X86::ADD32ri, X86::ADC32ri,
12560 case X86::ATOMSUB6432:
12561 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12562 X86::SUB32rr, X86::SBB32rr,
12563 X86::SUB32ri, X86::SBB32ri,
12565 case X86::ATOMSWAP6432:
12566 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12567 X86::MOV32rr, X86::MOV32rr,
12568 X86::MOV32ri, X86::MOV32ri,
12570 case X86::VASTART_SAVE_XMM_REGS:
12571 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12573 case X86::VAARG_64:
12574 return EmitVAARG64WithCustomInserter(MI, BB);
12578 //===----------------------------------------------------------------------===//
12579 // X86 Optimization Hooks
12580 //===----------------------------------------------------------------------===//
12582 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12586 const SelectionDAG &DAG,
12587 unsigned Depth) const {
12588 unsigned Opc = Op.getOpcode();
12589 assert((Opc >= ISD::BUILTIN_OP_END ||
12590 Opc == ISD::INTRINSIC_WO_CHAIN ||
12591 Opc == ISD::INTRINSIC_W_CHAIN ||
12592 Opc == ISD::INTRINSIC_VOID) &&
12593 "Should use MaskedValueIsZero if you don't know whether Op"
12594 " is a target node!");
12596 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12610 // These nodes' second result is a boolean.
12611 if (Op.getResNo() == 0)
12614 case X86ISD::SETCC:
12615 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12616 Mask.getBitWidth() - 1);
12618 case ISD::INTRINSIC_WO_CHAIN: {
12619 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12620 unsigned NumLoBits = 0;
12623 case Intrinsic::x86_sse_movmsk_ps:
12624 case Intrinsic::x86_avx_movmsk_ps_256:
12625 case Intrinsic::x86_sse2_movmsk_pd:
12626 case Intrinsic::x86_avx_movmsk_pd_256:
12627 case Intrinsic::x86_mmx_pmovmskb:
12628 case Intrinsic::x86_sse2_pmovmskb_128: {
12629 // High bits of movmskp{s|d}, pmovmskb are known zero.
12631 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12632 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12633 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12634 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12635 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12636 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12638 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12639 Mask.getBitWidth() - NumLoBits);
12648 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12649 unsigned Depth) const {
12650 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12651 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12652 return Op.getValueType().getScalarType().getSizeInBits();
12658 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12659 /// node is a GlobalAddress + offset.
12660 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12661 const GlobalValue* &GA,
12662 int64_t &Offset) const {
12663 if (N->getOpcode() == X86ISD::Wrapper) {
12664 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12665 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12666 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12670 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12673 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12674 /// same as extracting the high 128-bit part of 256-bit vector and then
12675 /// inserting the result into the low part of a new 256-bit vector
12676 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12677 EVT VT = SVOp->getValueType(0);
12678 int NumElems = VT.getVectorNumElements();
12680 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12681 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12682 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12683 SVOp->getMaskElt(j) >= 0)
12689 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12690 /// same as extracting the low 128-bit part of 256-bit vector and then
12691 /// inserting the result into the high part of a new 256-bit vector
12692 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12693 EVT VT = SVOp->getValueType(0);
12694 int NumElems = VT.getVectorNumElements();
12696 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12697 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12698 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12699 SVOp->getMaskElt(j) >= 0)
12705 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12706 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12707 TargetLowering::DAGCombinerInfo &DCI) {
12708 DebugLoc dl = N->getDebugLoc();
12709 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12710 SDValue V1 = SVOp->getOperand(0);
12711 SDValue V2 = SVOp->getOperand(1);
12712 EVT VT = SVOp->getValueType(0);
12713 int NumElems = VT.getVectorNumElements();
12715 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12716 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12720 // V UNDEF BUILD_VECTOR UNDEF
12722 // CONCAT_VECTOR CONCAT_VECTOR
12725 // RESULT: V + zero extended
12727 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12728 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12729 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12732 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12735 // To match the shuffle mask, the first half of the mask should
12736 // be exactly the first vector, and all the rest a splat with the
12737 // first element of the second one.
12738 for (int i = 0; i < NumElems/2; ++i)
12739 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12740 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12743 // Emit a zeroed vector and insert the desired subvector on its
12745 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12746 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12747 DAG.getConstant(0, MVT::i32), DAG, dl);
12748 return DCI.CombineTo(N, InsV);
12751 //===--------------------------------------------------------------------===//
12752 // Combine some shuffles into subvector extracts and inserts:
12755 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12756 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12757 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12759 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12760 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12761 return DCI.CombineTo(N, InsV);
12764 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12765 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12766 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12767 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12768 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12769 return DCI.CombineTo(N, InsV);
12775 /// PerformShuffleCombine - Performs several different shuffle combines.
12776 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12777 TargetLowering::DAGCombinerInfo &DCI,
12778 const X86Subtarget *Subtarget) {
12779 DebugLoc dl = N->getDebugLoc();
12780 EVT VT = N->getValueType(0);
12782 // Don't create instructions with illegal types after legalize types has run.
12783 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12784 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12787 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12788 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12789 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12790 return PerformShuffleCombine256(N, DAG, DCI);
12792 // Only handle 128 wide vector from here on.
12793 if (VT.getSizeInBits() != 128)
12796 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12797 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12798 // consecutive, non-overlapping, and in the right order.
12799 SmallVector<SDValue, 16> Elts;
12800 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12801 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12803 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12806 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12807 /// generation and convert it from being a bunch of shuffles and extracts
12808 /// to a simple store and scalar loads to extract the elements.
12809 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12810 const TargetLowering &TLI) {
12811 SDValue InputVector = N->getOperand(0);
12813 // Only operate on vectors of 4 elements, where the alternative shuffling
12814 // gets to be more expensive.
12815 if (InputVector.getValueType() != MVT::v4i32)
12818 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12819 // single use which is a sign-extend or zero-extend, and all elements are
12821 SmallVector<SDNode *, 4> Uses;
12822 unsigned ExtractedElements = 0;
12823 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12824 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12825 if (UI.getUse().getResNo() != InputVector.getResNo())
12828 SDNode *Extract = *UI;
12829 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12832 if (Extract->getValueType(0) != MVT::i32)
12834 if (!Extract->hasOneUse())
12836 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12837 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12839 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12842 // Record which element was extracted.
12843 ExtractedElements |=
12844 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12846 Uses.push_back(Extract);
12849 // If not all the elements were used, this may not be worthwhile.
12850 if (ExtractedElements != 15)
12853 // Ok, we've now decided to do the transformation.
12854 DebugLoc dl = InputVector.getDebugLoc();
12856 // Store the value to a temporary stack slot.
12857 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12858 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12859 MachinePointerInfo(), false, false, 0);
12861 // Replace each use (extract) with a load of the appropriate element.
12862 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12863 UE = Uses.end(); UI != UE; ++UI) {
12864 SDNode *Extract = *UI;
12866 // cOMpute the element's address.
12867 SDValue Idx = Extract->getOperand(1);
12869 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12870 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12871 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12873 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12874 StackPtr, OffsetVal);
12876 // Load the scalar.
12877 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12878 ScalarAddr, MachinePointerInfo(),
12879 false, false, false, 0);
12881 // Replace the exact with the load.
12882 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12885 // The replacement was made in place; don't return anything.
12889 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12891 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12892 const X86Subtarget *Subtarget) {
12893 DebugLoc DL = N->getDebugLoc();
12894 SDValue Cond = N->getOperand(0);
12895 // Get the LHS/RHS of the select.
12896 SDValue LHS = N->getOperand(1);
12897 SDValue RHS = N->getOperand(2);
12898 EVT VT = LHS.getValueType();
12900 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12901 // instructions match the semantics of the common C idiom x<y?x:y but not
12902 // x<=y?x:y, because of how they handle negative zero (which can be
12903 // ignored in unsafe-math mode).
12904 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12905 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12906 (Subtarget->hasXMMInt() ||
12907 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12908 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12910 unsigned Opcode = 0;
12911 // Check for x CC y ? x : y.
12912 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12913 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12917 // Converting this to a min would handle NaNs incorrectly, and swapping
12918 // the operands would cause it to handle comparisons between positive
12919 // and negative zero incorrectly.
12920 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12921 if (!DAG.getTarget().Options.UnsafeFPMath &&
12922 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12924 std::swap(LHS, RHS);
12926 Opcode = X86ISD::FMIN;
12929 // Converting this to a min would handle comparisons between positive
12930 // and negative zero incorrectly.
12931 if (!DAG.getTarget().Options.UnsafeFPMath &&
12932 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12934 Opcode = X86ISD::FMIN;
12937 // Converting this to a min would handle both negative zeros and NaNs
12938 // incorrectly, but we can swap the operands to fix both.
12939 std::swap(LHS, RHS);
12943 Opcode = X86ISD::FMIN;
12947 // Converting this to a max would handle comparisons between positive
12948 // and negative zero incorrectly.
12949 if (!DAG.getTarget().Options.UnsafeFPMath &&
12950 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12952 Opcode = X86ISD::FMAX;
12955 // Converting this to a max would handle NaNs incorrectly, and swapping
12956 // the operands would cause it to handle comparisons between positive
12957 // and negative zero incorrectly.
12958 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12959 if (!DAG.getTarget().Options.UnsafeFPMath &&
12960 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12962 std::swap(LHS, RHS);
12964 Opcode = X86ISD::FMAX;
12967 // Converting this to a max would handle both negative zeros and NaNs
12968 // incorrectly, but we can swap the operands to fix both.
12969 std::swap(LHS, RHS);
12973 Opcode = X86ISD::FMAX;
12976 // Check for x CC y ? y : x -- a min/max with reversed arms.
12977 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12978 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12982 // Converting this to a min would handle comparisons between positive
12983 // and negative zero incorrectly, and swapping the operands would
12984 // cause it to handle NaNs incorrectly.
12985 if (!DAG.getTarget().Options.UnsafeFPMath &&
12986 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12987 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12989 std::swap(LHS, RHS);
12991 Opcode = X86ISD::FMIN;
12994 // Converting this to a min would handle NaNs incorrectly.
12995 if (!DAG.getTarget().Options.UnsafeFPMath &&
12996 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12998 Opcode = X86ISD::FMIN;
13001 // Converting this to a min would handle both negative zeros and NaNs
13002 // incorrectly, but we can swap the operands to fix both.
13003 std::swap(LHS, RHS);
13007 Opcode = X86ISD::FMIN;
13011 // Converting this to a max would handle NaNs incorrectly.
13012 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13014 Opcode = X86ISD::FMAX;
13017 // Converting this to a max would handle comparisons between positive
13018 // and negative zero incorrectly, and swapping the operands would
13019 // cause it to handle NaNs incorrectly.
13020 if (!DAG.getTarget().Options.UnsafeFPMath &&
13021 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13022 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13024 std::swap(LHS, RHS);
13026 Opcode = X86ISD::FMAX;
13029 // Converting this to a max would handle both negative zeros and NaNs
13030 // incorrectly, but we can swap the operands to fix both.
13031 std::swap(LHS, RHS);
13035 Opcode = X86ISD::FMAX;
13041 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13044 // If this is a select between two integer constants, try to do some
13046 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13047 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13048 // Don't do this for crazy integer types.
13049 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13050 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13051 // so that TrueC (the true value) is larger than FalseC.
13052 bool NeedsCondInvert = false;
13054 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13055 // Efficiently invertible.
13056 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13057 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13058 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13059 NeedsCondInvert = true;
13060 std::swap(TrueC, FalseC);
13063 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13064 if (FalseC->getAPIntValue() == 0 &&
13065 TrueC->getAPIntValue().isPowerOf2()) {
13066 if (NeedsCondInvert) // Invert the condition if needed.
13067 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13068 DAG.getConstant(1, Cond.getValueType()));
13070 // Zero extend the condition if needed.
13071 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13073 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13074 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13075 DAG.getConstant(ShAmt, MVT::i8));
13078 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13079 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13080 if (NeedsCondInvert) // Invert the condition if needed.
13081 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13082 DAG.getConstant(1, Cond.getValueType()));
13084 // Zero extend the condition if needed.
13085 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13086 FalseC->getValueType(0), Cond);
13087 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13088 SDValue(FalseC, 0));
13091 // Optimize cases that will turn into an LEA instruction. This requires
13092 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13093 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13094 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13095 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13097 bool isFastMultiplier = false;
13099 switch ((unsigned char)Diff) {
13101 case 1: // result = add base, cond
13102 case 2: // result = lea base( , cond*2)
13103 case 3: // result = lea base(cond, cond*2)
13104 case 4: // result = lea base( , cond*4)
13105 case 5: // result = lea base(cond, cond*4)
13106 case 8: // result = lea base( , cond*8)
13107 case 9: // result = lea base(cond, cond*8)
13108 isFastMultiplier = true;
13113 if (isFastMultiplier) {
13114 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13115 if (NeedsCondInvert) // Invert the condition if needed.
13116 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13117 DAG.getConstant(1, Cond.getValueType()));
13119 // Zero extend the condition if needed.
13120 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13122 // Scale the condition by the difference.
13124 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13125 DAG.getConstant(Diff, Cond.getValueType()));
13127 // Add the base if non-zero.
13128 if (FalseC->getAPIntValue() != 0)
13129 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13130 SDValue(FalseC, 0));
13140 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13141 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13142 TargetLowering::DAGCombinerInfo &DCI) {
13143 DebugLoc DL = N->getDebugLoc();
13145 // If the flag operand isn't dead, don't touch this CMOV.
13146 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13149 SDValue FalseOp = N->getOperand(0);
13150 SDValue TrueOp = N->getOperand(1);
13151 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13152 SDValue Cond = N->getOperand(3);
13153 if (CC == X86::COND_E || CC == X86::COND_NE) {
13154 switch (Cond.getOpcode()) {
13158 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13159 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13160 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13164 // If this is a select between two integer constants, try to do some
13165 // optimizations. Note that the operands are ordered the opposite of SELECT
13167 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13168 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13169 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13170 // larger than FalseC (the false value).
13171 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13172 CC = X86::GetOppositeBranchCondition(CC);
13173 std::swap(TrueC, FalseC);
13176 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13177 // This is efficient for any integer data type (including i8/i16) and
13179 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13180 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13181 DAG.getConstant(CC, MVT::i8), Cond);
13183 // Zero extend the condition if needed.
13184 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13186 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13187 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13188 DAG.getConstant(ShAmt, MVT::i8));
13189 if (N->getNumValues() == 2) // Dead flag value?
13190 return DCI.CombineTo(N, Cond, SDValue());
13194 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13195 // for any integer data type, including i8/i16.
13196 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13197 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13198 DAG.getConstant(CC, MVT::i8), Cond);
13200 // Zero extend the condition if needed.
13201 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13202 FalseC->getValueType(0), Cond);
13203 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13204 SDValue(FalseC, 0));
13206 if (N->getNumValues() == 2) // Dead flag value?
13207 return DCI.CombineTo(N, Cond, SDValue());
13211 // Optimize cases that will turn into an LEA instruction. This requires
13212 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13213 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13214 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13215 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13217 bool isFastMultiplier = false;
13219 switch ((unsigned char)Diff) {
13221 case 1: // result = add base, cond
13222 case 2: // result = lea base( , cond*2)
13223 case 3: // result = lea base(cond, cond*2)
13224 case 4: // result = lea base( , cond*4)
13225 case 5: // result = lea base(cond, cond*4)
13226 case 8: // result = lea base( , cond*8)
13227 case 9: // result = lea base(cond, cond*8)
13228 isFastMultiplier = true;
13233 if (isFastMultiplier) {
13234 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13235 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13236 DAG.getConstant(CC, MVT::i8), Cond);
13237 // Zero extend the condition if needed.
13238 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13240 // Scale the condition by the difference.
13242 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13243 DAG.getConstant(Diff, Cond.getValueType()));
13245 // Add the base if non-zero.
13246 if (FalseC->getAPIntValue() != 0)
13247 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13248 SDValue(FalseC, 0));
13249 if (N->getNumValues() == 2) // Dead flag value?
13250 return DCI.CombineTo(N, Cond, SDValue());
13260 /// PerformMulCombine - Optimize a single multiply with constant into two
13261 /// in order to implement it with two cheaper instructions, e.g.
13262 /// LEA + SHL, LEA + LEA.
13263 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13264 TargetLowering::DAGCombinerInfo &DCI) {
13265 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13268 EVT VT = N->getValueType(0);
13269 if (VT != MVT::i64)
13272 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13275 uint64_t MulAmt = C->getZExtValue();
13276 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13279 uint64_t MulAmt1 = 0;
13280 uint64_t MulAmt2 = 0;
13281 if ((MulAmt % 9) == 0) {
13283 MulAmt2 = MulAmt / 9;
13284 } else if ((MulAmt % 5) == 0) {
13286 MulAmt2 = MulAmt / 5;
13287 } else if ((MulAmt % 3) == 0) {
13289 MulAmt2 = MulAmt / 3;
13292 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13293 DebugLoc DL = N->getDebugLoc();
13295 if (isPowerOf2_64(MulAmt2) &&
13296 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13297 // If second multiplifer is pow2, issue it first. We want the multiply by
13298 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13300 std::swap(MulAmt1, MulAmt2);
13303 if (isPowerOf2_64(MulAmt1))
13304 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13305 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13307 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13308 DAG.getConstant(MulAmt1, VT));
13310 if (isPowerOf2_64(MulAmt2))
13311 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13312 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13314 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13315 DAG.getConstant(MulAmt2, VT));
13317 // Do not add new nodes to DAG combiner worklist.
13318 DCI.CombineTo(N, NewMul, false);
13323 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13324 SDValue N0 = N->getOperand(0);
13325 SDValue N1 = N->getOperand(1);
13326 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13327 EVT VT = N0.getValueType();
13329 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13330 // since the result of setcc_c is all zero's or all ones.
13331 if (VT.isInteger() && !VT.isVector() &&
13332 N1C && N0.getOpcode() == ISD::AND &&
13333 N0.getOperand(1).getOpcode() == ISD::Constant) {
13334 SDValue N00 = N0.getOperand(0);
13335 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13336 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13337 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13338 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13339 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13340 APInt ShAmt = N1C->getAPIntValue();
13341 Mask = Mask.shl(ShAmt);
13343 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13344 N00, DAG.getConstant(Mask, VT));
13349 // Hardware support for vector shifts is sparse which makes us scalarize the
13350 // vector operations in many cases. Also, on sandybridge ADD is faster than
13352 // (shl V, 1) -> add V,V
13353 if (isSplatVector(N1.getNode())) {
13354 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13355 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13356 // We shift all of the values by one. In many cases we do not have
13357 // hardware support for this operation. This is better expressed as an ADD
13359 if (N1C && (1 == N1C->getZExtValue())) {
13360 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13367 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13369 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13370 const X86Subtarget *Subtarget) {
13371 EVT VT = N->getValueType(0);
13372 if (N->getOpcode() == ISD::SHL) {
13373 SDValue V = PerformSHLCombine(N, DAG);
13374 if (V.getNode()) return V;
13377 // On X86 with SSE2 support, we can transform this to a vector shift if
13378 // all elements are shifted by the same amount. We can't do this in legalize
13379 // because the a constant vector is typically transformed to a constant pool
13380 // so we have no knowledge of the shift amount.
13381 if (!Subtarget->hasXMMInt())
13384 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13385 (!Subtarget->hasAVX2() ||
13386 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13389 SDValue ShAmtOp = N->getOperand(1);
13390 EVT EltVT = VT.getVectorElementType();
13391 DebugLoc DL = N->getDebugLoc();
13392 SDValue BaseShAmt = SDValue();
13393 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13394 unsigned NumElts = VT.getVectorNumElements();
13396 for (; i != NumElts; ++i) {
13397 SDValue Arg = ShAmtOp.getOperand(i);
13398 if (Arg.getOpcode() == ISD::UNDEF) continue;
13402 for (; i != NumElts; ++i) {
13403 SDValue Arg = ShAmtOp.getOperand(i);
13404 if (Arg.getOpcode() == ISD::UNDEF) continue;
13405 if (Arg != BaseShAmt) {
13409 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13410 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13411 SDValue InVec = ShAmtOp.getOperand(0);
13412 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13413 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13415 for (; i != NumElts; ++i) {
13416 SDValue Arg = InVec.getOperand(i);
13417 if (Arg.getOpcode() == ISD::UNDEF) continue;
13421 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13422 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13423 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13424 if (C->getZExtValue() == SplatIdx)
13425 BaseShAmt = InVec.getOperand(1);
13428 if (BaseShAmt.getNode() == 0)
13429 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13430 DAG.getIntPtrConstant(0));
13434 // The shift amount is an i32.
13435 if (EltVT.bitsGT(MVT::i32))
13436 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13437 else if (EltVT.bitsLT(MVT::i32))
13438 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13440 // The shift amount is identical so we can do a vector shift.
13441 SDValue ValOp = N->getOperand(0);
13442 switch (N->getOpcode()) {
13444 llvm_unreachable("Unknown shift opcode!");
13447 if (VT == MVT::v2i64)
13448 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13449 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13451 if (VT == MVT::v4i32)
13452 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13453 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13455 if (VT == MVT::v8i16)
13456 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13457 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13459 if (VT == MVT::v4i64)
13460 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13461 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13463 if (VT == MVT::v8i32)
13464 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13465 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13467 if (VT == MVT::v16i16)
13468 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13469 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13473 if (VT == MVT::v4i32)
13474 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13475 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13477 if (VT == MVT::v8i16)
13478 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13479 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13481 if (VT == MVT::v8i32)
13482 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13483 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13485 if (VT == MVT::v16i16)
13486 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13487 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13491 if (VT == MVT::v2i64)
13492 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13493 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13495 if (VT == MVT::v4i32)
13496 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13497 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13499 if (VT == MVT::v8i16)
13500 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13501 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13503 if (VT == MVT::v4i64)
13504 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13505 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13507 if (VT == MVT::v8i32)
13508 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13509 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13511 if (VT == MVT::v16i16)
13512 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13513 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13521 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13522 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13523 // and friends. Likewise for OR -> CMPNEQSS.
13524 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13525 TargetLowering::DAGCombinerInfo &DCI,
13526 const X86Subtarget *Subtarget) {
13529 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13530 // we're requiring SSE2 for both.
13531 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13532 SDValue N0 = N->getOperand(0);
13533 SDValue N1 = N->getOperand(1);
13534 SDValue CMP0 = N0->getOperand(1);
13535 SDValue CMP1 = N1->getOperand(1);
13536 DebugLoc DL = N->getDebugLoc();
13538 // The SETCCs should both refer to the same CMP.
13539 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13542 SDValue CMP00 = CMP0->getOperand(0);
13543 SDValue CMP01 = CMP0->getOperand(1);
13544 EVT VT = CMP00.getValueType();
13546 if (VT == MVT::f32 || VT == MVT::f64) {
13547 bool ExpectingFlags = false;
13548 // Check for any users that want flags:
13549 for (SDNode::use_iterator UI = N->use_begin(),
13551 !ExpectingFlags && UI != UE; ++UI)
13552 switch (UI->getOpcode()) {
13557 ExpectingFlags = true;
13559 case ISD::CopyToReg:
13560 case ISD::SIGN_EXTEND:
13561 case ISD::ZERO_EXTEND:
13562 case ISD::ANY_EXTEND:
13566 if (!ExpectingFlags) {
13567 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13568 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13570 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13571 X86::CondCode tmp = cc0;
13576 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13577 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13578 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13579 X86ISD::NodeType NTOperator = is64BitFP ?
13580 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13581 // FIXME: need symbolic constants for these magic numbers.
13582 // See X86ATTInstPrinter.cpp:printSSECC().
13583 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13584 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13585 DAG.getConstant(x86cc, MVT::i8));
13586 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13588 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13589 DAG.getConstant(1, MVT::i32));
13590 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13591 return OneBitOfTruth;
13599 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13600 /// so it can be folded inside ANDNP.
13601 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13602 EVT VT = N->getValueType(0);
13604 // Match direct AllOnes for 128 and 256-bit vectors
13605 if (ISD::isBuildVectorAllOnes(N))
13608 // Look through a bit convert.
13609 if (N->getOpcode() == ISD::BITCAST)
13610 N = N->getOperand(0).getNode();
13612 // Sometimes the operand may come from a insert_subvector building a 256-bit
13614 if (VT.getSizeInBits() == 256 &&
13615 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13616 SDValue V1 = N->getOperand(0);
13617 SDValue V2 = N->getOperand(1);
13619 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13620 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13621 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13622 ISD::isBuildVectorAllOnes(V2.getNode()))
13629 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13630 TargetLowering::DAGCombinerInfo &DCI,
13631 const X86Subtarget *Subtarget) {
13632 if (DCI.isBeforeLegalizeOps())
13635 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13639 EVT VT = N->getValueType(0);
13641 // Create ANDN, BLSI, and BLSR instructions
13642 // BLSI is X & (-X)
13643 // BLSR is X & (X-1)
13644 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13645 SDValue N0 = N->getOperand(0);
13646 SDValue N1 = N->getOperand(1);
13647 DebugLoc DL = N->getDebugLoc();
13649 // Check LHS for not
13650 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13651 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13652 // Check RHS for not
13653 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13654 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13656 // Check LHS for neg
13657 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13658 isZero(N0.getOperand(0)))
13659 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13661 // Check RHS for neg
13662 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13663 isZero(N1.getOperand(0)))
13664 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13666 // Check LHS for X-1
13667 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13668 isAllOnes(N0.getOperand(1)))
13669 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13671 // Check RHS for X-1
13672 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13673 isAllOnes(N1.getOperand(1)))
13674 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13679 // Want to form ANDNP nodes:
13680 // 1) In the hopes of then easily combining them with OR and AND nodes
13681 // to form PBLEND/PSIGN.
13682 // 2) To match ANDN packed intrinsics
13683 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13686 SDValue N0 = N->getOperand(0);
13687 SDValue N1 = N->getOperand(1);
13688 DebugLoc DL = N->getDebugLoc();
13690 // Check LHS for vnot
13691 if (N0.getOpcode() == ISD::XOR &&
13692 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13693 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13694 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13696 // Check RHS for vnot
13697 if (N1.getOpcode() == ISD::XOR &&
13698 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13699 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13700 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13705 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13706 TargetLowering::DAGCombinerInfo &DCI,
13707 const X86Subtarget *Subtarget) {
13708 if (DCI.isBeforeLegalizeOps())
13711 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13715 EVT VT = N->getValueType(0);
13717 SDValue N0 = N->getOperand(0);
13718 SDValue N1 = N->getOperand(1);
13720 // look for psign/blend
13721 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13722 if (!Subtarget->hasSSSE3orAVX() ||
13723 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13726 // Canonicalize pandn to RHS
13727 if (N0.getOpcode() == X86ISD::ANDNP)
13729 // or (and (m, x), (pandn m, y))
13730 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13731 SDValue Mask = N1.getOperand(0);
13732 SDValue X = N1.getOperand(1);
13734 if (N0.getOperand(0) == Mask)
13735 Y = N0.getOperand(1);
13736 if (N0.getOperand(1) == Mask)
13737 Y = N0.getOperand(0);
13739 // Check to see if the mask appeared in both the AND and ANDNP and
13743 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13744 if (Mask.getOpcode() != ISD::BITCAST ||
13745 X.getOpcode() != ISD::BITCAST ||
13746 Y.getOpcode() != ISD::BITCAST)
13749 // Look through mask bitcast.
13750 Mask = Mask.getOperand(0);
13751 EVT MaskVT = Mask.getValueType();
13753 // Validate that the Mask operand is a vector sra node. The sra node
13754 // will be an intrinsic.
13755 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13758 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13759 // there is no psrai.b
13760 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13761 case Intrinsic::x86_sse2_psrai_w:
13762 case Intrinsic::x86_sse2_psrai_d:
13763 case Intrinsic::x86_avx2_psrai_w:
13764 case Intrinsic::x86_avx2_psrai_d:
13766 default: return SDValue();
13769 // Check that the SRA is all signbits.
13770 SDValue SraC = Mask.getOperand(2);
13771 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13772 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13773 if ((SraAmt + 1) != EltBits)
13776 DebugLoc DL = N->getDebugLoc();
13778 // Now we know we at least have a plendvb with the mask val. See if
13779 // we can form a psignb/w/d.
13780 // psign = x.type == y.type == mask.type && y = sub(0, x);
13781 X = X.getOperand(0);
13782 Y = Y.getOperand(0);
13783 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13784 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13785 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13786 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13787 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13788 Mask.getOperand(1));
13789 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13791 // PBLENDVB only available on SSE 4.1
13792 if (!Subtarget->hasSSE41orAVX())
13795 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13797 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13798 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13799 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13800 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13801 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13805 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13808 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13809 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13811 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13813 if (!N0.hasOneUse() || !N1.hasOneUse())
13816 SDValue ShAmt0 = N0.getOperand(1);
13817 if (ShAmt0.getValueType() != MVT::i8)
13819 SDValue ShAmt1 = N1.getOperand(1);
13820 if (ShAmt1.getValueType() != MVT::i8)
13822 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13823 ShAmt0 = ShAmt0.getOperand(0);
13824 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13825 ShAmt1 = ShAmt1.getOperand(0);
13827 DebugLoc DL = N->getDebugLoc();
13828 unsigned Opc = X86ISD::SHLD;
13829 SDValue Op0 = N0.getOperand(0);
13830 SDValue Op1 = N1.getOperand(0);
13831 if (ShAmt0.getOpcode() == ISD::SUB) {
13832 Opc = X86ISD::SHRD;
13833 std::swap(Op0, Op1);
13834 std::swap(ShAmt0, ShAmt1);
13837 unsigned Bits = VT.getSizeInBits();
13838 if (ShAmt1.getOpcode() == ISD::SUB) {
13839 SDValue Sum = ShAmt1.getOperand(0);
13840 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13841 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13842 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13843 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13844 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13845 return DAG.getNode(Opc, DL, VT,
13847 DAG.getNode(ISD::TRUNCATE, DL,
13850 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13851 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13853 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13854 return DAG.getNode(Opc, DL, VT,
13855 N0.getOperand(0), N1.getOperand(0),
13856 DAG.getNode(ISD::TRUNCATE, DL,
13863 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13864 TargetLowering::DAGCombinerInfo &DCI,
13865 const X86Subtarget *Subtarget) {
13866 if (DCI.isBeforeLegalizeOps())
13869 EVT VT = N->getValueType(0);
13871 if (VT != MVT::i32 && VT != MVT::i64)
13874 // Create BLSMSK instructions by finding X ^ (X-1)
13875 SDValue N0 = N->getOperand(0);
13876 SDValue N1 = N->getOperand(1);
13877 DebugLoc DL = N->getDebugLoc();
13879 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13880 isAllOnes(N0.getOperand(1)))
13881 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13883 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13884 isAllOnes(N1.getOperand(1)))
13885 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13890 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13891 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13892 const X86Subtarget *Subtarget) {
13893 LoadSDNode *Ld = cast<LoadSDNode>(N);
13894 EVT RegVT = Ld->getValueType(0);
13895 EVT MemVT = Ld->getMemoryVT();
13896 DebugLoc dl = Ld->getDebugLoc();
13897 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13899 ISD::LoadExtType Ext = Ld->getExtensionType();
13901 // If this is a vector EXT Load then attempt to optimize it using a
13902 // shuffle. We need SSE4 for the shuffles.
13903 // TODO: It is possible to support ZExt by zeroing the undef values
13904 // during the shuffle phase or after the shuffle.
13905 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13906 assert(MemVT != RegVT && "Cannot extend to the same type");
13907 assert(MemVT.isVector() && "Must load a vector from memory");
13909 unsigned NumElems = RegVT.getVectorNumElements();
13910 unsigned RegSz = RegVT.getSizeInBits();
13911 unsigned MemSz = MemVT.getSizeInBits();
13912 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13913 // All sizes must be a power of two
13914 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13916 // Attempt to load the original value using a single load op.
13917 // Find a scalar type which is equal to the loaded word size.
13918 MVT SclrLoadTy = MVT::i8;
13919 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13920 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13921 MVT Tp = (MVT::SimpleValueType)tp;
13922 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
13928 // Proceed if a load word is found.
13929 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13931 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13932 RegSz/SclrLoadTy.getSizeInBits());
13934 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13935 RegSz/MemVT.getScalarType().getSizeInBits());
13936 // Can't shuffle using an illegal type.
13937 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13939 // Perform a single load.
13940 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13942 Ld->getPointerInfo(), Ld->isVolatile(),
13943 Ld->isNonTemporal(), Ld->isInvariant(),
13944 Ld->getAlignment());
13946 // Insert the word loaded into a vector.
13947 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13948 LoadUnitVecVT, ScalarLoad);
13950 // Bitcast the loaded value to a vector of the original element type, in
13951 // the size of the target vector type.
13952 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13953 unsigned SizeRatio = RegSz/MemSz;
13955 // Redistribute the loaded elements into the different locations.
13956 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13957 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13959 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13960 DAG.getUNDEF(SlicedVec.getValueType()),
13961 ShuffleVec.data());
13963 // Bitcast to the requested type.
13964 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13965 // Replace the original load with the new sequence
13966 // and return the new chain.
13967 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13968 return SDValue(ScalarLoad.getNode(), 1);
13974 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13975 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13976 const X86Subtarget *Subtarget) {
13977 StoreSDNode *St = cast<StoreSDNode>(N);
13978 EVT VT = St->getValue().getValueType();
13979 EVT StVT = St->getMemoryVT();
13980 DebugLoc dl = St->getDebugLoc();
13981 SDValue StoredVal = St->getOperand(1);
13982 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13984 // If we are saving a concatenation of two XMM registers, perform two stores.
13985 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13986 // 128-bit ones. If in the future the cost becomes only one memory access the
13987 // first version would be better.
13988 if (VT.getSizeInBits() == 256 &&
13989 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13990 StoredVal.getNumOperands() == 2) {
13992 SDValue Value0 = StoredVal.getOperand(0);
13993 SDValue Value1 = StoredVal.getOperand(1);
13995 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13996 SDValue Ptr0 = St->getBasePtr();
13997 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13999 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14000 St->getPointerInfo(), St->isVolatile(),
14001 St->isNonTemporal(), St->getAlignment());
14002 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14003 St->getPointerInfo(), St->isVolatile(),
14004 St->isNonTemporal(), St->getAlignment());
14005 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14008 // Optimize trunc store (of multiple scalars) to shuffle and store.
14009 // First, pack all of the elements in one place. Next, store to memory
14010 // in fewer chunks.
14011 if (St->isTruncatingStore() && VT.isVector()) {
14012 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14013 unsigned NumElems = VT.getVectorNumElements();
14014 assert(StVT != VT && "Cannot truncate to the same type");
14015 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14016 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14018 // From, To sizes and ElemCount must be pow of two
14019 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14020 // We are going to use the original vector elt for storing.
14021 // Accumulated smaller vector elements must be a multiple of the store size.
14022 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14024 unsigned SizeRatio = FromSz / ToSz;
14026 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14028 // Create a type on which we perform the shuffle
14029 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14030 StVT.getScalarType(), NumElems*SizeRatio);
14032 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14034 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14035 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14036 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14038 // Can't shuffle using an illegal type
14039 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14041 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14042 DAG.getUNDEF(WideVec.getValueType()),
14043 ShuffleVec.data());
14044 // At this point all of the data is stored at the bottom of the
14045 // register. We now need to save it to mem.
14047 // Find the largest store unit
14048 MVT StoreType = MVT::i8;
14049 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14050 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14051 MVT Tp = (MVT::SimpleValueType)tp;
14052 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14056 // Bitcast the original vector into a vector of store-size units
14057 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14058 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14059 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14060 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14061 SmallVector<SDValue, 8> Chains;
14062 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14063 TLI.getPointerTy());
14064 SDValue Ptr = St->getBasePtr();
14066 // Perform one or more big stores into memory.
14067 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14068 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14069 StoreType, ShuffWide,
14070 DAG.getIntPtrConstant(i));
14071 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14072 St->getPointerInfo(), St->isVolatile(),
14073 St->isNonTemporal(), St->getAlignment());
14074 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14075 Chains.push_back(Ch);
14078 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14083 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14084 // the FP state in cases where an emms may be missing.
14085 // A preferable solution to the general problem is to figure out the right
14086 // places to insert EMMS. This qualifies as a quick hack.
14088 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14089 if (VT.getSizeInBits() != 64)
14092 const Function *F = DAG.getMachineFunction().getFunction();
14093 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14094 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14095 && Subtarget->hasXMMInt();
14096 if ((VT.isVector() ||
14097 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14098 isa<LoadSDNode>(St->getValue()) &&
14099 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14100 St->getChain().hasOneUse() && !St->isVolatile()) {
14101 SDNode* LdVal = St->getValue().getNode();
14102 LoadSDNode *Ld = 0;
14103 int TokenFactorIndex = -1;
14104 SmallVector<SDValue, 8> Ops;
14105 SDNode* ChainVal = St->getChain().getNode();
14106 // Must be a store of a load. We currently handle two cases: the load
14107 // is a direct child, and it's under an intervening TokenFactor. It is
14108 // possible to dig deeper under nested TokenFactors.
14109 if (ChainVal == LdVal)
14110 Ld = cast<LoadSDNode>(St->getChain());
14111 else if (St->getValue().hasOneUse() &&
14112 ChainVal->getOpcode() == ISD::TokenFactor) {
14113 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14114 if (ChainVal->getOperand(i).getNode() == LdVal) {
14115 TokenFactorIndex = i;
14116 Ld = cast<LoadSDNode>(St->getValue());
14118 Ops.push_back(ChainVal->getOperand(i));
14122 if (!Ld || !ISD::isNormalLoad(Ld))
14125 // If this is not the MMX case, i.e. we are just turning i64 load/store
14126 // into f64 load/store, avoid the transformation if there are multiple
14127 // uses of the loaded value.
14128 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14131 DebugLoc LdDL = Ld->getDebugLoc();
14132 DebugLoc StDL = N->getDebugLoc();
14133 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14134 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14136 if (Subtarget->is64Bit() || F64IsLegal) {
14137 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14138 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14139 Ld->getPointerInfo(), Ld->isVolatile(),
14140 Ld->isNonTemporal(), Ld->isInvariant(),
14141 Ld->getAlignment());
14142 SDValue NewChain = NewLd.getValue(1);
14143 if (TokenFactorIndex != -1) {
14144 Ops.push_back(NewChain);
14145 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14148 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14149 St->getPointerInfo(),
14150 St->isVolatile(), St->isNonTemporal(),
14151 St->getAlignment());
14154 // Otherwise, lower to two pairs of 32-bit loads / stores.
14155 SDValue LoAddr = Ld->getBasePtr();
14156 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14157 DAG.getConstant(4, MVT::i32));
14159 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14160 Ld->getPointerInfo(),
14161 Ld->isVolatile(), Ld->isNonTemporal(),
14162 Ld->isInvariant(), Ld->getAlignment());
14163 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14164 Ld->getPointerInfo().getWithOffset(4),
14165 Ld->isVolatile(), Ld->isNonTemporal(),
14167 MinAlign(Ld->getAlignment(), 4));
14169 SDValue NewChain = LoLd.getValue(1);
14170 if (TokenFactorIndex != -1) {
14171 Ops.push_back(LoLd);
14172 Ops.push_back(HiLd);
14173 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14177 LoAddr = St->getBasePtr();
14178 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14179 DAG.getConstant(4, MVT::i32));
14181 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14182 St->getPointerInfo(),
14183 St->isVolatile(), St->isNonTemporal(),
14184 St->getAlignment());
14185 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14186 St->getPointerInfo().getWithOffset(4),
14188 St->isNonTemporal(),
14189 MinAlign(St->getAlignment(), 4));
14190 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14195 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14196 /// and return the operands for the horizontal operation in LHS and RHS. A
14197 /// horizontal operation performs the binary operation on successive elements
14198 /// of its first operand, then on successive elements of its second operand,
14199 /// returning the resulting values in a vector. For example, if
14200 /// A = < float a0, float a1, float a2, float a3 >
14202 /// B = < float b0, float b1, float b2, float b3 >
14203 /// then the result of doing a horizontal operation on A and B is
14204 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14205 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14206 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14207 /// set to A, RHS to B, and the routine returns 'true'.
14208 /// Note that the binary operation should have the property that if one of the
14209 /// operands is UNDEF then the result is UNDEF.
14210 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14211 // Look for the following pattern: if
14212 // A = < float a0, float a1, float a2, float a3 >
14213 // B = < float b0, float b1, float b2, float b3 >
14215 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14216 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14217 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14218 // which is A horizontal-op B.
14220 // At least one of the operands should be a vector shuffle.
14221 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14222 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14225 EVT VT = LHS.getValueType();
14227 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14228 "Unsupported vector type for horizontal add/sub");
14230 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14231 // operate independently on 128-bit lanes.
14232 unsigned NumElts = VT.getVectorNumElements();
14233 unsigned NumLanes = VT.getSizeInBits()/128;
14234 unsigned NumLaneElts = NumElts / NumLanes;
14235 assert((NumLaneElts % 2 == 0) &&
14236 "Vector type should have an even number of elements in each lane");
14237 unsigned HalfLaneElts = NumLaneElts/2;
14239 // View LHS in the form
14240 // LHS = VECTOR_SHUFFLE A, B, LMask
14241 // If LHS is not a shuffle then pretend it is the shuffle
14242 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14243 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14246 SmallVector<int, 16> LMask(NumElts);
14247 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14248 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14249 A = LHS.getOperand(0);
14250 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14251 B = LHS.getOperand(1);
14252 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14254 if (LHS.getOpcode() != ISD::UNDEF)
14256 for (unsigned i = 0; i != NumElts; ++i)
14260 // Likewise, view RHS in the form
14261 // RHS = VECTOR_SHUFFLE C, D, RMask
14263 SmallVector<int, 16> RMask(NumElts);
14264 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14265 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14266 C = RHS.getOperand(0);
14267 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14268 D = RHS.getOperand(1);
14269 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14271 if (RHS.getOpcode() != ISD::UNDEF)
14273 for (unsigned i = 0; i != NumElts; ++i)
14277 // Check that the shuffles are both shuffling the same vectors.
14278 if (!(A == C && B == D) && !(A == D && B == C))
14281 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14282 if (!A.getNode() && !B.getNode())
14285 // If A and B occur in reverse order in RHS, then "swap" them (which means
14286 // rewriting the mask).
14288 CommuteVectorShuffleMask(RMask, NumElts);
14290 // At this point LHS and RHS are equivalent to
14291 // LHS = VECTOR_SHUFFLE A, B, LMask
14292 // RHS = VECTOR_SHUFFLE A, B, RMask
14293 // Check that the masks correspond to performing a horizontal operation.
14294 for (unsigned i = 0; i != NumElts; ++i) {
14295 int LIdx = LMask[i], RIdx = RMask[i];
14297 // Ignore any UNDEF components.
14298 if (LIdx < 0 || RIdx < 0 ||
14299 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14300 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14303 // Check that successive elements are being operated on. If not, this is
14304 // not a horizontal operation.
14305 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14306 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14307 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14308 if (!(LIdx == Index && RIdx == Index + 1) &&
14309 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14313 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14314 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14318 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14319 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14320 const X86Subtarget *Subtarget) {
14321 EVT VT = N->getValueType(0);
14322 SDValue LHS = N->getOperand(0);
14323 SDValue RHS = N->getOperand(1);
14325 // Try to synthesize horizontal adds from adds of shuffles.
14326 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14327 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14328 isHorizontalBinOp(LHS, RHS, true))
14329 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14333 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14334 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14335 const X86Subtarget *Subtarget) {
14336 EVT VT = N->getValueType(0);
14337 SDValue LHS = N->getOperand(0);
14338 SDValue RHS = N->getOperand(1);
14340 // Try to synthesize horizontal subs from subs of shuffles.
14341 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14342 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14343 isHorizontalBinOp(LHS, RHS, false))
14344 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14348 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14349 /// X86ISD::FXOR nodes.
14350 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14351 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14352 // F[X]OR(0.0, x) -> x
14353 // F[X]OR(x, 0.0) -> x
14354 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14355 if (C->getValueAPF().isPosZero())
14356 return N->getOperand(1);
14357 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14358 if (C->getValueAPF().isPosZero())
14359 return N->getOperand(0);
14363 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14364 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14365 // FAND(0.0, x) -> 0.0
14366 // FAND(x, 0.0) -> 0.0
14367 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14368 if (C->getValueAPF().isPosZero())
14369 return N->getOperand(0);
14370 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14371 if (C->getValueAPF().isPosZero())
14372 return N->getOperand(1);
14376 static SDValue PerformBTCombine(SDNode *N,
14378 TargetLowering::DAGCombinerInfo &DCI) {
14379 // BT ignores high bits in the bit index operand.
14380 SDValue Op1 = N->getOperand(1);
14381 if (Op1.hasOneUse()) {
14382 unsigned BitWidth = Op1.getValueSizeInBits();
14383 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14384 APInt KnownZero, KnownOne;
14385 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14386 !DCI.isBeforeLegalizeOps());
14387 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14388 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14389 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14390 DCI.CommitTargetLoweringOpt(TLO);
14395 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14396 SDValue Op = N->getOperand(0);
14397 if (Op.getOpcode() == ISD::BITCAST)
14398 Op = Op.getOperand(0);
14399 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14400 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14401 VT.getVectorElementType().getSizeInBits() ==
14402 OpVT.getVectorElementType().getSizeInBits()) {
14403 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14408 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14409 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14410 // (and (i32 x86isd::setcc_carry), 1)
14411 // This eliminates the zext. This transformation is necessary because
14412 // ISD::SETCC is always legalized to i8.
14413 DebugLoc dl = N->getDebugLoc();
14414 SDValue N0 = N->getOperand(0);
14415 EVT VT = N->getValueType(0);
14416 if (N0.getOpcode() == ISD::AND &&
14418 N0.getOperand(0).hasOneUse()) {
14419 SDValue N00 = N0.getOperand(0);
14420 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14422 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14423 if (!C || C->getZExtValue() != 1)
14425 return DAG.getNode(ISD::AND, dl, VT,
14426 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14427 N00.getOperand(0), N00.getOperand(1)),
14428 DAG.getConstant(1, VT));
14434 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14435 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14436 unsigned X86CC = N->getConstantOperandVal(0);
14437 SDValue EFLAG = N->getOperand(1);
14438 DebugLoc DL = N->getDebugLoc();
14440 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14441 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14443 if (X86CC == X86::COND_B)
14444 return DAG.getNode(ISD::AND, DL, MVT::i8,
14445 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14446 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14447 DAG.getConstant(1, MVT::i8));
14452 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14453 const X86TargetLowering *XTLI) {
14454 SDValue Op0 = N->getOperand(0);
14455 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14456 // a 32-bit target where SSE doesn't support i64->FP operations.
14457 if (Op0.getOpcode() == ISD::LOAD) {
14458 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14459 EVT VT = Ld->getValueType(0);
14460 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14461 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14462 !XTLI->getSubtarget()->is64Bit() &&
14463 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14464 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14465 Ld->getChain(), Op0, DAG);
14466 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14473 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14474 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14475 X86TargetLowering::DAGCombinerInfo &DCI) {
14476 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14477 // the result is either zero or one (depending on the input carry bit).
14478 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14479 if (X86::isZeroNode(N->getOperand(0)) &&
14480 X86::isZeroNode(N->getOperand(1)) &&
14481 // We don't have a good way to replace an EFLAGS use, so only do this when
14483 SDValue(N, 1).use_empty()) {
14484 DebugLoc DL = N->getDebugLoc();
14485 EVT VT = N->getValueType(0);
14486 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14487 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14488 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14489 DAG.getConstant(X86::COND_B,MVT::i8),
14491 DAG.getConstant(1, VT));
14492 return DCI.CombineTo(N, Res1, CarryOut);
14498 // fold (add Y, (sete X, 0)) -> adc 0, Y
14499 // (add Y, (setne X, 0)) -> sbb -1, Y
14500 // (sub (sete X, 0), Y) -> sbb 0, Y
14501 // (sub (setne X, 0), Y) -> adc -1, Y
14502 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14503 DebugLoc DL = N->getDebugLoc();
14505 // Look through ZExts.
14506 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14507 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14510 SDValue SetCC = Ext.getOperand(0);
14511 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14514 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14515 if (CC != X86::COND_E && CC != X86::COND_NE)
14518 SDValue Cmp = SetCC.getOperand(1);
14519 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14520 !X86::isZeroNode(Cmp.getOperand(1)) ||
14521 !Cmp.getOperand(0).getValueType().isInteger())
14524 SDValue CmpOp0 = Cmp.getOperand(0);
14525 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14526 DAG.getConstant(1, CmpOp0.getValueType()));
14528 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14529 if (CC == X86::COND_NE)
14530 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14531 DL, OtherVal.getValueType(), OtherVal,
14532 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14533 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14534 DL, OtherVal.getValueType(), OtherVal,
14535 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14538 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14539 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14540 const X86Subtarget *Subtarget) {
14541 EVT VT = N->getValueType(0);
14542 SDValue Op0 = N->getOperand(0);
14543 SDValue Op1 = N->getOperand(1);
14545 // Try to synthesize horizontal adds from adds of shuffles.
14546 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14547 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) &&
14548 isHorizontalBinOp(Op0, Op1, true))
14549 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14551 return OptimizeConditionalInDecrement(N, DAG);
14554 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14555 const X86Subtarget *Subtarget) {
14556 SDValue Op0 = N->getOperand(0);
14557 SDValue Op1 = N->getOperand(1);
14559 // X86 can't encode an immediate LHS of a sub. See if we can push the
14560 // negation into a preceding instruction.
14561 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14562 // If the RHS of the sub is a XOR with one use and a constant, invert the
14563 // immediate. Then add one to the LHS of the sub so we can turn
14564 // X-Y -> X+~Y+1, saving one register.
14565 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14566 isa<ConstantSDNode>(Op1.getOperand(1))) {
14567 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14568 EVT VT = Op0.getValueType();
14569 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14571 DAG.getConstant(~XorC, VT));
14572 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14573 DAG.getConstant(C->getAPIntValue()+1, VT));
14577 // Try to synthesize horizontal adds from adds of shuffles.
14578 EVT VT = N->getValueType(0);
14579 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14580 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14581 isHorizontalBinOp(Op0, Op1, true))
14582 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14584 return OptimizeConditionalInDecrement(N, DAG);
14587 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14588 DAGCombinerInfo &DCI) const {
14589 SelectionDAG &DAG = DCI.DAG;
14590 switch (N->getOpcode()) {
14592 case ISD::EXTRACT_VECTOR_ELT:
14593 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14595 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14596 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14597 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14598 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14599 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14600 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14603 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14604 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14605 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14606 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14607 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14608 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14609 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14610 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14611 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14613 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14614 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14615 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14616 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14617 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14618 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14619 case X86ISD::SHUFPS: // Handle all target specific shuffles
14620 case X86ISD::SHUFPD:
14621 case X86ISD::PALIGN:
14622 case X86ISD::UNPCKH:
14623 case X86ISD::UNPCKL:
14624 case X86ISD::MOVHLPS:
14625 case X86ISD::MOVLHPS:
14626 case X86ISD::PSHUFD:
14627 case X86ISD::PSHUFHW:
14628 case X86ISD::PSHUFLW:
14629 case X86ISD::MOVSS:
14630 case X86ISD::MOVSD:
14631 case X86ISD::VPERMILP:
14632 case X86ISD::VPERM2X128:
14633 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14639 /// isTypeDesirableForOp - Return true if the target has native support for
14640 /// the specified value type and it is 'desirable' to use the type for the
14641 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14642 /// instruction encodings are longer and some i16 instructions are slow.
14643 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14644 if (!isTypeLegal(VT))
14646 if (VT != MVT::i16)
14653 case ISD::SIGN_EXTEND:
14654 case ISD::ZERO_EXTEND:
14655 case ISD::ANY_EXTEND:
14668 /// IsDesirableToPromoteOp - This method query the target whether it is
14669 /// beneficial for dag combiner to promote the specified node. If true, it
14670 /// should return the desired promotion type by reference.
14671 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14672 EVT VT = Op.getValueType();
14673 if (VT != MVT::i16)
14676 bool Promote = false;
14677 bool Commute = false;
14678 switch (Op.getOpcode()) {
14681 LoadSDNode *LD = cast<LoadSDNode>(Op);
14682 // If the non-extending load has a single use and it's not live out, then it
14683 // might be folded.
14684 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14685 Op.hasOneUse()*/) {
14686 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14687 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14688 // The only case where we'd want to promote LOAD (rather then it being
14689 // promoted as an operand is when it's only use is liveout.
14690 if (UI->getOpcode() != ISD::CopyToReg)
14697 case ISD::SIGN_EXTEND:
14698 case ISD::ZERO_EXTEND:
14699 case ISD::ANY_EXTEND:
14704 SDValue N0 = Op.getOperand(0);
14705 // Look out for (store (shl (load), x)).
14706 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14719 SDValue N0 = Op.getOperand(0);
14720 SDValue N1 = Op.getOperand(1);
14721 if (!Commute && MayFoldLoad(N1))
14723 // Avoid disabling potential load folding opportunities.
14724 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14726 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14736 //===----------------------------------------------------------------------===//
14737 // X86 Inline Assembly Support
14738 //===----------------------------------------------------------------------===//
14741 // Helper to match a string separated by whitespace.
14742 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
14743 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
14745 for (unsigned i = 0, e = args.size(); i != e; ++i) {
14746 StringRef piece(*args[i]);
14747 if (!s.startswith(piece)) // Check if the piece matches.
14750 s = s.substr(piece.size());
14751 StringRef::size_type pos = s.find_first_not_of(" \t");
14752 if (pos == 0) // We matched a prefix.
14760 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
14763 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14764 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14766 std::string AsmStr = IA->getAsmString();
14768 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14769 if (!Ty || Ty->getBitWidth() % 16 != 0)
14772 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14773 SmallVector<StringRef, 4> AsmPieces;
14774 SplitString(AsmStr, AsmPieces, ";\n");
14776 switch (AsmPieces.size()) {
14777 default: return false;
14779 // FIXME: this should verify that we are targeting a 486 or better. If not,
14780 // we will turn this bswap into something that will be lowered to logical
14781 // ops instead of emitting the bswap asm. For now, we don't support 486 or
14782 // lower so don't worry about this.
14784 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
14785 matchAsm(AsmPieces[0], "bswapl", "$0") ||
14786 matchAsm(AsmPieces[0], "bswapq", "$0") ||
14787 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
14788 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
14789 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
14790 // No need to check constraints, nothing other than the equivalent of
14791 // "=r,0" would be valid here.
14792 return IntrinsicLowering::LowerToByteSwap(CI);
14795 // rorw $$8, ${0:w} --> llvm.bswap.i16
14796 if (CI->getType()->isIntegerTy(16) &&
14797 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14798 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
14799 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
14801 const std::string &ConstraintsStr = IA->getConstraintString();
14802 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14803 std::sort(AsmPieces.begin(), AsmPieces.end());
14804 if (AsmPieces.size() == 4 &&
14805 AsmPieces[0] == "~{cc}" &&
14806 AsmPieces[1] == "~{dirflag}" &&
14807 AsmPieces[2] == "~{flags}" &&
14808 AsmPieces[3] == "~{fpsr}")
14809 return IntrinsicLowering::LowerToByteSwap(CI);
14813 if (CI->getType()->isIntegerTy(32) &&
14814 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14815 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
14816 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
14817 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
14819 const std::string &ConstraintsStr = IA->getConstraintString();
14820 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14821 std::sort(AsmPieces.begin(), AsmPieces.end());
14822 if (AsmPieces.size() == 4 &&
14823 AsmPieces[0] == "~{cc}" &&
14824 AsmPieces[1] == "~{dirflag}" &&
14825 AsmPieces[2] == "~{flags}" &&
14826 AsmPieces[3] == "~{fpsr}")
14827 return IntrinsicLowering::LowerToByteSwap(CI);
14830 if (CI->getType()->isIntegerTy(64)) {
14831 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14832 if (Constraints.size() >= 2 &&
14833 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14834 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14835 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14836 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
14837 matchAsm(AsmPieces[1], "bswap", "%edx") &&
14838 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
14839 return IntrinsicLowering::LowerToByteSwap(CI);
14849 /// getConstraintType - Given a constraint letter, return the type of
14850 /// constraint it is for this target.
14851 X86TargetLowering::ConstraintType
14852 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14853 if (Constraint.size() == 1) {
14854 switch (Constraint[0]) {
14865 return C_RegisterClass;
14889 return TargetLowering::getConstraintType(Constraint);
14892 /// Examine constraint type and operand type and determine a weight value.
14893 /// This object must already have been set up with the operand type
14894 /// and the current alternative constraint selected.
14895 TargetLowering::ConstraintWeight
14896 X86TargetLowering::getSingleConstraintMatchWeight(
14897 AsmOperandInfo &info, const char *constraint) const {
14898 ConstraintWeight weight = CW_Invalid;
14899 Value *CallOperandVal = info.CallOperandVal;
14900 // If we don't have a value, we can't do a match,
14901 // but allow it at the lowest weight.
14902 if (CallOperandVal == NULL)
14904 Type *type = CallOperandVal->getType();
14905 // Look at the constraint type.
14906 switch (*constraint) {
14908 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14919 if (CallOperandVal->getType()->isIntegerTy())
14920 weight = CW_SpecificReg;
14925 if (type->isFloatingPointTy())
14926 weight = CW_SpecificReg;
14929 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14930 weight = CW_SpecificReg;
14934 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14935 weight = CW_Register;
14938 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14939 if (C->getZExtValue() <= 31)
14940 weight = CW_Constant;
14944 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14945 if (C->getZExtValue() <= 63)
14946 weight = CW_Constant;
14950 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14951 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14952 weight = CW_Constant;
14956 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14957 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14958 weight = CW_Constant;
14962 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14963 if (C->getZExtValue() <= 3)
14964 weight = CW_Constant;
14968 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14969 if (C->getZExtValue() <= 0xff)
14970 weight = CW_Constant;
14975 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14976 weight = CW_Constant;
14980 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14981 if ((C->getSExtValue() >= -0x80000000LL) &&
14982 (C->getSExtValue() <= 0x7fffffffLL))
14983 weight = CW_Constant;
14987 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14988 if (C->getZExtValue() <= 0xffffffff)
14989 weight = CW_Constant;
14996 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14997 /// with another that has more specific requirements based on the type of the
14998 /// corresponding operand.
14999 const char *X86TargetLowering::
15000 LowerXConstraint(EVT ConstraintVT) const {
15001 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15002 // 'f' like normal targets.
15003 if (ConstraintVT.isFloatingPoint()) {
15004 if (Subtarget->hasXMMInt())
15006 if (Subtarget->hasXMM())
15010 return TargetLowering::LowerXConstraint(ConstraintVT);
15013 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15014 /// vector. If it is invalid, don't add anything to Ops.
15015 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15016 std::string &Constraint,
15017 std::vector<SDValue>&Ops,
15018 SelectionDAG &DAG) const {
15019 SDValue Result(0, 0);
15021 // Only support length 1 constraints for now.
15022 if (Constraint.length() > 1) return;
15024 char ConstraintLetter = Constraint[0];
15025 switch (ConstraintLetter) {
15028 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15029 if (C->getZExtValue() <= 31) {
15030 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15037 if (C->getZExtValue() <= 63) {
15038 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15045 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15046 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15052 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15053 if (C->getZExtValue() <= 255) {
15054 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15060 // 32-bit signed value
15061 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15062 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15063 C->getSExtValue())) {
15064 // Widen to 64 bits here to get it sign extended.
15065 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15068 // FIXME gcc accepts some relocatable values here too, but only in certain
15069 // memory models; it's complicated.
15074 // 32-bit unsigned value
15075 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15076 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15077 C->getZExtValue())) {
15078 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15082 // FIXME gcc accepts some relocatable values here too, but only in certain
15083 // memory models; it's complicated.
15087 // Literal immediates are always ok.
15088 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15089 // Widen to 64 bits here to get it sign extended.
15090 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15094 // In any sort of PIC mode addresses need to be computed at runtime by
15095 // adding in a register or some sort of table lookup. These can't
15096 // be used as immediates.
15097 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15100 // If we are in non-pic codegen mode, we allow the address of a global (with
15101 // an optional displacement) to be used with 'i'.
15102 GlobalAddressSDNode *GA = 0;
15103 int64_t Offset = 0;
15105 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15107 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15108 Offset += GA->getOffset();
15110 } else if (Op.getOpcode() == ISD::ADD) {
15111 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15112 Offset += C->getZExtValue();
15113 Op = Op.getOperand(0);
15116 } else if (Op.getOpcode() == ISD::SUB) {
15117 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15118 Offset += -C->getZExtValue();
15119 Op = Op.getOperand(0);
15124 // Otherwise, this isn't something we can handle, reject it.
15128 const GlobalValue *GV = GA->getGlobal();
15129 // If we require an extra load to get this address, as in PIC mode, we
15130 // can't accept it.
15131 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15132 getTargetMachine())))
15135 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15136 GA->getValueType(0), Offset);
15141 if (Result.getNode()) {
15142 Ops.push_back(Result);
15145 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15148 std::pair<unsigned, const TargetRegisterClass*>
15149 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15151 // First, see if this is a constraint that directly corresponds to an LLVM
15153 if (Constraint.size() == 1) {
15154 // GCC Constraint Letters
15155 switch (Constraint[0]) {
15157 // TODO: Slight differences here in allocation order and leaving
15158 // RIP in the class. Do they matter any more here than they do
15159 // in the normal allocation?
15160 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15161 if (Subtarget->is64Bit()) {
15162 if (VT == MVT::i32 || VT == MVT::f32)
15163 return std::make_pair(0U, X86::GR32RegisterClass);
15164 else if (VT == MVT::i16)
15165 return std::make_pair(0U, X86::GR16RegisterClass);
15166 else if (VT == MVT::i8 || VT == MVT::i1)
15167 return std::make_pair(0U, X86::GR8RegisterClass);
15168 else if (VT == MVT::i64 || VT == MVT::f64)
15169 return std::make_pair(0U, X86::GR64RegisterClass);
15172 // 32-bit fallthrough
15173 case 'Q': // Q_REGS
15174 if (VT == MVT::i32 || VT == MVT::f32)
15175 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15176 else if (VT == MVT::i16)
15177 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15178 else if (VT == MVT::i8 || VT == MVT::i1)
15179 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15180 else if (VT == MVT::i64)
15181 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15183 case 'r': // GENERAL_REGS
15184 case 'l': // INDEX_REGS
15185 if (VT == MVT::i8 || VT == MVT::i1)
15186 return std::make_pair(0U, X86::GR8RegisterClass);
15187 if (VT == MVT::i16)
15188 return std::make_pair(0U, X86::GR16RegisterClass);
15189 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15190 return std::make_pair(0U, X86::GR32RegisterClass);
15191 return std::make_pair(0U, X86::GR64RegisterClass);
15192 case 'R': // LEGACY_REGS
15193 if (VT == MVT::i8 || VT == MVT::i1)
15194 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15195 if (VT == MVT::i16)
15196 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15197 if (VT == MVT::i32 || !Subtarget->is64Bit())
15198 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15199 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15200 case 'f': // FP Stack registers.
15201 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15202 // value to the correct fpstack register class.
15203 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15204 return std::make_pair(0U, X86::RFP32RegisterClass);
15205 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15206 return std::make_pair(0U, X86::RFP64RegisterClass);
15207 return std::make_pair(0U, X86::RFP80RegisterClass);
15208 case 'y': // MMX_REGS if MMX allowed.
15209 if (!Subtarget->hasMMX()) break;
15210 return std::make_pair(0U, X86::VR64RegisterClass);
15211 case 'Y': // SSE_REGS if SSE2 allowed
15212 if (!Subtarget->hasXMMInt()) break;
15214 case 'x': // SSE_REGS if SSE1 allowed
15215 if (!Subtarget->hasXMM()) break;
15217 switch (VT.getSimpleVT().SimpleTy) {
15219 // Scalar SSE types.
15222 return std::make_pair(0U, X86::FR32RegisterClass);
15225 return std::make_pair(0U, X86::FR64RegisterClass);
15233 return std::make_pair(0U, X86::VR128RegisterClass);
15239 // Use the default implementation in TargetLowering to convert the register
15240 // constraint into a member of a register class.
15241 std::pair<unsigned, const TargetRegisterClass*> Res;
15242 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15244 // Not found as a standard register?
15245 if (Res.second == 0) {
15246 // Map st(0) -> st(7) -> ST0
15247 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15248 tolower(Constraint[1]) == 's' &&
15249 tolower(Constraint[2]) == 't' &&
15250 Constraint[3] == '(' &&
15251 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15252 Constraint[5] == ')' &&
15253 Constraint[6] == '}') {
15255 Res.first = X86::ST0+Constraint[4]-'0';
15256 Res.second = X86::RFP80RegisterClass;
15260 // GCC allows "st(0)" to be called just plain "st".
15261 if (StringRef("{st}").equals_lower(Constraint)) {
15262 Res.first = X86::ST0;
15263 Res.second = X86::RFP80RegisterClass;
15268 if (StringRef("{flags}").equals_lower(Constraint)) {
15269 Res.first = X86::EFLAGS;
15270 Res.second = X86::CCRRegisterClass;
15274 // 'A' means EAX + EDX.
15275 if (Constraint == "A") {
15276 Res.first = X86::EAX;
15277 Res.second = X86::GR32_ADRegisterClass;
15283 // Otherwise, check to see if this is a register class of the wrong value
15284 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15285 // turn into {ax},{dx}.
15286 if (Res.second->hasType(VT))
15287 return Res; // Correct type already, nothing to do.
15289 // All of the single-register GCC register classes map their values onto
15290 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15291 // really want an 8-bit or 32-bit register, map to the appropriate register
15292 // class and return the appropriate register.
15293 if (Res.second == X86::GR16RegisterClass) {
15294 if (VT == MVT::i8) {
15295 unsigned DestReg = 0;
15296 switch (Res.first) {
15298 case X86::AX: DestReg = X86::AL; break;
15299 case X86::DX: DestReg = X86::DL; break;
15300 case X86::CX: DestReg = X86::CL; break;
15301 case X86::BX: DestReg = X86::BL; break;
15304 Res.first = DestReg;
15305 Res.second = X86::GR8RegisterClass;
15307 } else if (VT == MVT::i32) {
15308 unsigned DestReg = 0;
15309 switch (Res.first) {
15311 case X86::AX: DestReg = X86::EAX; break;
15312 case X86::DX: DestReg = X86::EDX; break;
15313 case X86::CX: DestReg = X86::ECX; break;
15314 case X86::BX: DestReg = X86::EBX; break;
15315 case X86::SI: DestReg = X86::ESI; break;
15316 case X86::DI: DestReg = X86::EDI; break;
15317 case X86::BP: DestReg = X86::EBP; break;
15318 case X86::SP: DestReg = X86::ESP; break;
15321 Res.first = DestReg;
15322 Res.second = X86::GR32RegisterClass;
15324 } else if (VT == MVT::i64) {
15325 unsigned DestReg = 0;
15326 switch (Res.first) {
15328 case X86::AX: DestReg = X86::RAX; break;
15329 case X86::DX: DestReg = X86::RDX; break;
15330 case X86::CX: DestReg = X86::RCX; break;
15331 case X86::BX: DestReg = X86::RBX; break;
15332 case X86::SI: DestReg = X86::RSI; break;
15333 case X86::DI: DestReg = X86::RDI; break;
15334 case X86::BP: DestReg = X86::RBP; break;
15335 case X86::SP: DestReg = X86::RSP; break;
15338 Res.first = DestReg;
15339 Res.second = X86::GR64RegisterClass;
15342 } else if (Res.second == X86::FR32RegisterClass ||
15343 Res.second == X86::FR64RegisterClass ||
15344 Res.second == X86::VR128RegisterClass) {
15345 // Handle references to XMM physical registers that got mapped into the
15346 // wrong class. This can happen with constraints like {xmm0} where the
15347 // target independent register mapper will just pick the first match it can
15348 // find, ignoring the required type.
15349 if (VT == MVT::f32)
15350 Res.second = X86::FR32RegisterClass;
15351 else if (VT == MVT::f64)
15352 Res.second = X86::FR64RegisterClass;
15353 else if (X86::VR128RegisterClass->hasType(VT))
15354 Res.second = X86::VR128RegisterClass;