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/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.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 (!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);
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 (!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 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
383 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
384 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
385 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
386 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
387 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
388 if (Subtarget->is64Bit()) {
389 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
390 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
393 if (Subtarget->hasPOPCNT()) {
394 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
396 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
397 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
398 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
399 if (Subtarget->is64Bit())
400 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
403 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
404 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
406 // These should be promoted to a larger select which is supported.
407 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
408 // X86 wants to expand cmov itself.
409 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
410 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
411 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
412 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
413 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
414 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
416 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
417 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
418 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
419 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
420 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
421 if (Subtarget->is64Bit()) {
422 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
423 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
425 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
428 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
429 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
430 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
431 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
435 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
436 if (Subtarget->is64Bit()) {
437 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
438 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
439 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
440 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
443 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
445 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
446 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
447 if (Subtarget->is64Bit()) {
448 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
449 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
450 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
453 if (Subtarget->hasXMM())
454 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
456 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
457 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
459 // On X86 and X86-64, atomic operations are lowered to locked instructions.
460 // Locked instructions, in turn, have implicit fence semantics (all memory
461 // operations are flushed before issuing the locked instruction, and they
462 // are not buffered), so we can fold away the common pattern of
463 // fence-atomic-fence.
464 setShouldFoldAtomicFences(true);
466 // Expand certain atomics
467 for (unsigned i = 0, e = 4; i != e; ++i) {
469 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
470 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
471 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
474 if (!Subtarget->is64Bit()) {
475 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
476 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
477 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
478 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
479 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
480 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
481 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
482 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
485 if (Subtarget->hasCmpxchg16b()) {
486 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
489 // FIXME - use subtarget debug flags
490 if (!Subtarget->isTargetDarwin() &&
491 !Subtarget->isTargetELF() &&
492 !Subtarget->isTargetCygMing()) {
493 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
496 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
497 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
498 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
499 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
500 if (Subtarget->is64Bit()) {
501 setExceptionPointerRegister(X86::RAX);
502 setExceptionSelectorRegister(X86::RDX);
504 setExceptionPointerRegister(X86::EAX);
505 setExceptionSelectorRegister(X86::EDX);
507 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
508 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
510 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
511 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
513 setOperationAction(ISD::TRAP, MVT::Other, Legal);
515 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
516 setOperationAction(ISD::VASTART , MVT::Other, Custom);
517 setOperationAction(ISD::VAEND , MVT::Other, Expand);
518 if (Subtarget->is64Bit()) {
519 setOperationAction(ISD::VAARG , MVT::Other, Custom);
520 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
522 setOperationAction(ISD::VAARG , MVT::Other, Expand);
523 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
526 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
527 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
529 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
530 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
531 MVT::i64 : MVT::i32, Custom);
532 else if (EnableSegmentedStacks)
533 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
534 MVT::i64 : MVT::i32, Custom);
536 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
537 MVT::i64 : MVT::i32, Expand);
539 if (!UseSoftFloat && X86ScalarSSEf64) {
540 // f32 and f64 use SSE.
541 // Set up the FP register classes.
542 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
543 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
545 // Use ANDPD to simulate FABS.
546 setOperationAction(ISD::FABS , MVT::f64, Custom);
547 setOperationAction(ISD::FABS , MVT::f32, Custom);
549 // Use XORP to simulate FNEG.
550 setOperationAction(ISD::FNEG , MVT::f64, Custom);
551 setOperationAction(ISD::FNEG , MVT::f32, Custom);
553 // Use ANDPD and ORPD to simulate FCOPYSIGN.
554 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
555 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
557 // Lower this to FGETSIGNx86 plus an AND.
558 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
559 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
561 // We don't support sin/cos/fmod
562 setOperationAction(ISD::FSIN , MVT::f64, Expand);
563 setOperationAction(ISD::FCOS , MVT::f64, Expand);
564 setOperationAction(ISD::FSIN , MVT::f32, Expand);
565 setOperationAction(ISD::FCOS , MVT::f32, Expand);
567 // Expand FP immediates into loads from the stack, except for the special
569 addLegalFPImmediate(APFloat(+0.0)); // xorpd
570 addLegalFPImmediate(APFloat(+0.0f)); // xorps
571 } else if (!UseSoftFloat && X86ScalarSSEf32) {
572 // Use SSE for f32, x87 for f64.
573 // Set up the FP register classes.
574 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
575 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
577 // Use ANDPS to simulate FABS.
578 setOperationAction(ISD::FABS , MVT::f32, Custom);
580 // Use XORP to simulate FNEG.
581 setOperationAction(ISD::FNEG , MVT::f32, Custom);
583 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
585 // Use ANDPS and ORPS to simulate FCOPYSIGN.
586 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
587 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
589 // We don't support sin/cos/fmod
590 setOperationAction(ISD::FSIN , MVT::f32, Expand);
591 setOperationAction(ISD::FCOS , MVT::f32, Expand);
593 // Special cases we handle for FP constants.
594 addLegalFPImmediate(APFloat(+0.0f)); // xorps
595 addLegalFPImmediate(APFloat(+0.0)); // FLD0
596 addLegalFPImmediate(APFloat(+1.0)); // FLD1
597 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
598 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
601 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
602 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
604 } else if (!UseSoftFloat) {
605 // f32 and f64 in x87.
606 // Set up the FP register classes.
607 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
608 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
610 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
611 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
612 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
613 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
616 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
617 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
619 addLegalFPImmediate(APFloat(+0.0)); // FLD0
620 addLegalFPImmediate(APFloat(+1.0)); // FLD1
621 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
622 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
623 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
624 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
625 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
626 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
629 // We don't support FMA.
630 setOperationAction(ISD::FMA, MVT::f64, Expand);
631 setOperationAction(ISD::FMA, MVT::f32, Expand);
633 // Long double always uses X87.
635 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
636 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
637 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
639 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
640 addLegalFPImmediate(TmpFlt); // FLD0
642 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
645 APFloat TmpFlt2(+1.0);
646 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
648 addLegalFPImmediate(TmpFlt2); // FLD1
649 TmpFlt2.changeSign();
650 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
654 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
655 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
658 setOperationAction(ISD::FMA, MVT::f80, Expand);
661 // Always use a library call for pow.
662 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
663 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
664 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
666 setOperationAction(ISD::FLOG, MVT::f80, Expand);
667 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
668 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
669 setOperationAction(ISD::FEXP, MVT::f80, Expand);
670 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
672 // First set operation action for all vector types to either promote
673 // (for widening) or expand (for scalarization). Then we will selectively
674 // turn on ones that can be effectively codegen'd.
675 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
676 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
677 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
678 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
679 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
680 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
681 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
682 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
683 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
684 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
685 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
692 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
694 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
695 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
727 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
732 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
733 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
734 setTruncStoreAction((MVT::SimpleValueType)VT,
735 (MVT::SimpleValueType)InnerVT, Expand);
736 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
737 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
738 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
741 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
742 // with -msoft-float, disable use of MMX as well.
743 if (!UseSoftFloat && Subtarget->hasMMX()) {
744 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
745 // No operations on x86mmx supported, everything uses intrinsics.
748 // MMX-sized vectors (other than x86mmx) are expected to be expanded
749 // into smaller operations.
750 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
751 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
752 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
753 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
754 setOperationAction(ISD::AND, MVT::v8i8, Expand);
755 setOperationAction(ISD::AND, MVT::v4i16, Expand);
756 setOperationAction(ISD::AND, MVT::v2i32, Expand);
757 setOperationAction(ISD::AND, MVT::v1i64, Expand);
758 setOperationAction(ISD::OR, MVT::v8i8, Expand);
759 setOperationAction(ISD::OR, MVT::v4i16, Expand);
760 setOperationAction(ISD::OR, MVT::v2i32, Expand);
761 setOperationAction(ISD::OR, MVT::v1i64, Expand);
762 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
763 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
764 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
765 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
766 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
767 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
768 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
769 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
770 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
771 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
772 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
773 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
774 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
775 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
776 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
777 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
778 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
780 if (!UseSoftFloat && Subtarget->hasXMM()) {
781 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
783 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
784 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
785 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
786 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
787 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
788 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
789 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
790 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
791 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
792 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
793 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
794 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
797 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
798 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
800 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
801 // registers cannot be used even for integer operations.
802 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
803 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
804 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
805 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
807 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
808 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
809 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
810 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
811 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
812 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
813 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
814 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
815 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
816 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
817 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
818 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
819 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
820 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
821 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
822 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
824 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
825 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
826 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
827 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
831 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
835 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
836 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
837 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
838 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
839 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
841 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
842 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
843 EVT VT = (MVT::SimpleValueType)i;
844 // Do not attempt to custom lower non-power-of-2 vectors
845 if (!isPowerOf2_32(VT.getVectorNumElements()))
847 // Do not attempt to custom lower non-128-bit vectors
848 if (!VT.is128BitVector())
850 setOperationAction(ISD::BUILD_VECTOR,
851 VT.getSimpleVT().SimpleTy, Custom);
852 setOperationAction(ISD::VECTOR_SHUFFLE,
853 VT.getSimpleVT().SimpleTy, Custom);
854 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
855 VT.getSimpleVT().SimpleTy, Custom);
858 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
859 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
860 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
861 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
862 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
863 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
865 if (Subtarget->is64Bit()) {
866 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
867 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
870 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
871 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
872 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
875 // Do not attempt to promote non-128-bit vectors
876 if (!VT.is128BitVector())
879 setOperationAction(ISD::AND, SVT, Promote);
880 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
881 setOperationAction(ISD::OR, SVT, Promote);
882 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
883 setOperationAction(ISD::XOR, SVT, Promote);
884 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
885 setOperationAction(ISD::LOAD, SVT, Promote);
886 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
887 setOperationAction(ISD::SELECT, SVT, Promote);
888 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
891 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
893 // Custom lower v2i64 and v2f64 selects.
894 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
895 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
896 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
897 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
899 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
900 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
903 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
904 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
905 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
906 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
907 setOperationAction(ISD::FRINT, MVT::f32, Legal);
908 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
909 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
910 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
911 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
912 setOperationAction(ISD::FRINT, MVT::f64, Legal);
913 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
915 // FIXME: Do we need to handle scalar-to-vector here?
916 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
918 // Can turn SHL into an integer multiply.
919 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
920 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
922 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
923 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
924 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
925 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
926 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
928 // i8 and i16 vectors are custom , because the source register and source
929 // source memory operand types are not the same width. f32 vectors are
930 // custom since the immediate controlling the insert encodes additional
932 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
933 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
934 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
935 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
938 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
939 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
940 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
942 if (Subtarget->is64Bit()) {
943 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
948 if (Subtarget->hasXMMInt()) {
949 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
950 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
951 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
952 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
954 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
955 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
956 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
958 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
959 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
962 if (Subtarget->hasSSE42() || Subtarget->hasAVX())
963 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
965 if (!UseSoftFloat && Subtarget->hasAVX()) {
966 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
967 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
968 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
969 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
970 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
971 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
973 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
974 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
975 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
977 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
978 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
979 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
980 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
981 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
982 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
984 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
985 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
986 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
987 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
988 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
989 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
991 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
992 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
993 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
995 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
996 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
997 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
998 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
999 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1000 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1002 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1003 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1004 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1005 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1007 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1008 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1009 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1010 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1012 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1013 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1015 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1016 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1017 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1018 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1020 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1021 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1022 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1024 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1025 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1026 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1027 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1029 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1030 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1031 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1032 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1034 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1035 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1036 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1037 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1039 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1040 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1041 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1042 // Don't lower v32i8 because there is no 128-bit byte mul
1044 // Custom lower several nodes for 256-bit types.
1045 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1046 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1047 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1050 // Extract subvector is special because the value type
1051 // (result) is 128-bit but the source is 256-bit wide.
1052 if (VT.is128BitVector())
1053 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1055 // Do not attempt to custom lower other non-256-bit vectors
1056 if (!VT.is256BitVector())
1059 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1060 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1061 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1062 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1063 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1064 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1067 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1068 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1069 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1072 // Do not attempt to promote non-256-bit vectors
1073 if (!VT.is256BitVector())
1076 setOperationAction(ISD::AND, SVT, Promote);
1077 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1078 setOperationAction(ISD::OR, SVT, Promote);
1079 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1080 setOperationAction(ISD::XOR, SVT, Promote);
1081 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1082 setOperationAction(ISD::LOAD, SVT, Promote);
1083 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1084 setOperationAction(ISD::SELECT, SVT, Promote);
1085 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1089 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1090 // of this type with custom code.
1091 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1092 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1093 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1096 // We want to custom lower some of our intrinsics.
1097 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1100 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1101 // handle type legalization for these operations here.
1103 // FIXME: We really should do custom legalization for addition and
1104 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1105 // than generic legalization for 64-bit multiplication-with-overflow, though.
1106 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1107 // Add/Sub/Mul with overflow operations are custom lowered.
1109 setOperationAction(ISD::SADDO, VT, Custom);
1110 setOperationAction(ISD::UADDO, VT, Custom);
1111 setOperationAction(ISD::SSUBO, VT, Custom);
1112 setOperationAction(ISD::USUBO, VT, Custom);
1113 setOperationAction(ISD::SMULO, VT, Custom);
1114 setOperationAction(ISD::UMULO, VT, Custom);
1117 // There are no 8-bit 3-address imul/mul instructions
1118 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1119 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1121 if (!Subtarget->is64Bit()) {
1122 // These libcalls are not available in 32-bit.
1123 setLibcallName(RTLIB::SHL_I128, 0);
1124 setLibcallName(RTLIB::SRL_I128, 0);
1125 setLibcallName(RTLIB::SRA_I128, 0);
1128 // We have target-specific dag combine patterns for the following nodes:
1129 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1130 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1131 setTargetDAGCombine(ISD::BUILD_VECTOR);
1132 setTargetDAGCombine(ISD::VSELECT);
1133 setTargetDAGCombine(ISD::SELECT);
1134 setTargetDAGCombine(ISD::SHL);
1135 setTargetDAGCombine(ISD::SRA);
1136 setTargetDAGCombine(ISD::SRL);
1137 setTargetDAGCombine(ISD::OR);
1138 setTargetDAGCombine(ISD::AND);
1139 setTargetDAGCombine(ISD::ADD);
1140 setTargetDAGCombine(ISD::FADD);
1141 setTargetDAGCombine(ISD::FSUB);
1142 setTargetDAGCombine(ISD::SUB);
1143 setTargetDAGCombine(ISD::LOAD);
1144 setTargetDAGCombine(ISD::STORE);
1145 setTargetDAGCombine(ISD::ZERO_EXTEND);
1146 setTargetDAGCombine(ISD::SINT_TO_FP);
1147 if (Subtarget->is64Bit())
1148 setTargetDAGCombine(ISD::MUL);
1150 computeRegisterProperties();
1152 // On Darwin, -Os means optimize for size without hurting performance,
1153 // do not reduce the limit.
1154 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1155 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1156 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1157 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1158 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1159 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1160 setPrefLoopAlignment(16);
1161 benefitFromCodePlacementOpt = true;
1163 setPrefFunctionAlignment(4);
1167 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1168 if (!VT.isVector()) return MVT::i8;
1169 return VT.changeVectorElementTypeToInteger();
1173 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1174 /// the desired ByVal argument alignment.
1175 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1178 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1179 if (VTy->getBitWidth() == 128)
1181 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1182 unsigned EltAlign = 0;
1183 getMaxByValAlign(ATy->getElementType(), EltAlign);
1184 if (EltAlign > MaxAlign)
1185 MaxAlign = EltAlign;
1186 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1187 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1188 unsigned EltAlign = 0;
1189 getMaxByValAlign(STy->getElementType(i), EltAlign);
1190 if (EltAlign > MaxAlign)
1191 MaxAlign = EltAlign;
1199 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1200 /// function arguments in the caller parameter area. For X86, aggregates
1201 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1202 /// are at 4-byte boundaries.
1203 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1204 if (Subtarget->is64Bit()) {
1205 // Max of 8 and alignment of type.
1206 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1213 if (Subtarget->hasXMM())
1214 getMaxByValAlign(Ty, Align);
1218 /// getOptimalMemOpType - Returns the target specific optimal type for load
1219 /// and store operations as a result of memset, memcpy, and memmove
1220 /// lowering. If DstAlign is zero that means it's safe to destination
1221 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1222 /// means there isn't a need to check it against alignment requirement,
1223 /// probably because the source does not need to be loaded. If
1224 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1225 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1226 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1227 /// constant so it does not need to be loaded.
1228 /// It returns EVT::Other if the type should be determined using generic
1229 /// target-independent logic.
1231 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1232 unsigned DstAlign, unsigned SrcAlign,
1233 bool NonScalarIntSafe,
1235 MachineFunction &MF) const {
1236 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1237 // linux. This is because the stack realignment code can't handle certain
1238 // cases like PR2962. This should be removed when PR2962 is fixed.
1239 const Function *F = MF.getFunction();
1240 if (NonScalarIntSafe &&
1241 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1243 (Subtarget->isUnalignedMemAccessFast() ||
1244 ((DstAlign == 0 || DstAlign >= 16) &&
1245 (SrcAlign == 0 || SrcAlign >= 16))) &&
1246 Subtarget->getStackAlignment() >= 16) {
1247 if (Subtarget->hasAVX() &&
1248 Subtarget->getStackAlignment() >= 32)
1250 if (Subtarget->hasXMMInt())
1252 if (Subtarget->hasXMM())
1254 } else if (!MemcpyStrSrc && Size >= 8 &&
1255 !Subtarget->is64Bit() &&
1256 Subtarget->getStackAlignment() >= 8 &&
1257 Subtarget->hasXMMInt()) {
1258 // Do not use f64 to lower memcpy if source is string constant. It's
1259 // better to use i32 to avoid the loads.
1263 if (Subtarget->is64Bit() && Size >= 8)
1268 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1269 /// current function. The returned value is a member of the
1270 /// MachineJumpTableInfo::JTEntryKind enum.
1271 unsigned X86TargetLowering::getJumpTableEncoding() const {
1272 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1274 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1275 Subtarget->isPICStyleGOT())
1276 return MachineJumpTableInfo::EK_Custom32;
1278 // Otherwise, use the normal jump table encoding heuristics.
1279 return TargetLowering::getJumpTableEncoding();
1283 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1284 const MachineBasicBlock *MBB,
1285 unsigned uid,MCContext &Ctx) const{
1286 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1287 Subtarget->isPICStyleGOT());
1288 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1290 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1291 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1294 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1296 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1297 SelectionDAG &DAG) const {
1298 if (!Subtarget->is64Bit())
1299 // This doesn't have DebugLoc associated with it, but is not really the
1300 // same as a Register.
1301 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1305 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1306 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1308 const MCExpr *X86TargetLowering::
1309 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1310 MCContext &Ctx) const {
1311 // X86-64 uses RIP relative addressing based on the jump table label.
1312 if (Subtarget->isPICStyleRIPRel())
1313 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1315 // Otherwise, the reference is relative to the PIC base.
1316 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1319 // FIXME: Why this routine is here? Move to RegInfo!
1320 std::pair<const TargetRegisterClass*, uint8_t>
1321 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1322 const TargetRegisterClass *RRC = 0;
1324 switch (VT.getSimpleVT().SimpleTy) {
1326 return TargetLowering::findRepresentativeClass(VT);
1327 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1328 RRC = (Subtarget->is64Bit()
1329 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1332 RRC = X86::VR64RegisterClass;
1334 case MVT::f32: case MVT::f64:
1335 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1336 case MVT::v4f32: case MVT::v2f64:
1337 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1339 RRC = X86::VR128RegisterClass;
1342 return std::make_pair(RRC, Cost);
1345 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1346 unsigned &Offset) const {
1347 if (!Subtarget->isTargetLinux())
1350 if (Subtarget->is64Bit()) {
1351 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1353 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1366 //===----------------------------------------------------------------------===//
1367 // Return Value Calling Convention Implementation
1368 //===----------------------------------------------------------------------===//
1370 #include "X86GenCallingConv.inc"
1373 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1374 MachineFunction &MF, bool isVarArg,
1375 const SmallVectorImpl<ISD::OutputArg> &Outs,
1376 LLVMContext &Context) const {
1377 SmallVector<CCValAssign, 16> RVLocs;
1378 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1380 return CCInfo.CheckReturn(Outs, RetCC_X86);
1384 X86TargetLowering::LowerReturn(SDValue Chain,
1385 CallingConv::ID CallConv, bool isVarArg,
1386 const SmallVectorImpl<ISD::OutputArg> &Outs,
1387 const SmallVectorImpl<SDValue> &OutVals,
1388 DebugLoc dl, SelectionDAG &DAG) const {
1389 MachineFunction &MF = DAG.getMachineFunction();
1390 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1392 SmallVector<CCValAssign, 16> RVLocs;
1393 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1394 RVLocs, *DAG.getContext());
1395 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1397 // Add the regs to the liveout set for the function.
1398 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1399 for (unsigned i = 0; i != RVLocs.size(); ++i)
1400 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1401 MRI.addLiveOut(RVLocs[i].getLocReg());
1405 SmallVector<SDValue, 6> RetOps;
1406 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1407 // Operand #1 = Bytes To Pop
1408 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1411 // Copy the result values into the output registers.
1412 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1413 CCValAssign &VA = RVLocs[i];
1414 assert(VA.isRegLoc() && "Can only return in registers!");
1415 SDValue ValToCopy = OutVals[i];
1416 EVT ValVT = ValToCopy.getValueType();
1418 // If this is x86-64, and we disabled SSE, we can't return FP values,
1419 // or SSE or MMX vectors.
1420 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1421 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1422 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1423 report_fatal_error("SSE register return with SSE disabled");
1425 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1426 // llvm-gcc has never done it right and no one has noticed, so this
1427 // should be OK for now.
1428 if (ValVT == MVT::f64 &&
1429 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1430 report_fatal_error("SSE2 register return with SSE2 disabled");
1432 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1433 // the RET instruction and handled by the FP Stackifier.
1434 if (VA.getLocReg() == X86::ST0 ||
1435 VA.getLocReg() == X86::ST1) {
1436 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1437 // change the value to the FP stack register class.
1438 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1439 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1440 RetOps.push_back(ValToCopy);
1441 // Don't emit a copytoreg.
1445 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1446 // which is returned in RAX / RDX.
1447 if (Subtarget->is64Bit()) {
1448 if (ValVT == MVT::x86mmx) {
1449 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1450 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1451 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1453 // If we don't have SSE2 available, convert to v4f32 so the generated
1454 // register is legal.
1455 if (!Subtarget->hasXMMInt())
1456 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1461 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1462 Flag = Chain.getValue(1);
1465 // The x86-64 ABI for returning structs by value requires that we copy
1466 // the sret argument into %rax for the return. We saved the argument into
1467 // a virtual register in the entry block, so now we copy the value out
1469 if (Subtarget->is64Bit() &&
1470 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1471 MachineFunction &MF = DAG.getMachineFunction();
1472 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1473 unsigned Reg = FuncInfo->getSRetReturnReg();
1475 "SRetReturnReg should have been set in LowerFormalArguments().");
1476 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1478 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1479 Flag = Chain.getValue(1);
1481 // RAX now acts like a return value.
1482 MRI.addLiveOut(X86::RAX);
1485 RetOps[0] = Chain; // Update chain.
1487 // Add the flag if we have it.
1489 RetOps.push_back(Flag);
1491 return DAG.getNode(X86ISD::RET_FLAG, dl,
1492 MVT::Other, &RetOps[0], RetOps.size());
1495 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1496 if (N->getNumValues() != 1)
1498 if (!N->hasNUsesOfValue(1, 0))
1501 SDNode *Copy = *N->use_begin();
1502 if (Copy->getOpcode() != ISD::CopyToReg &&
1503 Copy->getOpcode() != ISD::FP_EXTEND)
1506 bool HasRet = false;
1507 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1509 if (UI->getOpcode() != X86ISD::RET_FLAG)
1518 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1519 ISD::NodeType ExtendKind) const {
1521 // TODO: Is this also valid on 32-bit?
1522 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1523 ReturnMVT = MVT::i8;
1525 ReturnMVT = MVT::i32;
1527 EVT MinVT = getRegisterType(Context, ReturnMVT);
1528 return VT.bitsLT(MinVT) ? MinVT : VT;
1531 /// LowerCallResult - Lower the result values of a call into the
1532 /// appropriate copies out of appropriate physical registers.
1535 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1536 CallingConv::ID CallConv, bool isVarArg,
1537 const SmallVectorImpl<ISD::InputArg> &Ins,
1538 DebugLoc dl, SelectionDAG &DAG,
1539 SmallVectorImpl<SDValue> &InVals) const {
1541 // Assign locations to each value returned by this call.
1542 SmallVector<CCValAssign, 16> RVLocs;
1543 bool Is64Bit = Subtarget->is64Bit();
1544 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1545 getTargetMachine(), RVLocs, *DAG.getContext());
1546 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1548 // Copy all of the result registers out of their specified physreg.
1549 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1550 CCValAssign &VA = RVLocs[i];
1551 EVT CopyVT = VA.getValVT();
1553 // If this is x86-64, and we disabled SSE, we can't return FP values
1554 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1555 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1556 report_fatal_error("SSE register return with SSE disabled");
1561 // If this is a call to a function that returns an fp value on the floating
1562 // point stack, we must guarantee the the value is popped from the stack, so
1563 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1564 // if the return value is not used. We use the FpPOP_RETVAL instruction
1566 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1567 // If we prefer to use the value in xmm registers, copy it out as f80 and
1568 // use a truncate to move it from fp stack reg to xmm reg.
1569 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1570 SDValue Ops[] = { Chain, InFlag };
1571 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1572 MVT::Other, MVT::Glue, Ops, 2), 1);
1573 Val = Chain.getValue(0);
1575 // Round the f80 to the right size, which also moves it to the appropriate
1577 if (CopyVT != VA.getValVT())
1578 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1579 // This truncation won't change the value.
1580 DAG.getIntPtrConstant(1));
1582 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1583 CopyVT, InFlag).getValue(1);
1584 Val = Chain.getValue(0);
1586 InFlag = Chain.getValue(2);
1587 InVals.push_back(Val);
1594 //===----------------------------------------------------------------------===//
1595 // C & StdCall & Fast Calling Convention implementation
1596 //===----------------------------------------------------------------------===//
1597 // StdCall calling convention seems to be standard for many Windows' API
1598 // routines and around. It differs from C calling convention just a little:
1599 // callee should clean up the stack, not caller. Symbols should be also
1600 // decorated in some fancy way :) It doesn't support any vector arguments.
1601 // For info on fast calling convention see Fast Calling Convention (tail call)
1602 // implementation LowerX86_32FastCCCallTo.
1604 /// CallIsStructReturn - Determines whether a call uses struct return
1606 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1610 return Outs[0].Flags.isSRet();
1613 /// ArgsAreStructReturn - Determines whether a function uses struct
1614 /// return semantics.
1616 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1620 return Ins[0].Flags.isSRet();
1623 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1624 /// by "Src" to address "Dst" with size and alignment information specified by
1625 /// the specific parameter attribute. The copy will be passed as a byval
1626 /// function parameter.
1628 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1629 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1631 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1633 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1634 /*isVolatile*/false, /*AlwaysInline=*/true,
1635 MachinePointerInfo(), MachinePointerInfo());
1638 /// IsTailCallConvention - Return true if the calling convention is one that
1639 /// supports tail call optimization.
1640 static bool IsTailCallConvention(CallingConv::ID CC) {
1641 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1644 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1645 if (!CI->isTailCall())
1649 CallingConv::ID CalleeCC = CS.getCallingConv();
1650 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1656 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1657 /// a tailcall target by changing its ABI.
1658 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1659 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1663 X86TargetLowering::LowerMemArgument(SDValue Chain,
1664 CallingConv::ID CallConv,
1665 const SmallVectorImpl<ISD::InputArg> &Ins,
1666 DebugLoc dl, SelectionDAG &DAG,
1667 const CCValAssign &VA,
1668 MachineFrameInfo *MFI,
1670 // Create the nodes corresponding to a load from this parameter slot.
1671 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1672 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1673 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1676 // If value is passed by pointer we have address passed instead of the value
1678 if (VA.getLocInfo() == CCValAssign::Indirect)
1679 ValVT = VA.getLocVT();
1681 ValVT = VA.getValVT();
1683 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1684 // changed with more analysis.
1685 // In case of tail call optimization mark all arguments mutable. Since they
1686 // could be overwritten by lowering of arguments in case of a tail call.
1687 if (Flags.isByVal()) {
1688 unsigned Bytes = Flags.getByValSize();
1689 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1690 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1691 return DAG.getFrameIndex(FI, getPointerTy());
1693 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1694 VA.getLocMemOffset(), isImmutable);
1695 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1696 return DAG.getLoad(ValVT, dl, Chain, FIN,
1697 MachinePointerInfo::getFixedStack(FI),
1703 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1704 CallingConv::ID CallConv,
1706 const SmallVectorImpl<ISD::InputArg> &Ins,
1709 SmallVectorImpl<SDValue> &InVals)
1711 MachineFunction &MF = DAG.getMachineFunction();
1712 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1714 const Function* Fn = MF.getFunction();
1715 if (Fn->hasExternalLinkage() &&
1716 Subtarget->isTargetCygMing() &&
1717 Fn->getName() == "main")
1718 FuncInfo->setForceFramePointer(true);
1720 MachineFrameInfo *MFI = MF.getFrameInfo();
1721 bool Is64Bit = Subtarget->is64Bit();
1722 bool IsWin64 = Subtarget->isTargetWin64();
1724 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1725 "Var args not supported with calling convention fastcc or ghc");
1727 // Assign locations to all of the incoming arguments.
1728 SmallVector<CCValAssign, 16> ArgLocs;
1729 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1730 ArgLocs, *DAG.getContext());
1732 // Allocate shadow area for Win64
1734 CCInfo.AllocateStack(32, 8);
1737 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1739 unsigned LastVal = ~0U;
1741 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1742 CCValAssign &VA = ArgLocs[i];
1743 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1745 assert(VA.getValNo() != LastVal &&
1746 "Don't support value assigned to multiple locs yet");
1747 LastVal = VA.getValNo();
1749 if (VA.isRegLoc()) {
1750 EVT RegVT = VA.getLocVT();
1751 TargetRegisterClass *RC = NULL;
1752 if (RegVT == MVT::i32)
1753 RC = X86::GR32RegisterClass;
1754 else if (Is64Bit && RegVT == MVT::i64)
1755 RC = X86::GR64RegisterClass;
1756 else if (RegVT == MVT::f32)
1757 RC = X86::FR32RegisterClass;
1758 else if (RegVT == MVT::f64)
1759 RC = X86::FR64RegisterClass;
1760 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1761 RC = X86::VR256RegisterClass;
1762 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1763 RC = X86::VR128RegisterClass;
1764 else if (RegVT == MVT::x86mmx)
1765 RC = X86::VR64RegisterClass;
1767 llvm_unreachable("Unknown argument type!");
1769 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1770 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1772 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1773 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1775 if (VA.getLocInfo() == CCValAssign::SExt)
1776 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1777 DAG.getValueType(VA.getValVT()));
1778 else if (VA.getLocInfo() == CCValAssign::ZExt)
1779 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1780 DAG.getValueType(VA.getValVT()));
1781 else if (VA.getLocInfo() == CCValAssign::BCvt)
1782 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1784 if (VA.isExtInLoc()) {
1785 // Handle MMX values passed in XMM regs.
1786 if (RegVT.isVector()) {
1787 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1790 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1793 assert(VA.isMemLoc());
1794 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1797 // If value is passed via pointer - do a load.
1798 if (VA.getLocInfo() == CCValAssign::Indirect)
1799 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1800 MachinePointerInfo(), false, false, 0);
1802 InVals.push_back(ArgValue);
1805 // The x86-64 ABI for returning structs by value requires that we copy
1806 // the sret argument into %rax for the return. Save the argument into
1807 // a virtual register so that we can access it from the return points.
1808 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1809 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1810 unsigned Reg = FuncInfo->getSRetReturnReg();
1812 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1813 FuncInfo->setSRetReturnReg(Reg);
1815 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1816 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1819 unsigned StackSize = CCInfo.getNextStackOffset();
1820 // Align stack specially for tail calls.
1821 if (FuncIsMadeTailCallSafe(CallConv))
1822 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1824 // If the function takes variable number of arguments, make a frame index for
1825 // the start of the first vararg value... for expansion of llvm.va_start.
1827 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1828 CallConv != CallingConv::X86_ThisCall)) {
1829 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1832 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1834 // FIXME: We should really autogenerate these arrays
1835 static const unsigned GPR64ArgRegsWin64[] = {
1836 X86::RCX, X86::RDX, X86::R8, X86::R9
1838 static const unsigned GPR64ArgRegs64Bit[] = {
1839 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1841 static const unsigned XMMArgRegs64Bit[] = {
1842 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1843 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1845 const unsigned *GPR64ArgRegs;
1846 unsigned NumXMMRegs = 0;
1849 // The XMM registers which might contain var arg parameters are shadowed
1850 // in their paired GPR. So we only need to save the GPR to their home
1852 TotalNumIntRegs = 4;
1853 GPR64ArgRegs = GPR64ArgRegsWin64;
1855 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1856 GPR64ArgRegs = GPR64ArgRegs64Bit;
1858 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1860 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1863 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1864 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1865 "SSE register cannot be used when SSE is disabled!");
1866 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1867 "SSE register cannot be used when SSE is disabled!");
1868 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1869 // Kernel mode asks for SSE to be disabled, so don't push them
1871 TotalNumXMMRegs = 0;
1874 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1875 // Get to the caller-allocated home save location. Add 8 to account
1876 // for the return address.
1877 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1878 FuncInfo->setRegSaveFrameIndex(
1879 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1880 // Fixup to set vararg frame on shadow area (4 x i64).
1882 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1884 // For X86-64, if there are vararg parameters that are passed via
1885 // registers, then we must store them to their spots on the stack so they
1886 // may be loaded by deferencing the result of va_next.
1887 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1888 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1889 FuncInfo->setRegSaveFrameIndex(
1890 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1894 // Store the integer parameter registers.
1895 SmallVector<SDValue, 8> MemOps;
1896 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1898 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1899 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1900 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1901 DAG.getIntPtrConstant(Offset));
1902 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1903 X86::GR64RegisterClass);
1904 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1906 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1907 MachinePointerInfo::getFixedStack(
1908 FuncInfo->getRegSaveFrameIndex(), Offset),
1910 MemOps.push_back(Store);
1914 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1915 // Now store the XMM (fp + vector) parameter registers.
1916 SmallVector<SDValue, 11> SaveXMMOps;
1917 SaveXMMOps.push_back(Chain);
1919 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1920 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1921 SaveXMMOps.push_back(ALVal);
1923 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1924 FuncInfo->getRegSaveFrameIndex()));
1925 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1926 FuncInfo->getVarArgsFPOffset()));
1928 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1929 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1930 X86::VR128RegisterClass);
1931 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1932 SaveXMMOps.push_back(Val);
1934 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1936 &SaveXMMOps[0], SaveXMMOps.size()));
1939 if (!MemOps.empty())
1940 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1941 &MemOps[0], MemOps.size());
1945 // Some CCs need callee pop.
1946 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1947 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1949 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1950 // If this is an sret function, the return should pop the hidden pointer.
1951 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1952 FuncInfo->setBytesToPopOnReturn(4);
1956 // RegSaveFrameIndex is X86-64 only.
1957 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1958 if (CallConv == CallingConv::X86_FastCall ||
1959 CallConv == CallingConv::X86_ThisCall)
1960 // fastcc functions can't have varargs.
1961 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1964 FuncInfo->setArgumentStackSize(StackSize);
1970 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1971 SDValue StackPtr, SDValue Arg,
1972 DebugLoc dl, SelectionDAG &DAG,
1973 const CCValAssign &VA,
1974 ISD::ArgFlagsTy Flags) const {
1975 unsigned LocMemOffset = VA.getLocMemOffset();
1976 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1977 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1978 if (Flags.isByVal())
1979 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1981 return DAG.getStore(Chain, dl, Arg, PtrOff,
1982 MachinePointerInfo::getStack(LocMemOffset),
1986 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1987 /// optimization is performed and it is required.
1989 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1990 SDValue &OutRetAddr, SDValue Chain,
1991 bool IsTailCall, bool Is64Bit,
1992 int FPDiff, DebugLoc dl) const {
1993 // Adjust the Return address stack slot.
1994 EVT VT = getPointerTy();
1995 OutRetAddr = getReturnAddressFrameIndex(DAG);
1997 // Load the "old" Return address.
1998 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2000 return SDValue(OutRetAddr.getNode(), 1);
2003 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2004 /// optimization is performed and it is required (FPDiff!=0).
2006 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2007 SDValue Chain, SDValue RetAddrFrIdx,
2008 bool Is64Bit, int FPDiff, DebugLoc dl) {
2009 // Store the return address to the appropriate stack slot.
2010 if (!FPDiff) return Chain;
2011 // Calculate the new stack slot for the return address.
2012 int SlotSize = Is64Bit ? 8 : 4;
2013 int NewReturnAddrFI =
2014 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2015 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2016 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2017 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2018 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2024 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2025 CallingConv::ID CallConv, bool isVarArg,
2027 const SmallVectorImpl<ISD::OutputArg> &Outs,
2028 const SmallVectorImpl<SDValue> &OutVals,
2029 const SmallVectorImpl<ISD::InputArg> &Ins,
2030 DebugLoc dl, SelectionDAG &DAG,
2031 SmallVectorImpl<SDValue> &InVals) const {
2032 MachineFunction &MF = DAG.getMachineFunction();
2033 bool Is64Bit = Subtarget->is64Bit();
2034 bool IsWin64 = Subtarget->isTargetWin64();
2035 bool IsStructRet = CallIsStructReturn(Outs);
2036 bool IsSibcall = false;
2039 // Check if it's really possible to do a tail call.
2040 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2041 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2042 Outs, OutVals, Ins, DAG);
2044 // Sibcalls are automatically detected tailcalls which do not require
2046 if (!GuaranteedTailCallOpt && isTailCall)
2053 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2054 "Var args not supported with calling convention fastcc or ghc");
2056 // Analyze operands of the call, assigning locations to each operand.
2057 SmallVector<CCValAssign, 16> ArgLocs;
2058 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2059 ArgLocs, *DAG.getContext());
2061 // Allocate shadow area for Win64
2063 CCInfo.AllocateStack(32, 8);
2066 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2068 // Get a count of how many bytes are to be pushed on the stack.
2069 unsigned NumBytes = CCInfo.getNextStackOffset();
2071 // This is a sibcall. The memory operands are available in caller's
2072 // own caller's stack.
2074 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2075 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2078 if (isTailCall && !IsSibcall) {
2079 // Lower arguments at fp - stackoffset + fpdiff.
2080 unsigned NumBytesCallerPushed =
2081 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2082 FPDiff = NumBytesCallerPushed - NumBytes;
2084 // Set the delta of movement of the returnaddr stackslot.
2085 // But only set if delta is greater than previous delta.
2086 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2087 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2091 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2093 SDValue RetAddrFrIdx;
2094 // Load return address for tail calls.
2095 if (isTailCall && FPDiff)
2096 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2097 Is64Bit, FPDiff, dl);
2099 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2100 SmallVector<SDValue, 8> MemOpChains;
2103 // Walk the register/memloc assignments, inserting copies/loads. In the case
2104 // of tail call optimization arguments are handle later.
2105 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2106 CCValAssign &VA = ArgLocs[i];
2107 EVT RegVT = VA.getLocVT();
2108 SDValue Arg = OutVals[i];
2109 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2110 bool isByVal = Flags.isByVal();
2112 // Promote the value if needed.
2113 switch (VA.getLocInfo()) {
2114 default: llvm_unreachable("Unknown loc info!");
2115 case CCValAssign::Full: break;
2116 case CCValAssign::SExt:
2117 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2119 case CCValAssign::ZExt:
2120 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2122 case CCValAssign::AExt:
2123 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2124 // Special case: passing MMX values in XMM registers.
2125 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2126 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2127 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2129 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2131 case CCValAssign::BCvt:
2132 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2134 case CCValAssign::Indirect: {
2135 // Store the argument.
2136 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2137 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2138 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2139 MachinePointerInfo::getFixedStack(FI),
2146 if (VA.isRegLoc()) {
2147 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2148 if (isVarArg && IsWin64) {
2149 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2150 // shadow reg if callee is a varargs function.
2151 unsigned ShadowReg = 0;
2152 switch (VA.getLocReg()) {
2153 case X86::XMM0: ShadowReg = X86::RCX; break;
2154 case X86::XMM1: ShadowReg = X86::RDX; break;
2155 case X86::XMM2: ShadowReg = X86::R8; break;
2156 case X86::XMM3: ShadowReg = X86::R9; break;
2159 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2161 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2162 assert(VA.isMemLoc());
2163 if (StackPtr.getNode() == 0)
2164 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2165 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2166 dl, DAG, VA, Flags));
2170 if (!MemOpChains.empty())
2171 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2172 &MemOpChains[0], MemOpChains.size());
2174 // Build a sequence of copy-to-reg nodes chained together with token chain
2175 // and flag operands which copy the outgoing args into registers.
2177 // Tail call byval lowering might overwrite argument registers so in case of
2178 // tail call optimization the copies to registers are lowered later.
2180 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2181 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2182 RegsToPass[i].second, InFlag);
2183 InFlag = Chain.getValue(1);
2186 if (Subtarget->isPICStyleGOT()) {
2187 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2190 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2191 DAG.getNode(X86ISD::GlobalBaseReg,
2192 DebugLoc(), getPointerTy()),
2194 InFlag = Chain.getValue(1);
2196 // If we are tail calling and generating PIC/GOT style code load the
2197 // address of the callee into ECX. The value in ecx is used as target of
2198 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2199 // for tail calls on PIC/GOT architectures. Normally we would just put the
2200 // address of GOT into ebx and then call target@PLT. But for tail calls
2201 // ebx would be restored (since ebx is callee saved) before jumping to the
2204 // Note: The actual moving to ECX is done further down.
2205 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2206 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2207 !G->getGlobal()->hasProtectedVisibility())
2208 Callee = LowerGlobalAddress(Callee, DAG);
2209 else if (isa<ExternalSymbolSDNode>(Callee))
2210 Callee = LowerExternalSymbol(Callee, DAG);
2214 if (Is64Bit && isVarArg && !IsWin64) {
2215 // From AMD64 ABI document:
2216 // For calls that may call functions that use varargs or stdargs
2217 // (prototype-less calls or calls to functions containing ellipsis (...) in
2218 // the declaration) %al is used as hidden argument to specify the number
2219 // of SSE registers used. The contents of %al do not need to match exactly
2220 // the number of registers, but must be an ubound on the number of SSE
2221 // registers used and is in the range 0 - 8 inclusive.
2223 // Count the number of XMM registers allocated.
2224 static const unsigned XMMArgRegs[] = {
2225 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2226 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2228 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2229 assert((Subtarget->hasXMM() || !NumXMMRegs)
2230 && "SSE registers cannot be used when SSE is disabled");
2232 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2233 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2234 InFlag = Chain.getValue(1);
2238 // For tail calls lower the arguments to the 'real' stack slot.
2240 // Force all the incoming stack arguments to be loaded from the stack
2241 // before any new outgoing arguments are stored to the stack, because the
2242 // outgoing stack slots may alias the incoming argument stack slots, and
2243 // the alias isn't otherwise explicit. This is slightly more conservative
2244 // than necessary, because it means that each store effectively depends
2245 // on every argument instead of just those arguments it would clobber.
2246 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2248 SmallVector<SDValue, 8> MemOpChains2;
2251 // Do not flag preceding copytoreg stuff together with the following stuff.
2253 if (GuaranteedTailCallOpt) {
2254 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2255 CCValAssign &VA = ArgLocs[i];
2258 assert(VA.isMemLoc());
2259 SDValue Arg = OutVals[i];
2260 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2261 // Create frame index.
2262 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2263 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2264 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2265 FIN = DAG.getFrameIndex(FI, getPointerTy());
2267 if (Flags.isByVal()) {
2268 // Copy relative to framepointer.
2269 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2270 if (StackPtr.getNode() == 0)
2271 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2273 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2275 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2279 // Store relative to framepointer.
2280 MemOpChains2.push_back(
2281 DAG.getStore(ArgChain, dl, Arg, FIN,
2282 MachinePointerInfo::getFixedStack(FI),
2288 if (!MemOpChains2.empty())
2289 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2290 &MemOpChains2[0], MemOpChains2.size());
2292 // Copy arguments to their registers.
2293 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2294 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2295 RegsToPass[i].second, InFlag);
2296 InFlag = Chain.getValue(1);
2300 // Store the return address to the appropriate stack slot.
2301 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2305 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2306 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2307 // In the 64-bit large code model, we have to make all calls
2308 // through a register, since the call instruction's 32-bit
2309 // pc-relative offset may not be large enough to hold the whole
2311 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2312 // If the callee is a GlobalAddress node (quite common, every direct call
2313 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2316 // We should use extra load for direct calls to dllimported functions in
2318 const GlobalValue *GV = G->getGlobal();
2319 if (!GV->hasDLLImportLinkage()) {
2320 unsigned char OpFlags = 0;
2321 bool ExtraLoad = false;
2322 unsigned WrapperKind = ISD::DELETED_NODE;
2324 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2325 // external symbols most go through the PLT in PIC mode. If the symbol
2326 // has hidden or protected visibility, or if it is static or local, then
2327 // we don't need to use the PLT - we can directly call it.
2328 if (Subtarget->isTargetELF() &&
2329 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2330 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2331 OpFlags = X86II::MO_PLT;
2332 } else if (Subtarget->isPICStyleStubAny() &&
2333 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2334 (!Subtarget->getTargetTriple().isMacOSX() ||
2335 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2336 // PC-relative references to external symbols should go through $stub,
2337 // unless we're building with the leopard linker or later, which
2338 // automatically synthesizes these stubs.
2339 OpFlags = X86II::MO_DARWIN_STUB;
2340 } else if (Subtarget->isPICStyleRIPRel() &&
2341 isa<Function>(GV) &&
2342 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2343 // If the function is marked as non-lazy, generate an indirect call
2344 // which loads from the GOT directly. This avoids runtime overhead
2345 // at the cost of eager binding (and one extra byte of encoding).
2346 OpFlags = X86II::MO_GOTPCREL;
2347 WrapperKind = X86ISD::WrapperRIP;
2351 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2352 G->getOffset(), OpFlags);
2354 // Add a wrapper if needed.
2355 if (WrapperKind != ISD::DELETED_NODE)
2356 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2357 // Add extra indirection if needed.
2359 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2360 MachinePointerInfo::getGOT(),
2363 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2364 unsigned char OpFlags = 0;
2366 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2367 // external symbols should go through the PLT.
2368 if (Subtarget->isTargetELF() &&
2369 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2370 OpFlags = X86II::MO_PLT;
2371 } else if (Subtarget->isPICStyleStubAny() &&
2372 (!Subtarget->getTargetTriple().isMacOSX() ||
2373 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2374 // PC-relative references to external symbols should go through $stub,
2375 // unless we're building with the leopard linker or later, which
2376 // automatically synthesizes these stubs.
2377 OpFlags = X86II::MO_DARWIN_STUB;
2380 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2384 // Returns a chain & a flag for retval copy to use.
2385 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2386 SmallVector<SDValue, 8> Ops;
2388 if (!IsSibcall && isTailCall) {
2389 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2390 DAG.getIntPtrConstant(0, true), InFlag);
2391 InFlag = Chain.getValue(1);
2394 Ops.push_back(Chain);
2395 Ops.push_back(Callee);
2398 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2400 // Add argument registers to the end of the list so that they are known live
2402 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2403 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2404 RegsToPass[i].second.getValueType()));
2406 // Add an implicit use GOT pointer in EBX.
2407 if (!isTailCall && Subtarget->isPICStyleGOT())
2408 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2410 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2411 if (Is64Bit && isVarArg && !IsWin64)
2412 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2414 if (InFlag.getNode())
2415 Ops.push_back(InFlag);
2419 //// If this is the first return lowered for this function, add the regs
2420 //// to the liveout set for the function.
2421 // This isn't right, although it's probably harmless on x86; liveouts
2422 // should be computed from returns not tail calls. Consider a void
2423 // function making a tail call to a function returning int.
2424 return DAG.getNode(X86ISD::TC_RETURN, dl,
2425 NodeTys, &Ops[0], Ops.size());
2428 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2429 InFlag = Chain.getValue(1);
2431 // Create the CALLSEQ_END node.
2432 unsigned NumBytesForCalleeToPush;
2433 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2434 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2435 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2436 // If this is a call to a struct-return function, the callee
2437 // pops the hidden struct pointer, so we have to push it back.
2438 // This is common for Darwin/X86, Linux & Mingw32 targets.
2439 NumBytesForCalleeToPush = 4;
2441 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2443 // Returns a flag for retval copy to use.
2445 Chain = DAG.getCALLSEQ_END(Chain,
2446 DAG.getIntPtrConstant(NumBytes, true),
2447 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2450 InFlag = Chain.getValue(1);
2453 // Handle result values, copying them out of physregs into vregs that we
2455 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2456 Ins, dl, DAG, InVals);
2460 //===----------------------------------------------------------------------===//
2461 // Fast Calling Convention (tail call) implementation
2462 //===----------------------------------------------------------------------===//
2464 // Like std call, callee cleans arguments, convention except that ECX is
2465 // reserved for storing the tail called function address. Only 2 registers are
2466 // free for argument passing (inreg). Tail call optimization is performed
2468 // * tailcallopt is enabled
2469 // * caller/callee are fastcc
2470 // On X86_64 architecture with GOT-style position independent code only local
2471 // (within module) calls are supported at the moment.
2472 // To keep the stack aligned according to platform abi the function
2473 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2474 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2475 // If a tail called function callee has more arguments than the caller the
2476 // caller needs to make sure that there is room to move the RETADDR to. This is
2477 // achieved by reserving an area the size of the argument delta right after the
2478 // original REtADDR, but before the saved framepointer or the spilled registers
2479 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2491 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2492 /// for a 16 byte align requirement.
2494 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2495 SelectionDAG& DAG) const {
2496 MachineFunction &MF = DAG.getMachineFunction();
2497 const TargetMachine &TM = MF.getTarget();
2498 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2499 unsigned StackAlignment = TFI.getStackAlignment();
2500 uint64_t AlignMask = StackAlignment - 1;
2501 int64_t Offset = StackSize;
2502 uint64_t SlotSize = TD->getPointerSize();
2503 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2504 // Number smaller than 12 so just add the difference.
2505 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2507 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2508 Offset = ((~AlignMask) & Offset) + StackAlignment +
2509 (StackAlignment-SlotSize);
2514 /// MatchingStackOffset - Return true if the given stack call argument is
2515 /// already available in the same position (relatively) of the caller's
2516 /// incoming argument stack.
2518 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2519 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2520 const X86InstrInfo *TII) {
2521 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2523 if (Arg.getOpcode() == ISD::CopyFromReg) {
2524 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2525 if (!TargetRegisterInfo::isVirtualRegister(VR))
2527 MachineInstr *Def = MRI->getVRegDef(VR);
2530 if (!Flags.isByVal()) {
2531 if (!TII->isLoadFromStackSlot(Def, FI))
2534 unsigned Opcode = Def->getOpcode();
2535 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2536 Def->getOperand(1).isFI()) {
2537 FI = Def->getOperand(1).getIndex();
2538 Bytes = Flags.getByValSize();
2542 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2543 if (Flags.isByVal())
2544 // ByVal argument is passed in as a pointer but it's now being
2545 // dereferenced. e.g.
2546 // define @foo(%struct.X* %A) {
2547 // tail call @bar(%struct.X* byval %A)
2550 SDValue Ptr = Ld->getBasePtr();
2551 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2554 FI = FINode->getIndex();
2555 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2556 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2557 FI = FINode->getIndex();
2558 Bytes = Flags.getByValSize();
2562 assert(FI != INT_MAX);
2563 if (!MFI->isFixedObjectIndex(FI))
2565 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2568 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2569 /// for tail call optimization. Targets which want to do tail call
2570 /// optimization should implement this function.
2572 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2573 CallingConv::ID CalleeCC,
2575 bool isCalleeStructRet,
2576 bool isCallerStructRet,
2577 const SmallVectorImpl<ISD::OutputArg> &Outs,
2578 const SmallVectorImpl<SDValue> &OutVals,
2579 const SmallVectorImpl<ISD::InputArg> &Ins,
2580 SelectionDAG& DAG) const {
2581 if (!IsTailCallConvention(CalleeCC) &&
2582 CalleeCC != CallingConv::C)
2585 // If -tailcallopt is specified, make fastcc functions tail-callable.
2586 const MachineFunction &MF = DAG.getMachineFunction();
2587 const Function *CallerF = DAG.getMachineFunction().getFunction();
2588 CallingConv::ID CallerCC = CallerF->getCallingConv();
2589 bool CCMatch = CallerCC == CalleeCC;
2591 if (GuaranteedTailCallOpt) {
2592 if (IsTailCallConvention(CalleeCC) && CCMatch)
2597 // Look for obvious safe cases to perform tail call optimization that do not
2598 // require ABI changes. This is what gcc calls sibcall.
2600 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2601 // emit a special epilogue.
2602 if (RegInfo->needsStackRealignment(MF))
2605 // Also avoid sibcall optimization if either caller or callee uses struct
2606 // return semantics.
2607 if (isCalleeStructRet || isCallerStructRet)
2610 // An stdcall caller is expected to clean up its arguments; the callee
2611 // isn't going to do that.
2612 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2615 // Do not sibcall optimize vararg calls unless all arguments are passed via
2617 if (isVarArg && !Outs.empty()) {
2619 // Optimizing for varargs on Win64 is unlikely to be safe without
2620 // additional testing.
2621 if (Subtarget->isTargetWin64())
2624 SmallVector<CCValAssign, 16> ArgLocs;
2625 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2626 getTargetMachine(), ArgLocs, *DAG.getContext());
2628 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2629 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2630 if (!ArgLocs[i].isRegLoc())
2634 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2635 // Therefore if it's not used by the call it is not safe to optimize this into
2637 bool Unused = false;
2638 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2645 SmallVector<CCValAssign, 16> RVLocs;
2646 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2647 getTargetMachine(), RVLocs, *DAG.getContext());
2648 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2649 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2650 CCValAssign &VA = RVLocs[i];
2651 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2656 // If the calling conventions do not match, then we'd better make sure the
2657 // results are returned in the same way as what the caller expects.
2659 SmallVector<CCValAssign, 16> RVLocs1;
2660 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2661 getTargetMachine(), RVLocs1, *DAG.getContext());
2662 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2664 SmallVector<CCValAssign, 16> RVLocs2;
2665 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2666 getTargetMachine(), RVLocs2, *DAG.getContext());
2667 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2669 if (RVLocs1.size() != RVLocs2.size())
2671 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2672 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2674 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2676 if (RVLocs1[i].isRegLoc()) {
2677 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2680 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2686 // If the callee takes no arguments then go on to check the results of the
2688 if (!Outs.empty()) {
2689 // Check if stack adjustment is needed. For now, do not do this if any
2690 // argument is passed on the stack.
2691 SmallVector<CCValAssign, 16> ArgLocs;
2692 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2693 getTargetMachine(), ArgLocs, *DAG.getContext());
2695 // Allocate shadow area for Win64
2696 if (Subtarget->isTargetWin64()) {
2697 CCInfo.AllocateStack(32, 8);
2700 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2701 if (CCInfo.getNextStackOffset()) {
2702 MachineFunction &MF = DAG.getMachineFunction();
2703 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2706 // Check if the arguments are already laid out in the right way as
2707 // the caller's fixed stack objects.
2708 MachineFrameInfo *MFI = MF.getFrameInfo();
2709 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2710 const X86InstrInfo *TII =
2711 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2712 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2713 CCValAssign &VA = ArgLocs[i];
2714 SDValue Arg = OutVals[i];
2715 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2716 if (VA.getLocInfo() == CCValAssign::Indirect)
2718 if (!VA.isRegLoc()) {
2719 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2726 // If the tailcall address may be in a register, then make sure it's
2727 // possible to register allocate for it. In 32-bit, the call address can
2728 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2729 // callee-saved registers are restored. These happen to be the same
2730 // registers used to pass 'inreg' arguments so watch out for those.
2731 if (!Subtarget->is64Bit() &&
2732 !isa<GlobalAddressSDNode>(Callee) &&
2733 !isa<ExternalSymbolSDNode>(Callee)) {
2734 unsigned NumInRegs = 0;
2735 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2736 CCValAssign &VA = ArgLocs[i];
2739 unsigned Reg = VA.getLocReg();
2742 case X86::EAX: case X86::EDX: case X86::ECX:
2743 if (++NumInRegs == 3)
2755 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2756 return X86::createFastISel(funcInfo);
2760 //===----------------------------------------------------------------------===//
2761 // Other Lowering Hooks
2762 //===----------------------------------------------------------------------===//
2764 static bool MayFoldLoad(SDValue Op) {
2765 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2768 static bool MayFoldIntoStore(SDValue Op) {
2769 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2772 static bool isTargetShuffle(unsigned Opcode) {
2774 default: return false;
2775 case X86ISD::PSHUFD:
2776 case X86ISD::PSHUFHW:
2777 case X86ISD::PSHUFLW:
2778 case X86ISD::SHUFPD:
2779 case X86ISD::PALIGN:
2780 case X86ISD::SHUFPS:
2781 case X86ISD::MOVLHPS:
2782 case X86ISD::MOVLHPD:
2783 case X86ISD::MOVHLPS:
2784 case X86ISD::MOVLPS:
2785 case X86ISD::MOVLPD:
2786 case X86ISD::MOVSHDUP:
2787 case X86ISD::MOVSLDUP:
2788 case X86ISD::MOVDDUP:
2791 case X86ISD::UNPCKLPS:
2792 case X86ISD::UNPCKLPD:
2793 case X86ISD::VUNPCKLPSY:
2794 case X86ISD::VUNPCKLPDY:
2795 case X86ISD::PUNPCKLWD:
2796 case X86ISD::PUNPCKLBW:
2797 case X86ISD::PUNPCKLDQ:
2798 case X86ISD::PUNPCKLQDQ:
2799 case X86ISD::UNPCKHPS:
2800 case X86ISD::UNPCKHPD:
2801 case X86ISD::VUNPCKHPSY:
2802 case X86ISD::VUNPCKHPDY:
2803 case X86ISD::PUNPCKHWD:
2804 case X86ISD::PUNPCKHBW:
2805 case X86ISD::PUNPCKHDQ:
2806 case X86ISD::PUNPCKHQDQ:
2807 case X86ISD::VPERMILPS:
2808 case X86ISD::VPERMILPSY:
2809 case X86ISD::VPERMILPD:
2810 case X86ISD::VPERMILPDY:
2811 case X86ISD::VPERM2F128:
2817 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2818 SDValue V1, SelectionDAG &DAG) {
2820 default: llvm_unreachable("Unknown x86 shuffle node");
2821 case X86ISD::MOVSHDUP:
2822 case X86ISD::MOVSLDUP:
2823 case X86ISD::MOVDDUP:
2824 return DAG.getNode(Opc, dl, VT, V1);
2830 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2831 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2833 default: llvm_unreachable("Unknown x86 shuffle node");
2834 case X86ISD::PSHUFD:
2835 case X86ISD::PSHUFHW:
2836 case X86ISD::PSHUFLW:
2837 case X86ISD::VPERMILPS:
2838 case X86ISD::VPERMILPSY:
2839 case X86ISD::VPERMILPD:
2840 case X86ISD::VPERMILPDY:
2841 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2847 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2848 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2850 default: llvm_unreachable("Unknown x86 shuffle node");
2851 case X86ISD::PALIGN:
2852 case X86ISD::SHUFPD:
2853 case X86ISD::SHUFPS:
2854 case X86ISD::VPERM2F128:
2855 return DAG.getNode(Opc, dl, VT, V1, V2,
2856 DAG.getConstant(TargetMask, MVT::i8));
2861 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2862 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2864 default: llvm_unreachable("Unknown x86 shuffle node");
2865 case X86ISD::MOVLHPS:
2866 case X86ISD::MOVLHPD:
2867 case X86ISD::MOVHLPS:
2868 case X86ISD::MOVLPS:
2869 case X86ISD::MOVLPD:
2872 case X86ISD::UNPCKLPS:
2873 case X86ISD::UNPCKLPD:
2874 case X86ISD::VUNPCKLPSY:
2875 case X86ISD::VUNPCKLPDY:
2876 case X86ISD::PUNPCKLWD:
2877 case X86ISD::PUNPCKLBW:
2878 case X86ISD::PUNPCKLDQ:
2879 case X86ISD::PUNPCKLQDQ:
2880 case X86ISD::UNPCKHPS:
2881 case X86ISD::UNPCKHPD:
2882 case X86ISD::VUNPCKHPSY:
2883 case X86ISD::VUNPCKHPDY:
2884 case X86ISD::PUNPCKHWD:
2885 case X86ISD::PUNPCKHBW:
2886 case X86ISD::PUNPCKHDQ:
2887 case X86ISD::PUNPCKHQDQ:
2888 return DAG.getNode(Opc, dl, VT, V1, V2);
2893 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2894 MachineFunction &MF = DAG.getMachineFunction();
2895 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2896 int ReturnAddrIndex = FuncInfo->getRAIndex();
2898 if (ReturnAddrIndex == 0) {
2899 // Set up a frame object for the return address.
2900 uint64_t SlotSize = TD->getPointerSize();
2901 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2903 FuncInfo->setRAIndex(ReturnAddrIndex);
2906 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2910 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2911 bool hasSymbolicDisplacement) {
2912 // Offset should fit into 32 bit immediate field.
2913 if (!isInt<32>(Offset))
2916 // If we don't have a symbolic displacement - we don't have any extra
2918 if (!hasSymbolicDisplacement)
2921 // FIXME: Some tweaks might be needed for medium code model.
2922 if (M != CodeModel::Small && M != CodeModel::Kernel)
2925 // For small code model we assume that latest object is 16MB before end of 31
2926 // bits boundary. We may also accept pretty large negative constants knowing
2927 // that all objects are in the positive half of address space.
2928 if (M == CodeModel::Small && Offset < 16*1024*1024)
2931 // For kernel code model we know that all object resist in the negative half
2932 // of 32bits address space. We may not accept negative offsets, since they may
2933 // be just off and we may accept pretty large positive ones.
2934 if (M == CodeModel::Kernel && Offset > 0)
2940 /// isCalleePop - Determines whether the callee is required to pop its
2941 /// own arguments. Callee pop is necessary to support tail calls.
2942 bool X86::isCalleePop(CallingConv::ID CallingConv,
2943 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2947 switch (CallingConv) {
2950 case CallingConv::X86_StdCall:
2952 case CallingConv::X86_FastCall:
2954 case CallingConv::X86_ThisCall:
2956 case CallingConv::Fast:
2958 case CallingConv::GHC:
2963 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2964 /// specific condition code, returning the condition code and the LHS/RHS of the
2965 /// comparison to make.
2966 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2967 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2969 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2970 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2971 // X > -1 -> X == 0, jump !sign.
2972 RHS = DAG.getConstant(0, RHS.getValueType());
2973 return X86::COND_NS;
2974 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2975 // X < 0 -> X == 0, jump on sign.
2977 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2979 RHS = DAG.getConstant(0, RHS.getValueType());
2980 return X86::COND_LE;
2984 switch (SetCCOpcode) {
2985 default: llvm_unreachable("Invalid integer condition!");
2986 case ISD::SETEQ: return X86::COND_E;
2987 case ISD::SETGT: return X86::COND_G;
2988 case ISD::SETGE: return X86::COND_GE;
2989 case ISD::SETLT: return X86::COND_L;
2990 case ISD::SETLE: return X86::COND_LE;
2991 case ISD::SETNE: return X86::COND_NE;
2992 case ISD::SETULT: return X86::COND_B;
2993 case ISD::SETUGT: return X86::COND_A;
2994 case ISD::SETULE: return X86::COND_BE;
2995 case ISD::SETUGE: return X86::COND_AE;
2999 // First determine if it is required or is profitable to flip the operands.
3001 // If LHS is a foldable load, but RHS is not, flip the condition.
3002 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3003 !ISD::isNON_EXTLoad(RHS.getNode())) {
3004 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3005 std::swap(LHS, RHS);
3008 switch (SetCCOpcode) {
3014 std::swap(LHS, RHS);
3018 // On a floating point condition, the flags are set as follows:
3020 // 0 | 0 | 0 | X > Y
3021 // 0 | 0 | 1 | X < Y
3022 // 1 | 0 | 0 | X == Y
3023 // 1 | 1 | 1 | unordered
3024 switch (SetCCOpcode) {
3025 default: llvm_unreachable("Condcode should be pre-legalized away");
3027 case ISD::SETEQ: return X86::COND_E;
3028 case ISD::SETOLT: // flipped
3030 case ISD::SETGT: return X86::COND_A;
3031 case ISD::SETOLE: // flipped
3033 case ISD::SETGE: return X86::COND_AE;
3034 case ISD::SETUGT: // flipped
3036 case ISD::SETLT: return X86::COND_B;
3037 case ISD::SETUGE: // flipped
3039 case ISD::SETLE: return X86::COND_BE;
3041 case ISD::SETNE: return X86::COND_NE;
3042 case ISD::SETUO: return X86::COND_P;
3043 case ISD::SETO: return X86::COND_NP;
3045 case ISD::SETUNE: return X86::COND_INVALID;
3049 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3050 /// code. Current x86 isa includes the following FP cmov instructions:
3051 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3052 static bool hasFPCMov(unsigned X86CC) {
3068 /// isFPImmLegal - Returns true if the target can instruction select the
3069 /// specified FP immediate natively. If false, the legalizer will
3070 /// materialize the FP immediate as a load from a constant pool.
3071 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3072 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3073 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3079 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3080 /// the specified range (L, H].
3081 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3082 return (Val < 0) || (Val >= Low && Val < Hi);
3085 /// isUndefOrInRange - Return true if every element in Mask, begining
3086 /// from position Pos and ending in Pos+Size, falls within the specified
3087 /// range (L, L+Pos]. or is undef.
3088 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3089 int Pos, int Size, int Low, int Hi) {
3090 for (int i = Pos, e = Pos+Size; i != e; ++i)
3091 if (!isUndefOrInRange(Mask[i], Low, Hi))
3096 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3097 /// specified value.
3098 static bool isUndefOrEqual(int Val, int CmpVal) {
3099 if (Val < 0 || Val == CmpVal)
3104 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3105 /// from position Pos and ending in Pos+Size, falls within the specified
3106 /// sequential range (L, L+Pos]. or is undef.
3107 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3108 int Pos, int Size, int Low) {
3109 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3110 if (!isUndefOrEqual(Mask[i], Low))
3115 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3116 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3117 /// the second operand.
3118 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3119 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3120 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3121 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3122 return (Mask[0] < 2 && Mask[1] < 2);
3126 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3127 SmallVector<int, 8> M;
3129 return ::isPSHUFDMask(M, N->getValueType(0));
3132 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3133 /// is suitable for input to PSHUFHW.
3134 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3135 if (VT != MVT::v8i16)
3138 // Lower quadword copied in order or undef.
3139 for (int i = 0; i != 4; ++i)
3140 if (Mask[i] >= 0 && Mask[i] != i)
3143 // Upper quadword shuffled.
3144 for (int i = 4; i != 8; ++i)
3145 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3151 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3152 SmallVector<int, 8> M;
3154 return ::isPSHUFHWMask(M, N->getValueType(0));
3157 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3158 /// is suitable for input to PSHUFLW.
3159 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3160 if (VT != MVT::v8i16)
3163 // Upper quadword copied in order.
3164 for (int i = 4; i != 8; ++i)
3165 if (Mask[i] >= 0 && Mask[i] != i)
3168 // Lower quadword shuffled.
3169 for (int i = 0; i != 4; ++i)
3176 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3177 SmallVector<int, 8> M;
3179 return ::isPSHUFLWMask(M, N->getValueType(0));
3182 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3183 /// is suitable for input to PALIGNR.
3184 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3185 bool hasSSSE3OrAVX) {
3186 int i, e = VT.getVectorNumElements();
3187 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3190 // Do not handle v2i64 / v2f64 shuffles with palignr.
3191 if (e < 4 || !hasSSSE3OrAVX)
3194 for (i = 0; i != e; ++i)
3198 // All undef, not a palignr.
3202 // Make sure we're shifting in the right direction.
3206 int s = Mask[i] - i;
3208 // Check the rest of the elements to see if they are consecutive.
3209 for (++i; i != e; ++i) {
3211 if (m >= 0 && m != s+i)
3217 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3218 /// specifies a shuffle of elements that is suitable for input to 256-bit
3220 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3221 const X86Subtarget *Subtarget) {
3222 int NumElems = VT.getVectorNumElements();
3224 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3230 // VSHUFPSY divides the resulting vector into 4 chunks.
3231 // The sources are also splitted into 4 chunks, and each destination
3232 // chunk must come from a different source chunk.
3234 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3235 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3237 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3238 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3240 int QuarterSize = NumElems/4;
3241 int HalfSize = QuarterSize*2;
3242 for (int i = 0; i < QuarterSize; ++i)
3243 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3245 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3246 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3249 // The mask of the second half must be the same as the first but with
3250 // the appropriate offsets. This works in the same way as VPERMILPS
3251 // works with masks.
3252 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3253 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3255 int FstHalfIdx = i-HalfSize;
3256 if (Mask[FstHalfIdx] < 0)
3258 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3261 for (int i = QuarterSize*3; i < NumElems; ++i) {
3262 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3264 int FstHalfIdx = i-HalfSize;
3265 if (Mask[FstHalfIdx] < 0)
3267 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3275 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3276 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3277 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3278 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3279 EVT VT = SVOp->getValueType(0);
3280 int NumElems = VT.getVectorNumElements();
3282 assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3283 "Only supports v8i32 and v8f32 types");
3285 int HalfSize = NumElems/2;
3287 for (int i = 0; i != NumElems ; ++i) {
3288 if (SVOp->getMaskElt(i) < 0)
3290 // The mask of the first half must be equal to the second one.
3291 unsigned Shamt = (i%HalfSize)*2;
3292 unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3293 Mask |= Elt << Shamt;
3299 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3300 /// specifies a shuffle of elements that is suitable for input to 256-bit
3301 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3302 /// version and the mask of the second half isn't binded with the first
3304 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3305 const X86Subtarget *Subtarget) {
3306 int NumElems = VT.getVectorNumElements();
3308 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3314 // VSHUFPSY divides the resulting vector into 4 chunks.
3315 // The sources are also splitted into 4 chunks, and each destination
3316 // chunk must come from a different source chunk.
3318 // SRC1 => X3 X2 X1 X0
3319 // SRC2 => Y3 Y2 Y1 Y0
3321 // DST => Y2..Y3, X2..X3, Y1..Y0, X1..X0
3323 int QuarterSize = NumElems/4;
3324 int HalfSize = QuarterSize*2;
3325 for (int i = 0; i < QuarterSize; ++i)
3326 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3328 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3329 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3331 for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3332 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3334 for (int i = QuarterSize*3; i < NumElems; ++i)
3335 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3341 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3342 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3343 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3344 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3345 EVT VT = SVOp->getValueType(0);
3346 int NumElems = VT.getVectorNumElements();
3348 assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3349 "Only supports v4i64 and v4f64 types");
3351 int HalfSize = NumElems/2;
3353 for (int i = 0; i != NumElems ; ++i) {
3354 if (SVOp->getMaskElt(i) < 0)
3356 int Elt = SVOp->getMaskElt(i) % HalfSize;
3363 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3364 /// specifies a shuffle of elements that is suitable for input to 128-bit
3365 /// SHUFPS and SHUFPD.
3366 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3367 int NumElems = VT.getVectorNumElements();
3369 if (VT.getSizeInBits() != 128)
3372 if (NumElems != 2 && NumElems != 4)
3375 int Half = NumElems / 2;
3376 for (int i = 0; i < Half; ++i)
3377 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3379 for (int i = Half; i < NumElems; ++i)
3380 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3386 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3387 SmallVector<int, 8> M;
3389 return ::isSHUFPMask(M, N->getValueType(0));
3392 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3393 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3394 /// half elements to come from vector 1 (which would equal the dest.) and
3395 /// the upper half to come from vector 2.
3396 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3397 int NumElems = VT.getVectorNumElements();
3399 if (NumElems != 2 && NumElems != 4)
3402 int Half = NumElems / 2;
3403 for (int i = 0; i < Half; ++i)
3404 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3406 for (int i = Half; i < NumElems; ++i)
3407 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3412 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3413 SmallVector<int, 8> M;
3415 return isCommutedSHUFPMask(M, N->getValueType(0));
3418 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3419 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3420 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3421 EVT VT = N->getValueType(0);
3422 unsigned NumElems = VT.getVectorNumElements();
3424 if (VT.getSizeInBits() != 128)
3430 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3431 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3432 isUndefOrEqual(N->getMaskElt(1), 7) &&
3433 isUndefOrEqual(N->getMaskElt(2), 2) &&
3434 isUndefOrEqual(N->getMaskElt(3), 3);
3437 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3438 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3440 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3441 EVT VT = N->getValueType(0);
3442 unsigned NumElems = VT.getVectorNumElements();
3444 if (VT.getSizeInBits() != 128)
3450 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3451 isUndefOrEqual(N->getMaskElt(1), 3) &&
3452 isUndefOrEqual(N->getMaskElt(2), 2) &&
3453 isUndefOrEqual(N->getMaskElt(3), 3);
3456 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3457 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3458 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3459 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3461 if (NumElems != 2 && NumElems != 4)
3464 for (unsigned i = 0; i < NumElems/2; ++i)
3465 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3468 for (unsigned i = NumElems/2; i < NumElems; ++i)
3469 if (!isUndefOrEqual(N->getMaskElt(i), i))
3475 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3476 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3477 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3478 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3480 if ((NumElems != 2 && NumElems != 4)
3481 || N->getValueType(0).getSizeInBits() > 128)
3484 for (unsigned i = 0; i < NumElems/2; ++i)
3485 if (!isUndefOrEqual(N->getMaskElt(i), i))
3488 for (unsigned i = 0; i < NumElems/2; ++i)
3489 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3495 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3497 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3498 bool V2IsSplat = false) {
3499 int NumElts = VT.getVectorNumElements();
3501 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3502 "Unsupported vector type for unpckh");
3504 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3507 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3508 // independently on 128-bit lanes.
3509 unsigned NumLanes = VT.getSizeInBits()/128;
3510 unsigned NumLaneElts = NumElts/NumLanes;
3513 unsigned End = NumLaneElts;
3514 for (unsigned s = 0; s < NumLanes; ++s) {
3515 for (unsigned i = Start, j = s * NumLaneElts;
3519 int BitI1 = Mask[i+1];
3520 if (!isUndefOrEqual(BitI, j))
3523 if (!isUndefOrEqual(BitI1, NumElts))
3526 if (!isUndefOrEqual(BitI1, j + NumElts))
3530 // Process the next 128 bits.
3531 Start += NumLaneElts;
3538 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3539 SmallVector<int, 8> M;
3541 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3544 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3545 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3546 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3547 bool V2IsSplat = false) {
3548 int NumElts = VT.getVectorNumElements();
3550 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3551 "Unsupported vector type for unpckh");
3553 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3556 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3557 // independently on 128-bit lanes.
3558 unsigned NumLanes = VT.getSizeInBits()/128;
3559 unsigned NumLaneElts = NumElts/NumLanes;
3562 unsigned End = NumLaneElts;
3563 for (unsigned l = 0; l != NumLanes; ++l) {
3564 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3565 i != End; i += 2, ++j) {
3567 int BitI1 = Mask[i+1];
3568 if (!isUndefOrEqual(BitI, j))
3571 if (isUndefOrEqual(BitI1, NumElts))
3574 if (!isUndefOrEqual(BitI1, j+NumElts))
3578 // Process the next 128 bits.
3579 Start += NumLaneElts;
3585 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3586 SmallVector<int, 8> M;
3588 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3591 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3592 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3594 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3595 int NumElems = VT.getVectorNumElements();
3596 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3599 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3600 // FIXME: Need a better way to get rid of this, there's no latency difference
3601 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3602 // the former later. We should also remove the "_undef" special mask.
3603 if (NumElems == 4 && VT.getSizeInBits() == 256)
3606 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3607 // independently on 128-bit lanes.
3608 unsigned NumLanes = VT.getSizeInBits() / 128;
3609 unsigned NumLaneElts = NumElems / NumLanes;
3611 for (unsigned s = 0; s < NumLanes; ++s) {
3612 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3613 i != NumLaneElts * (s + 1);
3616 int BitI1 = Mask[i+1];
3618 if (!isUndefOrEqual(BitI, j))
3620 if (!isUndefOrEqual(BitI1, j))
3628 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3629 SmallVector<int, 8> M;
3631 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3634 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3635 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3637 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3638 int NumElems = VT.getVectorNumElements();
3639 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3642 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3644 int BitI1 = Mask[i+1];
3645 if (!isUndefOrEqual(BitI, j))
3647 if (!isUndefOrEqual(BitI1, j))
3653 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3654 SmallVector<int, 8> M;
3656 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3659 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3660 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3661 /// MOVSD, and MOVD, i.e. setting the lowest element.
3662 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3663 if (VT.getVectorElementType().getSizeInBits() < 32)
3666 int NumElts = VT.getVectorNumElements();
3668 if (!isUndefOrEqual(Mask[0], NumElts))
3671 for (int i = 1; i < NumElts; ++i)
3672 if (!isUndefOrEqual(Mask[i], i))
3678 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3679 SmallVector<int, 8> M;
3681 return ::isMOVLMask(M, N->getValueType(0));
3684 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3685 /// as permutations between 128-bit chunks or halves. As an example: this
3687 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3688 /// The first half comes from the second half of V1 and the second half from the
3689 /// the second half of V2.
3690 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3691 const X86Subtarget *Subtarget) {
3692 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3695 // The shuffle result is divided into half A and half B. In total the two
3696 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3697 // B must come from C, D, E or F.
3698 int HalfSize = VT.getVectorNumElements()/2;
3699 bool MatchA = false, MatchB = false;
3701 // Check if A comes from one of C, D, E, F.
3702 for (int Half = 0; Half < 4; ++Half) {
3703 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3709 // Check if B comes from one of C, D, E, F.
3710 for (int Half = 0; Half < 4; ++Half) {
3711 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3717 return MatchA && MatchB;
3720 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3721 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3722 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3723 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3724 EVT VT = SVOp->getValueType(0);
3726 int HalfSize = VT.getVectorNumElements()/2;
3728 int FstHalf = 0, SndHalf = 0;
3729 for (int i = 0; i < HalfSize; ++i) {
3730 if (SVOp->getMaskElt(i) > 0) {
3731 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3735 for (int i = HalfSize; i < HalfSize*2; ++i) {
3736 if (SVOp->getMaskElt(i) > 0) {
3737 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3742 return (FstHalf | (SndHalf << 4));
3745 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3746 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3747 /// Note that VPERMIL mask matching is different depending whether theunderlying
3748 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3749 /// to the same elements of the low, but to the higher half of the source.
3750 /// In VPERMILPD the two lanes could be shuffled independently of each other
3751 /// with the same restriction that lanes can't be crossed.
3752 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3753 const X86Subtarget *Subtarget) {
3754 int NumElts = VT.getVectorNumElements();
3755 int NumLanes = VT.getSizeInBits()/128;
3757 if (!Subtarget->hasAVX())
3760 // Match any permutation of 128-bit vector with 64-bit types
3761 if (NumLanes == 1 && NumElts != 2)
3764 // Only match 256-bit with 32 types
3765 if (VT.getSizeInBits() == 256 && NumElts != 4)
3768 // The mask on the high lane is independent of the low. Both can match
3769 // any element in inside its own lane, but can't cross.
3770 int LaneSize = NumElts/NumLanes;
3771 for (int l = 0; l < NumLanes; ++l)
3772 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3773 int LaneStart = l*LaneSize;
3774 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3781 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3782 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3783 /// Note that VPERMIL mask matching is different depending whether theunderlying
3784 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3785 /// to the same elements of the low, but to the higher half of the source.
3786 /// In VPERMILPD the two lanes could be shuffled independently of each other
3787 /// with the same restriction that lanes can't be crossed.
3788 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3789 const X86Subtarget *Subtarget) {
3790 unsigned NumElts = VT.getVectorNumElements();
3791 unsigned NumLanes = VT.getSizeInBits()/128;
3793 if (!Subtarget->hasAVX())
3796 // Match any permutation of 128-bit vector with 32-bit types
3797 if (NumLanes == 1 && NumElts != 4)
3800 // Only match 256-bit with 32 types
3801 if (VT.getSizeInBits() == 256 && NumElts != 8)
3804 // The mask on the high lane should be the same as the low. Actually,
3805 // they can differ if any of the corresponding index in a lane is undef
3806 // and the other stays in range.
3807 int LaneSize = NumElts/NumLanes;
3808 for (int i = 0; i < LaneSize; ++i) {
3809 int HighElt = i+LaneSize;
3810 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3811 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3813 if (!HighValid || !LowValid)
3815 if (Mask[i] < 0 || Mask[HighElt] < 0)
3817 if (Mask[HighElt]-Mask[i] != LaneSize)
3824 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3825 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3826 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3827 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3828 EVT VT = SVOp->getValueType(0);
3830 int NumElts = VT.getVectorNumElements();
3831 int NumLanes = VT.getSizeInBits()/128;
3832 int LaneSize = NumElts/NumLanes;
3834 // Although the mask is equal for both lanes do it twice to get the cases
3835 // where a mask will match because the same mask element is undef on the
3836 // first half but valid on the second. This would get pathological cases
3837 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3839 for (int l = 0; l < NumLanes; ++l) {
3840 for (int i = 0; i < LaneSize; ++i) {
3841 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3844 if (MaskElt >= LaneSize)
3845 MaskElt -= LaneSize;
3846 Mask |= MaskElt << (i*2);
3853 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3854 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3855 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3856 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3857 EVT VT = SVOp->getValueType(0);
3859 int NumElts = VT.getVectorNumElements();
3860 int NumLanes = VT.getSizeInBits()/128;
3863 int LaneSize = NumElts/NumLanes;
3864 for (int l = 0; l < NumLanes; ++l)
3865 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3866 int MaskElt = SVOp->getMaskElt(i);
3869 Mask |= (MaskElt-l*LaneSize) << i;
3875 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3876 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3877 /// element of vector 2 and the other elements to come from vector 1 in order.
3878 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3879 bool V2IsSplat = false, bool V2IsUndef = false) {
3880 int NumOps = VT.getVectorNumElements();
3881 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3884 if (!isUndefOrEqual(Mask[0], 0))
3887 for (int i = 1; i < NumOps; ++i)
3888 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3889 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3890 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3896 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3897 bool V2IsUndef = false) {
3898 SmallVector<int, 8> M;
3900 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3903 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3905 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3906 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3907 const X86Subtarget *Subtarget) {
3908 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3911 // The second vector must be undef
3912 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3915 EVT VT = N->getValueType(0);
3916 unsigned NumElems = VT.getVectorNumElements();
3918 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3919 (VT.getSizeInBits() == 256 && NumElems != 8))
3922 // "i+1" is the value the indexed mask element must have
3923 for (unsigned i = 0; i < NumElems; i += 2)
3924 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3925 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3931 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3932 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3933 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3934 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3935 const X86Subtarget *Subtarget) {
3936 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3939 // The second vector must be undef
3940 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3943 EVT VT = N->getValueType(0);
3944 unsigned NumElems = VT.getVectorNumElements();
3946 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3947 (VT.getSizeInBits() == 256 && NumElems != 8))
3950 // "i" is the value the indexed mask element must have
3951 for (unsigned i = 0; i < NumElems; i += 2)
3952 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3953 !isUndefOrEqual(N->getMaskElt(i+1), i))
3959 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3960 /// specifies a shuffle of elements that is suitable for input to 256-bit
3961 /// version of MOVDDUP.
3962 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3963 const X86Subtarget *Subtarget) {
3964 EVT VT = N->getValueType(0);
3965 int NumElts = VT.getVectorNumElements();
3966 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3968 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3969 !V2IsUndef || NumElts != 4)
3972 for (int i = 0; i != NumElts/2; ++i)
3973 if (!isUndefOrEqual(N->getMaskElt(i), 0))
3975 for (int i = NumElts/2; i != NumElts; ++i)
3976 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3981 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3982 /// specifies a shuffle of elements that is suitable for input to 128-bit
3983 /// version of MOVDDUP.
3984 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3985 EVT VT = N->getValueType(0);
3987 if (VT.getSizeInBits() != 128)
3990 int e = VT.getVectorNumElements() / 2;
3991 for (int i = 0; i < e; ++i)
3992 if (!isUndefOrEqual(N->getMaskElt(i), i))
3994 for (int i = 0; i < e; ++i)
3995 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4000 /// isVEXTRACTF128Index - Return true if the specified
4001 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4002 /// suitable for input to VEXTRACTF128.
4003 bool X86::isVEXTRACTF128Index(SDNode *N) {
4004 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4007 // The index should be aligned on a 128-bit boundary.
4009 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4011 unsigned VL = N->getValueType(0).getVectorNumElements();
4012 unsigned VBits = N->getValueType(0).getSizeInBits();
4013 unsigned ElSize = VBits / VL;
4014 bool Result = (Index * ElSize) % 128 == 0;
4019 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4020 /// operand specifies a subvector insert that is suitable for input to
4022 bool X86::isVINSERTF128Index(SDNode *N) {
4023 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4026 // The index should be aligned on a 128-bit boundary.
4028 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4030 unsigned VL = N->getValueType(0).getVectorNumElements();
4031 unsigned VBits = N->getValueType(0).getSizeInBits();
4032 unsigned ElSize = VBits / VL;
4033 bool Result = (Index * ElSize) % 128 == 0;
4038 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4039 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4040 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4041 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4042 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4044 unsigned Shift = (NumOperands == 4) ? 2 : 1;
4046 for (int i = 0; i < NumOperands; ++i) {
4047 int Val = SVOp->getMaskElt(NumOperands-i-1);
4048 if (Val < 0) Val = 0;
4049 if (Val >= NumOperands) Val -= NumOperands;
4051 if (i != NumOperands - 1)
4057 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4058 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4059 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4060 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4062 // 8 nodes, but we only care about the last 4.
4063 for (unsigned i = 7; i >= 4; --i) {
4064 int Val = SVOp->getMaskElt(i);
4073 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4074 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4075 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4076 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4078 // 8 nodes, but we only care about the first 4.
4079 for (int i = 3; i >= 0; --i) {
4080 int Val = SVOp->getMaskElt(i);
4089 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4090 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4091 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4092 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4093 EVT VVT = N->getValueType(0);
4094 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4098 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4099 Val = SVOp->getMaskElt(i);
4103 assert(Val - i > 0 && "PALIGNR imm should be positive");
4104 return (Val - i) * EltSize;
4107 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4108 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4110 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4111 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4112 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4115 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4117 EVT VecVT = N->getOperand(0).getValueType();
4118 EVT ElVT = VecVT.getVectorElementType();
4120 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4121 return Index / NumElemsPerChunk;
4124 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4125 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4127 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4128 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4129 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4132 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4134 EVT VecVT = N->getValueType(0);
4135 EVT ElVT = VecVT.getVectorElementType();
4137 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4138 return Index / NumElemsPerChunk;
4141 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4143 bool X86::isZeroNode(SDValue Elt) {
4144 return ((isa<ConstantSDNode>(Elt) &&
4145 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4146 (isa<ConstantFPSDNode>(Elt) &&
4147 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4150 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4151 /// their permute mask.
4152 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4153 SelectionDAG &DAG) {
4154 EVT VT = SVOp->getValueType(0);
4155 unsigned NumElems = VT.getVectorNumElements();
4156 SmallVector<int, 8> MaskVec;
4158 for (unsigned i = 0; i != NumElems; ++i) {
4159 int idx = SVOp->getMaskElt(i);
4161 MaskVec.push_back(idx);
4162 else if (idx < (int)NumElems)
4163 MaskVec.push_back(idx + NumElems);
4165 MaskVec.push_back(idx - NumElems);
4167 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4168 SVOp->getOperand(0), &MaskVec[0]);
4171 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4172 /// the two vector operands have swapped position.
4173 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4174 unsigned NumElems = VT.getVectorNumElements();
4175 for (unsigned i = 0; i != NumElems; ++i) {
4179 else if (idx < (int)NumElems)
4180 Mask[i] = idx + NumElems;
4182 Mask[i] = idx - NumElems;
4186 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4187 /// match movhlps. The lower half elements should come from upper half of
4188 /// V1 (and in order), and the upper half elements should come from the upper
4189 /// half of V2 (and in order).
4190 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4191 EVT VT = Op->getValueType(0);
4192 if (VT.getSizeInBits() != 128)
4194 if (VT.getVectorNumElements() != 4)
4196 for (unsigned i = 0, e = 2; i != e; ++i)
4197 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4199 for (unsigned i = 2; i != 4; ++i)
4200 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4205 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4206 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4208 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4209 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4211 N = N->getOperand(0).getNode();
4212 if (!ISD::isNON_EXTLoad(N))
4215 *LD = cast<LoadSDNode>(N);
4219 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4220 /// match movlp{s|d}. The lower half elements should come from lower half of
4221 /// V1 (and in order), and the upper half elements should come from the upper
4222 /// half of V2 (and in order). And since V1 will become the source of the
4223 /// MOVLP, it must be either a vector load or a scalar load to vector.
4224 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4225 ShuffleVectorSDNode *Op) {
4226 EVT VT = Op->getValueType(0);
4227 if (VT.getSizeInBits() != 128)
4230 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4232 // Is V2 is a vector load, don't do this transformation. We will try to use
4233 // load folding shufps op.
4234 if (ISD::isNON_EXTLoad(V2))
4237 unsigned NumElems = VT.getVectorNumElements();
4239 if (NumElems != 2 && NumElems != 4)
4241 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4242 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4244 for (unsigned i = NumElems/2; i != NumElems; ++i)
4245 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4250 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4252 static bool isSplatVector(SDNode *N) {
4253 if (N->getOpcode() != ISD::BUILD_VECTOR)
4256 SDValue SplatValue = N->getOperand(0);
4257 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4258 if (N->getOperand(i) != SplatValue)
4263 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4264 /// to an zero vector.
4265 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4266 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4267 SDValue V1 = N->getOperand(0);
4268 SDValue V2 = N->getOperand(1);
4269 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4270 for (unsigned i = 0; i != NumElems; ++i) {
4271 int Idx = N->getMaskElt(i);
4272 if (Idx >= (int)NumElems) {
4273 unsigned Opc = V2.getOpcode();
4274 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4276 if (Opc != ISD::BUILD_VECTOR ||
4277 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4279 } else if (Idx >= 0) {
4280 unsigned Opc = V1.getOpcode();
4281 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4283 if (Opc != ISD::BUILD_VECTOR ||
4284 !X86::isZeroNode(V1.getOperand(Idx)))
4291 /// getZeroVector - Returns a vector of specified type with all zero elements.
4293 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4295 assert(VT.isVector() && "Expected a vector type");
4297 // Always build SSE zero vectors as <4 x i32> bitcasted
4298 // to their dest type. This ensures they get CSE'd.
4300 if (VT.getSizeInBits() == 128) { // SSE
4301 if (HasXMMInt) { // SSE2
4302 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4303 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4305 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4306 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4308 } else if (VT.getSizeInBits() == 256) { // AVX
4309 // 256-bit logic and arithmetic instructions in AVX are
4310 // all floating-point, no support for integer ops. Default
4311 // to emitting fp zeroed vectors then.
4312 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4313 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4314 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4316 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4319 /// getOnesVector - Returns a vector of specified type with all bits set.
4320 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4321 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4322 /// original type, ensuring they get CSE'd.
4323 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4324 assert(VT.isVector() && "Expected a vector type");
4325 assert((VT.is128BitVector() || VT.is256BitVector())
4326 && "Expected a 128-bit or 256-bit vector type");
4328 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4329 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4330 Cst, Cst, Cst, Cst);
4332 if (VT.is256BitVector()) {
4333 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4334 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4335 Vec = Insert128BitVector(InsV, Vec,
4336 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4339 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4342 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4343 /// that point to V2 points to its first element.
4344 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4345 EVT VT = SVOp->getValueType(0);
4346 unsigned NumElems = VT.getVectorNumElements();
4348 bool Changed = false;
4349 SmallVector<int, 8> MaskVec;
4350 SVOp->getMask(MaskVec);
4352 for (unsigned i = 0; i != NumElems; ++i) {
4353 if (MaskVec[i] > (int)NumElems) {
4354 MaskVec[i] = NumElems;
4359 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4360 SVOp->getOperand(1), &MaskVec[0]);
4361 return SDValue(SVOp, 0);
4364 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4365 /// operation of specified width.
4366 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4368 unsigned NumElems = VT.getVectorNumElements();
4369 SmallVector<int, 8> Mask;
4370 Mask.push_back(NumElems);
4371 for (unsigned i = 1; i != NumElems; ++i)
4373 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4376 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4377 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4379 unsigned NumElems = VT.getVectorNumElements();
4380 SmallVector<int, 8> Mask;
4381 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4383 Mask.push_back(i + NumElems);
4385 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4388 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4389 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4391 unsigned NumElems = VT.getVectorNumElements();
4392 unsigned Half = NumElems/2;
4393 SmallVector<int, 8> Mask;
4394 for (unsigned i = 0; i != Half; ++i) {
4395 Mask.push_back(i + Half);
4396 Mask.push_back(i + NumElems + Half);
4398 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4401 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4402 // a generic shuffle instruction because the target has no such instructions.
4403 // Generate shuffles which repeat i16 and i8 several times until they can be
4404 // represented by v4f32 and then be manipulated by target suported shuffles.
4405 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4406 EVT VT = V.getValueType();
4407 int NumElems = VT.getVectorNumElements();
4408 DebugLoc dl = V.getDebugLoc();
4410 while (NumElems > 4) {
4411 if (EltNo < NumElems/2) {
4412 V = getUnpackl(DAG, dl, VT, V, V);
4414 V = getUnpackh(DAG, dl, VT, V, V);
4415 EltNo -= NumElems/2;
4422 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4423 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4424 EVT VT = V.getValueType();
4425 DebugLoc dl = V.getDebugLoc();
4426 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4427 && "Vector size not supported");
4429 if (VT.getSizeInBits() == 128) {
4430 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4431 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4432 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4435 // To use VPERMILPS to splat scalars, the second half of indicies must
4436 // refer to the higher part, which is a duplication of the lower one,
4437 // because VPERMILPS can only handle in-lane permutations.
4438 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4439 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4441 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4442 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4446 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4449 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4450 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4451 EVT SrcVT = SV->getValueType(0);
4452 SDValue V1 = SV->getOperand(0);
4453 DebugLoc dl = SV->getDebugLoc();
4455 int EltNo = SV->getSplatIndex();
4456 int NumElems = SrcVT.getVectorNumElements();
4457 unsigned Size = SrcVT.getSizeInBits();
4459 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4460 "Unknown how to promote splat for type");
4462 // Extract the 128-bit part containing the splat element and update
4463 // the splat element index when it refers to the higher register.
4465 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4466 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4468 EltNo -= NumElems/2;
4471 // All i16 and i8 vector types can't be used directly by a generic shuffle
4472 // instruction because the target has no such instruction. Generate shuffles
4473 // which repeat i16 and i8 several times until they fit in i32, and then can
4474 // be manipulated by target suported shuffles.
4475 EVT EltVT = SrcVT.getVectorElementType();
4476 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4477 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4479 // Recreate the 256-bit vector and place the same 128-bit vector
4480 // into the low and high part. This is necessary because we want
4481 // to use VPERM* to shuffle the vectors
4483 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4484 DAG.getConstant(0, MVT::i32), DAG, dl);
4485 V1 = Insert128BitVector(InsV, V1,
4486 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4489 return getLegalSplat(DAG, V1, EltNo);
4492 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4493 /// vector of zero or undef vector. This produces a shuffle where the low
4494 /// element of V2 is swizzled into the zero/undef vector, landing at element
4495 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4496 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4497 bool isZero, bool HasXMMInt,
4498 SelectionDAG &DAG) {
4499 EVT VT = V2.getValueType();
4501 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4502 unsigned NumElems = VT.getVectorNumElements();
4503 SmallVector<int, 16> MaskVec;
4504 for (unsigned i = 0; i != NumElems; ++i)
4505 // If this is the insertion idx, put the low elt of V2 here.
4506 MaskVec.push_back(i == Idx ? NumElems : i);
4507 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4510 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4511 /// element of the result of the vector shuffle.
4512 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4515 return SDValue(); // Limit search depth.
4517 SDValue V = SDValue(N, 0);
4518 EVT VT = V.getValueType();
4519 unsigned Opcode = V.getOpcode();
4521 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4522 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4523 Index = SV->getMaskElt(Index);
4526 return DAG.getUNDEF(VT.getVectorElementType());
4528 int NumElems = VT.getVectorNumElements();
4529 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4530 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4533 // Recurse into target specific vector shuffles to find scalars.
4534 if (isTargetShuffle(Opcode)) {
4535 int NumElems = VT.getVectorNumElements();
4536 SmallVector<unsigned, 16> ShuffleMask;
4540 case X86ISD::SHUFPS:
4541 case X86ISD::SHUFPD:
4542 ImmN = N->getOperand(N->getNumOperands()-1);
4543 DecodeSHUFPSMask(NumElems,
4544 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4547 case X86ISD::PUNPCKHBW:
4548 case X86ISD::PUNPCKHWD:
4549 case X86ISD::PUNPCKHDQ:
4550 case X86ISD::PUNPCKHQDQ:
4551 DecodePUNPCKHMask(NumElems, ShuffleMask);
4553 case X86ISD::UNPCKHPS:
4554 case X86ISD::UNPCKHPD:
4555 case X86ISD::VUNPCKHPSY:
4556 case X86ISD::VUNPCKHPDY:
4557 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4559 case X86ISD::PUNPCKLBW:
4560 case X86ISD::PUNPCKLWD:
4561 case X86ISD::PUNPCKLDQ:
4562 case X86ISD::PUNPCKLQDQ:
4563 DecodePUNPCKLMask(VT, ShuffleMask);
4565 case X86ISD::UNPCKLPS:
4566 case X86ISD::UNPCKLPD:
4567 case X86ISD::VUNPCKLPSY:
4568 case X86ISD::VUNPCKLPDY:
4569 DecodeUNPCKLPMask(VT, ShuffleMask);
4571 case X86ISD::MOVHLPS:
4572 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4574 case X86ISD::MOVLHPS:
4575 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4577 case X86ISD::PSHUFD:
4578 ImmN = N->getOperand(N->getNumOperands()-1);
4579 DecodePSHUFMask(NumElems,
4580 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4583 case X86ISD::PSHUFHW:
4584 ImmN = N->getOperand(N->getNumOperands()-1);
4585 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4588 case X86ISD::PSHUFLW:
4589 ImmN = N->getOperand(N->getNumOperands()-1);
4590 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4594 case X86ISD::MOVSD: {
4595 // The index 0 always comes from the first element of the second source,
4596 // this is why MOVSS and MOVSD are used in the first place. The other
4597 // elements come from the other positions of the first source vector.
4598 unsigned OpNum = (Index == 0) ? 1 : 0;
4599 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4602 case X86ISD::VPERMILPS:
4603 ImmN = N->getOperand(N->getNumOperands()-1);
4604 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4607 case X86ISD::VPERMILPSY:
4608 ImmN = N->getOperand(N->getNumOperands()-1);
4609 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4612 case X86ISD::VPERMILPD:
4613 ImmN = N->getOperand(N->getNumOperands()-1);
4614 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4617 case X86ISD::VPERMILPDY:
4618 ImmN = N->getOperand(N->getNumOperands()-1);
4619 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4622 case X86ISD::VPERM2F128:
4623 ImmN = N->getOperand(N->getNumOperands()-1);
4624 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4627 case X86ISD::MOVDDUP:
4628 case X86ISD::MOVLHPD:
4629 case X86ISD::MOVLPD:
4630 case X86ISD::MOVLPS:
4631 case X86ISD::MOVSHDUP:
4632 case X86ISD::MOVSLDUP:
4633 case X86ISD::PALIGN:
4634 return SDValue(); // Not yet implemented.
4636 assert(0 && "unknown target shuffle node");
4640 Index = ShuffleMask[Index];
4642 return DAG.getUNDEF(VT.getVectorElementType());
4644 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4645 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4649 // Actual nodes that may contain scalar elements
4650 if (Opcode == ISD::BITCAST) {
4651 V = V.getOperand(0);
4652 EVT SrcVT = V.getValueType();
4653 unsigned NumElems = VT.getVectorNumElements();
4655 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4659 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4660 return (Index == 0) ? V.getOperand(0)
4661 : DAG.getUNDEF(VT.getVectorElementType());
4663 if (V.getOpcode() == ISD::BUILD_VECTOR)
4664 return V.getOperand(Index);
4669 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4670 /// shuffle operation which come from a consecutively from a zero. The
4671 /// search can start in two different directions, from left or right.
4673 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4674 bool ZerosFromLeft, SelectionDAG &DAG) {
4677 while (i < NumElems) {
4678 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4679 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4680 if (!(Elt.getNode() &&
4681 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4689 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4690 /// MaskE correspond consecutively to elements from one of the vector operands,
4691 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4693 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4694 int OpIdx, int NumElems, unsigned &OpNum) {
4695 bool SeenV1 = false;
4696 bool SeenV2 = false;
4698 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4699 int Idx = SVOp->getMaskElt(i);
4700 // Ignore undef indicies
4709 // Only accept consecutive elements from the same vector
4710 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4714 OpNum = SeenV1 ? 0 : 1;
4718 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4719 /// logical left shift of a vector.
4720 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4721 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4722 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4723 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4724 false /* check zeros from right */, DAG);
4730 // Considering the elements in the mask that are not consecutive zeros,
4731 // check if they consecutively come from only one of the source vectors.
4733 // V1 = {X, A, B, C} 0
4735 // vector_shuffle V1, V2 <1, 2, 3, X>
4737 if (!isShuffleMaskConsecutive(SVOp,
4738 0, // Mask Start Index
4739 NumElems-NumZeros-1, // Mask End Index
4740 NumZeros, // Where to start looking in the src vector
4741 NumElems, // Number of elements in vector
4742 OpSrc)) // Which source operand ?
4747 ShVal = SVOp->getOperand(OpSrc);
4751 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4752 /// logical left shift of a vector.
4753 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4754 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4755 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4756 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4757 true /* check zeros from left */, DAG);
4763 // Considering the elements in the mask that are not consecutive zeros,
4764 // check if they consecutively come from only one of the source vectors.
4766 // 0 { A, B, X, X } = V2
4768 // vector_shuffle V1, V2 <X, X, 4, 5>
4770 if (!isShuffleMaskConsecutive(SVOp,
4771 NumZeros, // Mask Start Index
4772 NumElems-1, // Mask End Index
4773 0, // Where to start looking in the src vector
4774 NumElems, // Number of elements in vector
4775 OpSrc)) // Which source operand ?
4780 ShVal = SVOp->getOperand(OpSrc);
4784 /// isVectorShift - Returns true if the shuffle can be implemented as a
4785 /// logical left or right shift of a vector.
4786 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4787 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4788 // Although the logic below support any bitwidth size, there are no
4789 // shift instructions which handle more than 128-bit vectors.
4790 if (SVOp->getValueType(0).getSizeInBits() > 128)
4793 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4794 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4800 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4802 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4803 unsigned NumNonZero, unsigned NumZero,
4805 const TargetLowering &TLI) {
4809 DebugLoc dl = Op.getDebugLoc();
4812 for (unsigned i = 0; i < 16; ++i) {
4813 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4814 if (ThisIsNonZero && First) {
4816 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4818 V = DAG.getUNDEF(MVT::v8i16);
4823 SDValue ThisElt(0, 0), LastElt(0, 0);
4824 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4825 if (LastIsNonZero) {
4826 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4827 MVT::i16, Op.getOperand(i-1));
4829 if (ThisIsNonZero) {
4830 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4831 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4832 ThisElt, DAG.getConstant(8, MVT::i8));
4834 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4838 if (ThisElt.getNode())
4839 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4840 DAG.getIntPtrConstant(i/2));
4844 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4847 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4849 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4850 unsigned NumNonZero, unsigned NumZero,
4852 const TargetLowering &TLI) {
4856 DebugLoc dl = Op.getDebugLoc();
4859 for (unsigned i = 0; i < 8; ++i) {
4860 bool isNonZero = (NonZeros & (1 << i)) != 0;
4864 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4866 V = DAG.getUNDEF(MVT::v8i16);
4869 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4870 MVT::v8i16, V, Op.getOperand(i),
4871 DAG.getIntPtrConstant(i));
4878 /// getVShift - Return a vector logical shift node.
4880 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4881 unsigned NumBits, SelectionDAG &DAG,
4882 const TargetLowering &TLI, DebugLoc dl) {
4883 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4884 EVT ShVT = MVT::v2i64;
4885 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4886 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4887 return DAG.getNode(ISD::BITCAST, dl, VT,
4888 DAG.getNode(Opc, dl, ShVT, SrcOp,
4889 DAG.getConstant(NumBits,
4890 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4894 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4895 SelectionDAG &DAG) const {
4897 // Check if the scalar load can be widened into a vector load. And if
4898 // the address is "base + cst" see if the cst can be "absorbed" into
4899 // the shuffle mask.
4900 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4901 SDValue Ptr = LD->getBasePtr();
4902 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4904 EVT PVT = LD->getValueType(0);
4905 if (PVT != MVT::i32 && PVT != MVT::f32)
4910 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4911 FI = FINode->getIndex();
4913 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4914 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4915 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4916 Offset = Ptr.getConstantOperandVal(1);
4917 Ptr = Ptr.getOperand(0);
4922 // FIXME: 256-bit vector instructions don't require a strict alignment,
4923 // improve this code to support it better.
4924 unsigned RequiredAlign = VT.getSizeInBits()/8;
4925 SDValue Chain = LD->getChain();
4926 // Make sure the stack object alignment is at least 16 or 32.
4927 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4928 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4929 if (MFI->isFixedObjectIndex(FI)) {
4930 // Can't change the alignment. FIXME: It's possible to compute
4931 // the exact stack offset and reference FI + adjust offset instead.
4932 // If someone *really* cares about this. That's the way to implement it.
4935 MFI->setObjectAlignment(FI, RequiredAlign);
4939 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4940 // Ptr + (Offset & ~15).
4943 if ((Offset % RequiredAlign) & 3)
4945 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4947 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4948 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4950 int EltNo = (Offset - StartOffset) >> 2;
4951 int NumElems = VT.getVectorNumElements();
4953 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4954 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4955 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4956 LD->getPointerInfo().getWithOffset(StartOffset),
4959 // Canonicalize it to a v4i32 or v8i32 shuffle.
4960 SmallVector<int, 8> Mask;
4961 for (int i = 0; i < NumElems; ++i)
4962 Mask.push_back(EltNo);
4964 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4965 return DAG.getNode(ISD::BITCAST, dl, NVT,
4966 DAG.getVectorShuffle(CanonVT, dl, V1,
4967 DAG.getUNDEF(CanonVT),&Mask[0]));
4973 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4974 /// vector of type 'VT', see if the elements can be replaced by a single large
4975 /// load which has the same value as a build_vector whose operands are 'elts'.
4977 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4979 /// FIXME: we'd also like to handle the case where the last elements are zero
4980 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4981 /// There's even a handy isZeroNode for that purpose.
4982 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4983 DebugLoc &DL, SelectionDAG &DAG) {
4984 EVT EltVT = VT.getVectorElementType();
4985 unsigned NumElems = Elts.size();
4987 LoadSDNode *LDBase = NULL;
4988 unsigned LastLoadedElt = -1U;
4990 // For each element in the initializer, see if we've found a load or an undef.
4991 // If we don't find an initial load element, or later load elements are
4992 // non-consecutive, bail out.
4993 for (unsigned i = 0; i < NumElems; ++i) {
4994 SDValue Elt = Elts[i];
4996 if (!Elt.getNode() ||
4997 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5000 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5002 LDBase = cast<LoadSDNode>(Elt.getNode());
5006 if (Elt.getOpcode() == ISD::UNDEF)
5009 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5010 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5015 // If we have found an entire vector of loads and undefs, then return a large
5016 // load of the entire vector width starting at the base pointer. If we found
5017 // consecutive loads for the low half, generate a vzext_load node.
5018 if (LastLoadedElt == NumElems - 1) {
5019 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5020 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5021 LDBase->getPointerInfo(),
5022 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5023 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5024 LDBase->getPointerInfo(),
5025 LDBase->isVolatile(), LDBase->isNonTemporal(),
5026 LDBase->getAlignment());
5027 } else if (NumElems == 4 && LastLoadedElt == 1 &&
5028 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5029 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5030 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5032 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5033 LDBase->getPointerInfo(),
5034 LDBase->getAlignment(),
5035 false/*isVolatile*/, true/*ReadMem*/,
5037 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5043 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5044 DebugLoc dl = Op.getDebugLoc();
5046 EVT VT = Op.getValueType();
5047 EVT ExtVT = VT.getVectorElementType();
5048 unsigned NumElems = Op.getNumOperands();
5050 // Vectors containing all zeros can be matched by pxor and xorps later
5051 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5052 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5053 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5054 if (Op.getValueType() == MVT::v4i32 ||
5055 Op.getValueType() == MVT::v8i32)
5058 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5061 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5062 // vectors or broken into v4i32 operations on 256-bit vectors.
5063 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5064 if (Op.getValueType() == MVT::v4i32)
5067 return getOnesVector(Op.getValueType(), DAG, dl);
5070 unsigned EVTBits = ExtVT.getSizeInBits();
5072 unsigned NumZero = 0;
5073 unsigned NumNonZero = 0;
5074 unsigned NonZeros = 0;
5075 bool IsAllConstants = true;
5076 SmallSet<SDValue, 8> Values;
5077 for (unsigned i = 0; i < NumElems; ++i) {
5078 SDValue Elt = Op.getOperand(i);
5079 if (Elt.getOpcode() == ISD::UNDEF)
5082 if (Elt.getOpcode() != ISD::Constant &&
5083 Elt.getOpcode() != ISD::ConstantFP)
5084 IsAllConstants = false;
5085 if (X86::isZeroNode(Elt))
5088 NonZeros |= (1 << i);
5093 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5094 if (NumNonZero == 0)
5095 return DAG.getUNDEF(VT);
5097 // Special case for single non-zero, non-undef, element.
5098 if (NumNonZero == 1) {
5099 unsigned Idx = CountTrailingZeros_32(NonZeros);
5100 SDValue Item = Op.getOperand(Idx);
5102 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5103 // the value are obviously zero, truncate the value to i32 and do the
5104 // insertion that way. Only do this if the value is non-constant or if the
5105 // value is a constant being inserted into element 0. It is cheaper to do
5106 // a constant pool load than it is to do a movd + shuffle.
5107 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5108 (!IsAllConstants || Idx == 0)) {
5109 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5111 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5112 EVT VecVT = MVT::v4i32;
5113 unsigned VecElts = 4;
5115 // Truncate the value (which may itself be a constant) to i32, and
5116 // convert it to a vector with movd (S2V+shuffle to zero extend).
5117 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5118 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5119 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5120 Subtarget->hasXMMInt(), DAG);
5122 // Now we have our 32-bit value zero extended in the low element of
5123 // a vector. If Idx != 0, swizzle it into place.
5125 SmallVector<int, 4> Mask;
5126 Mask.push_back(Idx);
5127 for (unsigned i = 1; i != VecElts; ++i)
5129 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5130 DAG.getUNDEF(Item.getValueType()),
5133 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5137 // If we have a constant or non-constant insertion into the low element of
5138 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5139 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5140 // depending on what the source datatype is.
5143 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5144 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5145 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5146 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5147 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5148 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5150 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5151 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5152 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5153 EVT MiddleVT = MVT::v4i32;
5154 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5155 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5156 Subtarget->hasXMMInt(), DAG);
5157 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5161 // Is it a vector logical left shift?
5162 if (NumElems == 2 && Idx == 1 &&
5163 X86::isZeroNode(Op.getOperand(0)) &&
5164 !X86::isZeroNode(Op.getOperand(1))) {
5165 unsigned NumBits = VT.getSizeInBits();
5166 return getVShift(true, VT,
5167 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5168 VT, Op.getOperand(1)),
5169 NumBits/2, DAG, *this, dl);
5172 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5175 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5176 // is a non-constant being inserted into an element other than the low one,
5177 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5178 // movd/movss) to move this into the low element, then shuffle it into
5180 if (EVTBits == 32) {
5181 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5183 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5184 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5185 Subtarget->hasXMMInt(), DAG);
5186 SmallVector<int, 8> MaskVec;
5187 for (unsigned i = 0; i < NumElems; i++)
5188 MaskVec.push_back(i == Idx ? 0 : 1);
5189 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5193 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5194 if (Values.size() == 1) {
5195 if (EVTBits == 32) {
5196 // Instead of a shuffle like this:
5197 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5198 // Check if it's possible to issue this instead.
5199 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5200 unsigned Idx = CountTrailingZeros_32(NonZeros);
5201 SDValue Item = Op.getOperand(Idx);
5202 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5203 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5208 // A vector full of immediates; various special cases are already
5209 // handled, so this is best done with a single constant-pool load.
5213 // For AVX-length vectors, build the individual 128-bit pieces and use
5214 // shuffles to put them in place.
5215 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5216 SmallVector<SDValue, 32> V;
5217 for (unsigned i = 0; i < NumElems; ++i)
5218 V.push_back(Op.getOperand(i));
5220 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5222 // Build both the lower and upper subvector.
5223 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5224 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5227 // Recreate the wider vector with the lower and upper part.
5228 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5229 DAG.getConstant(0, MVT::i32), DAG, dl);
5230 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5234 // Let legalizer expand 2-wide build_vectors.
5235 if (EVTBits == 64) {
5236 if (NumNonZero == 1) {
5237 // One half is zero or undef.
5238 unsigned Idx = CountTrailingZeros_32(NonZeros);
5239 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5240 Op.getOperand(Idx));
5241 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5242 Subtarget->hasXMMInt(), DAG);
5247 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5248 if (EVTBits == 8 && NumElems == 16) {
5249 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5251 if (V.getNode()) return V;
5254 if (EVTBits == 16 && NumElems == 8) {
5255 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5257 if (V.getNode()) return V;
5260 // If element VT is == 32 bits, turn it into a number of shuffles.
5261 SmallVector<SDValue, 8> V;
5263 if (NumElems == 4 && NumZero > 0) {
5264 for (unsigned i = 0; i < 4; ++i) {
5265 bool isZero = !(NonZeros & (1 << i));
5267 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5269 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5272 for (unsigned i = 0; i < 2; ++i) {
5273 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5276 V[i] = V[i*2]; // Must be a zero vector.
5279 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5282 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5285 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5290 SmallVector<int, 8> MaskVec;
5291 bool Reverse = (NonZeros & 0x3) == 2;
5292 for (unsigned i = 0; i < 2; ++i)
5293 MaskVec.push_back(Reverse ? 1-i : i);
5294 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5295 for (unsigned i = 0; i < 2; ++i)
5296 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5297 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5300 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5301 // Check for a build vector of consecutive loads.
5302 for (unsigned i = 0; i < NumElems; ++i)
5303 V[i] = Op.getOperand(i);
5305 // Check for elements which are consecutive loads.
5306 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5310 // For SSE 4.1, use insertps to put the high elements into the low element.
5311 if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5313 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5314 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5316 Result = DAG.getUNDEF(VT);
5318 for (unsigned i = 1; i < NumElems; ++i) {
5319 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5320 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5321 Op.getOperand(i), DAG.getIntPtrConstant(i));
5326 // Otherwise, expand into a number of unpckl*, start by extending each of
5327 // our (non-undef) elements to the full vector width with the element in the
5328 // bottom slot of the vector (which generates no code for SSE).
5329 for (unsigned i = 0; i < NumElems; ++i) {
5330 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5331 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5333 V[i] = DAG.getUNDEF(VT);
5336 // Next, we iteratively mix elements, e.g. for v4f32:
5337 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5338 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5339 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5340 unsigned EltStride = NumElems >> 1;
5341 while (EltStride != 0) {
5342 for (unsigned i = 0; i < EltStride; ++i) {
5343 // If V[i+EltStride] is undef and this is the first round of mixing,
5344 // then it is safe to just drop this shuffle: V[i] is already in the
5345 // right place, the one element (since it's the first round) being
5346 // inserted as undef can be dropped. This isn't safe for successive
5347 // rounds because they will permute elements within both vectors.
5348 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5349 EltStride == NumElems/2)
5352 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5361 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5362 // them in a MMX register. This is better than doing a stack convert.
5363 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5364 DebugLoc dl = Op.getDebugLoc();
5365 EVT ResVT = Op.getValueType();
5367 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5368 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5370 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5371 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5372 InVec = Op.getOperand(1);
5373 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5374 unsigned NumElts = ResVT.getVectorNumElements();
5375 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5376 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5377 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5379 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5380 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5381 Mask[0] = 0; Mask[1] = 2;
5382 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5384 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5387 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5388 // to create 256-bit vectors from two other 128-bit ones.
5389 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5390 DebugLoc dl = Op.getDebugLoc();
5391 EVT ResVT = Op.getValueType();
5393 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5395 SDValue V1 = Op.getOperand(0);
5396 SDValue V2 = Op.getOperand(1);
5397 unsigned NumElems = ResVT.getVectorNumElements();
5399 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5400 DAG.getConstant(0, MVT::i32), DAG, dl);
5401 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5406 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5407 EVT ResVT = Op.getValueType();
5409 assert(Op.getNumOperands() == 2);
5410 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5411 "Unsupported CONCAT_VECTORS for value type");
5413 // We support concatenate two MMX registers and place them in a MMX register.
5414 // This is better than doing a stack convert.
5415 if (ResVT.is128BitVector())
5416 return LowerMMXCONCAT_VECTORS(Op, DAG);
5418 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5419 // from two other 128-bit ones.
5420 return LowerAVXCONCAT_VECTORS(Op, DAG);
5423 // v8i16 shuffles - Prefer shuffles in the following order:
5424 // 1. [all] pshuflw, pshufhw, optional move
5425 // 2. [ssse3] 1 x pshufb
5426 // 3. [ssse3] 2 x pshufb + 1 x por
5427 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5429 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5430 SelectionDAG &DAG) const {
5431 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5432 SDValue V1 = SVOp->getOperand(0);
5433 SDValue V2 = SVOp->getOperand(1);
5434 DebugLoc dl = SVOp->getDebugLoc();
5435 SmallVector<int, 8> MaskVals;
5437 // Determine if more than 1 of the words in each of the low and high quadwords
5438 // of the result come from the same quadword of one of the two inputs. Undef
5439 // mask values count as coming from any quadword, for better codegen.
5440 SmallVector<unsigned, 4> LoQuad(4);
5441 SmallVector<unsigned, 4> HiQuad(4);
5442 BitVector InputQuads(4);
5443 for (unsigned i = 0; i < 8; ++i) {
5444 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5445 int EltIdx = SVOp->getMaskElt(i);
5446 MaskVals.push_back(EltIdx);
5455 InputQuads.set(EltIdx / 4);
5458 int BestLoQuad = -1;
5459 unsigned MaxQuad = 1;
5460 for (unsigned i = 0; i < 4; ++i) {
5461 if (LoQuad[i] > MaxQuad) {
5463 MaxQuad = LoQuad[i];
5467 int BestHiQuad = -1;
5469 for (unsigned i = 0; i < 4; ++i) {
5470 if (HiQuad[i] > MaxQuad) {
5472 MaxQuad = HiQuad[i];
5476 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5477 // of the two input vectors, shuffle them into one input vector so only a
5478 // single pshufb instruction is necessary. If There are more than 2 input
5479 // quads, disable the next transformation since it does not help SSSE3.
5480 bool V1Used = InputQuads[0] || InputQuads[1];
5481 bool V2Used = InputQuads[2] || InputQuads[3];
5482 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5483 if (InputQuads.count() == 2 && V1Used && V2Used) {
5484 BestLoQuad = InputQuads.find_first();
5485 BestHiQuad = InputQuads.find_next(BestLoQuad);
5487 if (InputQuads.count() > 2) {
5493 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5494 // the shuffle mask. If a quad is scored as -1, that means that it contains
5495 // words from all 4 input quadwords.
5497 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5498 SmallVector<int, 8> MaskV;
5499 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5500 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5501 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5502 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5503 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5504 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5506 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5507 // source words for the shuffle, to aid later transformations.
5508 bool AllWordsInNewV = true;
5509 bool InOrder[2] = { true, true };
5510 for (unsigned i = 0; i != 8; ++i) {
5511 int idx = MaskVals[i];
5513 InOrder[i/4] = false;
5514 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5516 AllWordsInNewV = false;
5520 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5521 if (AllWordsInNewV) {
5522 for (int i = 0; i != 8; ++i) {
5523 int idx = MaskVals[i];
5526 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5527 if ((idx != i) && idx < 4)
5529 if ((idx != i) && idx > 3)
5538 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5539 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5540 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5541 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5542 unsigned TargetMask = 0;
5543 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5544 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5545 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5546 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5547 V1 = NewV.getOperand(0);
5548 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5552 // If we have SSSE3, and all words of the result are from 1 input vector,
5553 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5554 // is present, fall back to case 4.
5555 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5556 SmallVector<SDValue,16> pshufbMask;
5558 // If we have elements from both input vectors, set the high bit of the
5559 // shuffle mask element to zero out elements that come from V2 in the V1
5560 // mask, and elements that come from V1 in the V2 mask, so that the two
5561 // results can be OR'd together.
5562 bool TwoInputs = V1Used && V2Used;
5563 for (unsigned i = 0; i != 8; ++i) {
5564 int EltIdx = MaskVals[i] * 2;
5565 if (TwoInputs && (EltIdx >= 16)) {
5566 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5567 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5570 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5571 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5573 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5574 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5575 DAG.getNode(ISD::BUILD_VECTOR, dl,
5576 MVT::v16i8, &pshufbMask[0], 16));
5578 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5580 // Calculate the shuffle mask for the second input, shuffle it, and
5581 // OR it with the first shuffled input.
5583 for (unsigned i = 0; i != 8; ++i) {
5584 int EltIdx = MaskVals[i] * 2;
5586 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5587 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5590 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5591 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5593 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5594 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5595 DAG.getNode(ISD::BUILD_VECTOR, dl,
5596 MVT::v16i8, &pshufbMask[0], 16));
5597 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5598 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5601 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5602 // and update MaskVals with new element order.
5603 BitVector InOrder(8);
5604 if (BestLoQuad >= 0) {
5605 SmallVector<int, 8> MaskV;
5606 for (int i = 0; i != 4; ++i) {
5607 int idx = MaskVals[i];
5609 MaskV.push_back(-1);
5611 } else if ((idx / 4) == BestLoQuad) {
5612 MaskV.push_back(idx & 3);
5615 MaskV.push_back(-1);
5618 for (unsigned i = 4; i != 8; ++i)
5620 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5623 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5624 (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5625 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5627 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5631 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5632 // and update MaskVals with the new element order.
5633 if (BestHiQuad >= 0) {
5634 SmallVector<int, 8> MaskV;
5635 for (unsigned i = 0; i != 4; ++i)
5637 for (unsigned i = 4; i != 8; ++i) {
5638 int idx = MaskVals[i];
5640 MaskV.push_back(-1);
5642 } else if ((idx / 4) == BestHiQuad) {
5643 MaskV.push_back((idx & 3) + 4);
5646 MaskV.push_back(-1);
5649 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5652 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5653 (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5654 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5656 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5660 // In case BestHi & BestLo were both -1, which means each quadword has a word
5661 // from each of the four input quadwords, calculate the InOrder bitvector now
5662 // before falling through to the insert/extract cleanup.
5663 if (BestLoQuad == -1 && BestHiQuad == -1) {
5665 for (int i = 0; i != 8; ++i)
5666 if (MaskVals[i] < 0 || MaskVals[i] == i)
5670 // The other elements are put in the right place using pextrw and pinsrw.
5671 for (unsigned i = 0; i != 8; ++i) {
5674 int EltIdx = MaskVals[i];
5677 SDValue ExtOp = (EltIdx < 8)
5678 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5679 DAG.getIntPtrConstant(EltIdx))
5680 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5681 DAG.getIntPtrConstant(EltIdx - 8));
5682 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5683 DAG.getIntPtrConstant(i));
5688 // v16i8 shuffles - Prefer shuffles in the following order:
5689 // 1. [ssse3] 1 x pshufb
5690 // 2. [ssse3] 2 x pshufb + 1 x por
5691 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5693 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5695 const X86TargetLowering &TLI) {
5696 SDValue V1 = SVOp->getOperand(0);
5697 SDValue V2 = SVOp->getOperand(1);
5698 DebugLoc dl = SVOp->getDebugLoc();
5699 SmallVector<int, 16> MaskVals;
5700 SVOp->getMask(MaskVals);
5702 // If we have SSSE3, case 1 is generated when all result bytes come from
5703 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5704 // present, fall back to case 3.
5705 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5708 for (unsigned i = 0; i < 16; ++i) {
5709 int EltIdx = MaskVals[i];
5718 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5719 if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5720 SmallVector<SDValue,16> pshufbMask;
5722 // If all result elements are from one input vector, then only translate
5723 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5725 // Otherwise, we have elements from both input vectors, and must zero out
5726 // elements that come from V2 in the first mask, and V1 in the second mask
5727 // so that we can OR them together.
5728 bool TwoInputs = !(V1Only || V2Only);
5729 for (unsigned i = 0; i != 16; ++i) {
5730 int EltIdx = MaskVals[i];
5731 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5732 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5735 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5737 // If all the elements are from V2, assign it to V1 and return after
5738 // building the first pshufb.
5741 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5742 DAG.getNode(ISD::BUILD_VECTOR, dl,
5743 MVT::v16i8, &pshufbMask[0], 16));
5747 // Calculate the shuffle mask for the second input, shuffle it, and
5748 // OR it with the first shuffled input.
5750 for (unsigned i = 0; i != 16; ++i) {
5751 int EltIdx = MaskVals[i];
5753 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5756 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5758 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5759 DAG.getNode(ISD::BUILD_VECTOR, dl,
5760 MVT::v16i8, &pshufbMask[0], 16));
5761 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5764 // No SSSE3 - Calculate in place words and then fix all out of place words
5765 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5766 // the 16 different words that comprise the two doublequadword input vectors.
5767 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5768 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5769 SDValue NewV = V2Only ? V2 : V1;
5770 for (int i = 0; i != 8; ++i) {
5771 int Elt0 = MaskVals[i*2];
5772 int Elt1 = MaskVals[i*2+1];
5774 // This word of the result is all undef, skip it.
5775 if (Elt0 < 0 && Elt1 < 0)
5778 // This word of the result is already in the correct place, skip it.
5779 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5781 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5784 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5785 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5788 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5789 // using a single extract together, load it and store it.
5790 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5791 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5792 DAG.getIntPtrConstant(Elt1 / 2));
5793 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5794 DAG.getIntPtrConstant(i));
5798 // If Elt1 is defined, extract it from the appropriate source. If the
5799 // source byte is not also odd, shift the extracted word left 8 bits
5800 // otherwise clear the bottom 8 bits if we need to do an or.
5802 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5803 DAG.getIntPtrConstant(Elt1 / 2));
5804 if ((Elt1 & 1) == 0)
5805 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5807 TLI.getShiftAmountTy(InsElt.getValueType())));
5809 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5810 DAG.getConstant(0xFF00, MVT::i16));
5812 // If Elt0 is defined, extract it from the appropriate source. If the
5813 // source byte is not also even, shift the extracted word right 8 bits. If
5814 // Elt1 was also defined, OR the extracted values together before
5815 // inserting them in the result.
5817 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5818 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5819 if ((Elt0 & 1) != 0)
5820 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5822 TLI.getShiftAmountTy(InsElt0.getValueType())));
5824 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5825 DAG.getConstant(0x00FF, MVT::i16));
5826 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5829 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5830 DAG.getIntPtrConstant(i));
5832 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5835 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5836 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5837 /// done when every pair / quad of shuffle mask elements point to elements in
5838 /// the right sequence. e.g.
5839 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5841 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5842 SelectionDAG &DAG, DebugLoc dl) {
5843 EVT VT = SVOp->getValueType(0);
5844 SDValue V1 = SVOp->getOperand(0);
5845 SDValue V2 = SVOp->getOperand(1);
5846 unsigned NumElems = VT.getVectorNumElements();
5847 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5849 switch (VT.getSimpleVT().SimpleTy) {
5850 default: assert(false && "Unexpected!");
5851 case MVT::v4f32: NewVT = MVT::v2f64; break;
5852 case MVT::v4i32: NewVT = MVT::v2i64; break;
5853 case MVT::v8i16: NewVT = MVT::v4i32; break;
5854 case MVT::v16i8: NewVT = MVT::v4i32; break;
5857 int Scale = NumElems / NewWidth;
5858 SmallVector<int, 8> MaskVec;
5859 for (unsigned i = 0; i < NumElems; i += Scale) {
5861 for (int j = 0; j < Scale; ++j) {
5862 int EltIdx = SVOp->getMaskElt(i+j);
5866 StartIdx = EltIdx - (EltIdx % Scale);
5867 if (EltIdx != StartIdx + j)
5871 MaskVec.push_back(-1);
5873 MaskVec.push_back(StartIdx / Scale);
5876 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5877 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5878 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5881 /// getVZextMovL - Return a zero-extending vector move low node.
5883 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5884 SDValue SrcOp, SelectionDAG &DAG,
5885 const X86Subtarget *Subtarget, DebugLoc dl) {
5886 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5887 LoadSDNode *LD = NULL;
5888 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5889 LD = dyn_cast<LoadSDNode>(SrcOp);
5891 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5893 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5894 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5895 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5896 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5897 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5899 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5900 return DAG.getNode(ISD::BITCAST, dl, VT,
5901 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5902 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5910 return DAG.getNode(ISD::BITCAST, dl, VT,
5911 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5912 DAG.getNode(ISD::BITCAST, dl,
5916 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5917 /// shuffle node referes to only one lane in the sources.
5918 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5919 EVT VT = SVOp->getValueType(0);
5920 int NumElems = VT.getVectorNumElements();
5921 int HalfSize = NumElems/2;
5922 SmallVector<int, 16> M;
5924 bool MatchA = false, MatchB = false;
5926 for (int l = 0; l < NumElems*2; l += HalfSize) {
5927 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5933 for (int l = 0; l < NumElems*2; l += HalfSize) {
5934 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5940 return MatchA && MatchB;
5943 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5944 /// which could not be matched by any known target speficic shuffle
5946 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5947 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5948 // If each half of a vector shuffle node referes to only one lane in the
5949 // source vectors, extract each used 128-bit lane and shuffle them using
5950 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5951 // the work to the legalizer.
5952 DebugLoc dl = SVOp->getDebugLoc();
5953 EVT VT = SVOp->getValueType(0);
5954 int NumElems = VT.getVectorNumElements();
5955 int HalfSize = NumElems/2;
5957 // Extract the reference for each half
5958 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5959 int FstVecOpNum = 0, SndVecOpNum = 0;
5960 for (int i = 0; i < HalfSize; ++i) {
5961 int Elt = SVOp->getMaskElt(i);
5962 if (SVOp->getMaskElt(i) < 0)
5964 FstVecOpNum = Elt/NumElems;
5965 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5968 for (int i = HalfSize; i < NumElems; ++i) {
5969 int Elt = SVOp->getMaskElt(i);
5970 if (SVOp->getMaskElt(i) < 0)
5972 SndVecOpNum = Elt/NumElems;
5973 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5977 // Extract the subvectors
5978 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5979 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5980 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5981 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5983 // Generate 128-bit shuffles
5984 SmallVector<int, 16> MaskV1, MaskV2;
5985 for (int i = 0; i < HalfSize; ++i) {
5986 int Elt = SVOp->getMaskElt(i);
5987 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5989 for (int i = HalfSize; i < NumElems; ++i) {
5990 int Elt = SVOp->getMaskElt(i);
5991 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5994 EVT NVT = V1.getValueType();
5995 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5996 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5998 // Concatenate the result back
5999 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6000 DAG.getConstant(0, MVT::i32), DAG, dl);
6001 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6008 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6009 /// 4 elements, and match them with several different shuffle types.
6011 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6012 SDValue V1 = SVOp->getOperand(0);
6013 SDValue V2 = SVOp->getOperand(1);
6014 DebugLoc dl = SVOp->getDebugLoc();
6015 EVT VT = SVOp->getValueType(0);
6017 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6019 SmallVector<std::pair<int, int>, 8> Locs;
6021 SmallVector<int, 8> Mask1(4U, -1);
6022 SmallVector<int, 8> PermMask;
6023 SVOp->getMask(PermMask);
6027 for (unsigned i = 0; i != 4; ++i) {
6028 int Idx = PermMask[i];
6030 Locs[i] = std::make_pair(-1, -1);
6032 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6034 Locs[i] = std::make_pair(0, NumLo);
6038 Locs[i] = std::make_pair(1, NumHi);
6040 Mask1[2+NumHi] = Idx;
6046 if (NumLo <= 2 && NumHi <= 2) {
6047 // If no more than two elements come from either vector. This can be
6048 // implemented with two shuffles. First shuffle gather the elements.
6049 // The second shuffle, which takes the first shuffle as both of its
6050 // vector operands, put the elements into the right order.
6051 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6053 SmallVector<int, 8> Mask2(4U, -1);
6055 for (unsigned i = 0; i != 4; ++i) {
6056 if (Locs[i].first == -1)
6059 unsigned Idx = (i < 2) ? 0 : 4;
6060 Idx += Locs[i].first * 2 + Locs[i].second;
6065 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6066 } else if (NumLo == 3 || NumHi == 3) {
6067 // Otherwise, we must have three elements from one vector, call it X, and
6068 // one element from the other, call it Y. First, use a shufps to build an
6069 // intermediate vector with the one element from Y and the element from X
6070 // that will be in the same half in the final destination (the indexes don't
6071 // matter). Then, use a shufps to build the final vector, taking the half
6072 // containing the element from Y from the intermediate, and the other half
6075 // Normalize it so the 3 elements come from V1.
6076 CommuteVectorShuffleMask(PermMask, VT);
6080 // Find the element from V2.
6082 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6083 int Val = PermMask[HiIndex];
6090 Mask1[0] = PermMask[HiIndex];
6092 Mask1[2] = PermMask[HiIndex^1];
6094 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6097 Mask1[0] = PermMask[0];
6098 Mask1[1] = PermMask[1];
6099 Mask1[2] = HiIndex & 1 ? 6 : 4;
6100 Mask1[3] = HiIndex & 1 ? 4 : 6;
6101 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6103 Mask1[0] = HiIndex & 1 ? 2 : 0;
6104 Mask1[1] = HiIndex & 1 ? 0 : 2;
6105 Mask1[2] = PermMask[2];
6106 Mask1[3] = PermMask[3];
6111 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6115 // Break it into (shuffle shuffle_hi, shuffle_lo).
6118 SmallVector<int,8> LoMask(4U, -1);
6119 SmallVector<int,8> HiMask(4U, -1);
6121 SmallVector<int,8> *MaskPtr = &LoMask;
6122 unsigned MaskIdx = 0;
6125 for (unsigned i = 0; i != 4; ++i) {
6132 int Idx = PermMask[i];
6134 Locs[i] = std::make_pair(-1, -1);
6135 } else if (Idx < 4) {
6136 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6137 (*MaskPtr)[LoIdx] = Idx;
6140 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6141 (*MaskPtr)[HiIdx] = Idx;
6146 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6147 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6148 SmallVector<int, 8> MaskOps;
6149 for (unsigned i = 0; i != 4; ++i) {
6150 if (Locs[i].first == -1) {
6151 MaskOps.push_back(-1);
6153 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6154 MaskOps.push_back(Idx);
6157 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6160 static bool MayFoldVectorLoad(SDValue V) {
6161 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6162 V = V.getOperand(0);
6163 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6164 V = V.getOperand(0);
6170 // FIXME: the version above should always be used. Since there's
6171 // a bug where several vector shuffles can't be folded because the
6172 // DAG is not updated during lowering and a node claims to have two
6173 // uses while it only has one, use this version, and let isel match
6174 // another instruction if the load really happens to have more than
6175 // one use. Remove this version after this bug get fixed.
6176 // rdar://8434668, PR8156
6177 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6178 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6179 V = V.getOperand(0);
6180 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6181 V = V.getOperand(0);
6182 if (ISD::isNormalLoad(V.getNode()))
6187 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6188 /// a vector extract, and if both can be later optimized into a single load.
6189 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6190 /// here because otherwise a target specific shuffle node is going to be
6191 /// emitted for this shuffle, and the optimization not done.
6192 /// FIXME: This is probably not the best approach, but fix the problem
6193 /// until the right path is decided.
6195 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6196 const TargetLowering &TLI) {
6197 EVT VT = V.getValueType();
6198 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6200 // Be sure that the vector shuffle is present in a pattern like this:
6201 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6205 SDNode *N = *V.getNode()->use_begin();
6206 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6209 SDValue EltNo = N->getOperand(1);
6210 if (!isa<ConstantSDNode>(EltNo))
6213 // If the bit convert changed the number of elements, it is unsafe
6214 // to examine the mask.
6215 bool HasShuffleIntoBitcast = false;
6216 if (V.getOpcode() == ISD::BITCAST) {
6217 EVT SrcVT = V.getOperand(0).getValueType();
6218 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6220 V = V.getOperand(0);
6221 HasShuffleIntoBitcast = true;
6224 // Select the input vector, guarding against out of range extract vector.
6225 unsigned NumElems = VT.getVectorNumElements();
6226 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6227 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6228 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6230 // Skip one more bit_convert if necessary
6231 if (V.getOpcode() == ISD::BITCAST)
6232 V = V.getOperand(0);
6234 if (ISD::isNormalLoad(V.getNode())) {
6235 // Is the original load suitable?
6236 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6238 // FIXME: avoid the multi-use bug that is preventing lots of
6239 // of foldings to be detected, this is still wrong of course, but
6240 // give the temporary desired behavior, and if it happens that
6241 // the load has real more uses, during isel it will not fold, and
6242 // will generate poor code.
6243 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6246 if (!HasShuffleIntoBitcast)
6249 // If there's a bitcast before the shuffle, check if the load type and
6250 // alignment is valid.
6251 unsigned Align = LN0->getAlignment();
6253 TLI.getTargetData()->getABITypeAlignment(
6254 VT.getTypeForEVT(*DAG.getContext()));
6256 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6264 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6265 EVT VT = Op.getValueType();
6267 // Canonizalize to v2f64.
6268 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6269 return DAG.getNode(ISD::BITCAST, dl, VT,
6270 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6275 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6277 SDValue V1 = Op.getOperand(0);
6278 SDValue V2 = Op.getOperand(1);
6279 EVT VT = Op.getValueType();
6281 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6283 if (HasXMMInt && VT == MVT::v2f64)
6284 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6286 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6287 return DAG.getNode(ISD::BITCAST, dl, VT,
6288 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6289 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6290 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6294 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6295 SDValue V1 = Op.getOperand(0);
6296 SDValue V2 = Op.getOperand(1);
6297 EVT VT = Op.getValueType();
6299 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6300 "unsupported shuffle type");
6302 if (V2.getOpcode() == ISD::UNDEF)
6306 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6309 static inline unsigned getSHUFPOpcode(EVT VT) {
6310 switch(VT.getSimpleVT().SimpleTy) {
6311 case MVT::v8i32: // Use fp unit for int unpack.
6313 case MVT::v4i32: // Use fp unit for int unpack.
6314 case MVT::v4f32: return X86ISD::SHUFPS;
6315 case MVT::v4i64: // Use fp unit for int unpack.
6317 case MVT::v2i64: // Use fp unit for int unpack.
6318 case MVT::v2f64: return X86ISD::SHUFPD;
6320 llvm_unreachable("Unknown type for shufp*");
6326 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6327 SDValue V1 = Op.getOperand(0);
6328 SDValue V2 = Op.getOperand(1);
6329 EVT VT = Op.getValueType();
6330 unsigned NumElems = VT.getVectorNumElements();
6332 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6333 // operand of these instructions is only memory, so check if there's a
6334 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6336 bool CanFoldLoad = false;
6338 // Trivial case, when V2 comes from a load.
6339 if (MayFoldVectorLoad(V2))
6342 // When V1 is a load, it can be folded later into a store in isel, example:
6343 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6345 // (MOVLPSmr addr:$src1, VR128:$src2)
6346 // So, recognize this potential and also use MOVLPS or MOVLPD
6347 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6350 // Both of them can't be memory operations though.
6351 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6352 CanFoldLoad = false;
6355 if (HasXMMInt && NumElems == 2)
6356 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6359 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6362 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6363 // movl and movlp will both match v2i64, but v2i64 is never matched by
6364 // movl earlier because we make it strict to avoid messing with the movlp load
6365 // folding logic (see the code above getMOVLP call). Match it here then,
6366 // this is horrible, but will stay like this until we move all shuffle
6367 // matching to x86 specific nodes. Note that for the 1st condition all
6368 // types are matched with movsd.
6370 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6371 // as to remove this logic from here, as much as possible
6372 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6373 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6374 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6377 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6379 // Invert the operand order and use SHUFPS to match it.
6380 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6381 X86::getShuffleSHUFImmediate(SVOp), DAG);
6384 static inline unsigned getUNPCKLOpcode(EVT VT) {
6385 switch(VT.getSimpleVT().SimpleTy) {
6386 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6387 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6388 case MVT::v4f32: return X86ISD::UNPCKLPS;
6389 case MVT::v2f64: return X86ISD::UNPCKLPD;
6390 case MVT::v8i32: // Use fp unit for int unpack.
6391 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6392 case MVT::v4i64: // Use fp unit for int unpack.
6393 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6394 case MVT::v16i8: return X86ISD::PUNPCKLBW;
6395 case MVT::v8i16: return X86ISD::PUNPCKLWD;
6397 llvm_unreachable("Unknown type for unpckl");
6402 static inline unsigned getUNPCKHOpcode(EVT VT) {
6403 switch(VT.getSimpleVT().SimpleTy) {
6404 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6405 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6406 case MVT::v4f32: return X86ISD::UNPCKHPS;
6407 case MVT::v2f64: return X86ISD::UNPCKHPD;
6408 case MVT::v8i32: // Use fp unit for int unpack.
6409 case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6410 case MVT::v4i64: // Use fp unit for int unpack.
6411 case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6412 case MVT::v16i8: return X86ISD::PUNPCKHBW;
6413 case MVT::v8i16: return X86ISD::PUNPCKHWD;
6415 llvm_unreachable("Unknown type for unpckh");
6420 static inline unsigned getVPERMILOpcode(EVT VT) {
6421 switch(VT.getSimpleVT().SimpleTy) {
6423 case MVT::v4f32: return X86ISD::VPERMILPS;
6425 case MVT::v2f64: return X86ISD::VPERMILPD;
6427 case MVT::v8f32: return X86ISD::VPERMILPSY;
6429 case MVT::v4f64: return X86ISD::VPERMILPDY;
6431 llvm_unreachable("Unknown type for vpermil");
6436 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6437 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6438 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6439 static bool isVectorBroadcast(SDValue &Op) {
6440 EVT VT = Op.getValueType();
6441 bool Is256 = VT.getSizeInBits() == 256;
6443 assert((VT.getSizeInBits() == 128 || Is256) &&
6444 "Unsupported type for vbroadcast node");
6447 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6448 V = V.getOperand(0);
6450 if (Is256 && !(V.hasOneUse() &&
6451 V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6452 V.getOperand(0).getOpcode() == ISD::UNDEF))
6456 V = V.getOperand(1);
6461 // Check the source scalar_to_vector type. 256-bit broadcasts are
6462 // supported for 32/64-bit sizes, while 128-bit ones are only supported
6463 // for 32-bit scalars.
6464 if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6467 unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6468 if (ScalarSize != 32 && ScalarSize != 64)
6470 if (!Is256 && ScalarSize == 64)
6473 V = V.getOperand(0);
6474 if (!MayFoldLoad(V))
6477 // Return the load node
6483 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6484 const TargetLowering &TLI,
6485 const X86Subtarget *Subtarget) {
6486 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6487 EVT VT = Op.getValueType();
6488 DebugLoc dl = Op.getDebugLoc();
6489 SDValue V1 = Op.getOperand(0);
6490 SDValue V2 = Op.getOperand(1);
6492 if (isZeroShuffle(SVOp))
6493 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6495 // Handle splat operations
6496 if (SVOp->isSplat()) {
6497 unsigned NumElem = VT.getVectorNumElements();
6498 int Size = VT.getSizeInBits();
6499 // Special case, this is the only place now where it's allowed to return
6500 // a vector_shuffle operation without using a target specific node, because
6501 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6502 // this be moved to DAGCombine instead?
6503 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6506 // Use vbroadcast whenever the splat comes from a foldable load
6507 if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6508 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6510 // Handle splats by matching through known shuffle masks
6511 if ((Size == 128 && NumElem <= 4) ||
6512 (Size == 256 && NumElem < 8))
6515 // All remaning splats are promoted to target supported vector shuffles.
6516 return PromoteSplat(SVOp, DAG);
6519 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6521 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6522 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6523 if (NewOp.getNode())
6524 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6525 } else if ((VT == MVT::v4i32 ||
6526 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6527 // FIXME: Figure out a cleaner way to do this.
6528 // Try to make use of movq to zero out the top part.
6529 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6530 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6531 if (NewOp.getNode()) {
6532 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6533 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6534 DAG, Subtarget, dl);
6536 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6537 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6538 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6539 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6540 DAG, Subtarget, dl);
6547 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6548 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6549 SDValue V1 = Op.getOperand(0);
6550 SDValue V2 = Op.getOperand(1);
6551 EVT VT = Op.getValueType();
6552 DebugLoc dl = Op.getDebugLoc();
6553 unsigned NumElems = VT.getVectorNumElements();
6554 bool isMMX = VT.getSizeInBits() == 64;
6555 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6556 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6557 bool V1IsSplat = false;
6558 bool V2IsSplat = false;
6559 bool HasXMMInt = Subtarget->hasXMMInt();
6560 MachineFunction &MF = DAG.getMachineFunction();
6561 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6563 // Shuffle operations on MMX not supported.
6567 // Vector shuffle lowering takes 3 steps:
6569 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6570 // narrowing and commutation of operands should be handled.
6571 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6573 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6574 // so the shuffle can be broken into other shuffles and the legalizer can
6575 // try the lowering again.
6577 // The general ideia is that no vector_shuffle operation should be left to
6578 // be matched during isel, all of them must be converted to a target specific
6581 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6582 // narrowing and commutation of operands should be handled. The actual code
6583 // doesn't include all of those, work in progress...
6584 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6585 if (NewOp.getNode())
6588 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6589 // unpckh_undef). Only use pshufd if speed is more important than size.
6590 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6591 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6592 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6593 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6595 if (X86::isMOVDDUPMask(SVOp) &&
6596 (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6597 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6598 return getMOVDDup(Op, dl, V1, DAG);
6600 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6601 return getMOVHighToLow(Op, dl, DAG);
6603 // Use to match splats
6604 if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6605 (VT == MVT::v2f64 || VT == MVT::v2i64))
6606 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6608 if (X86::isPSHUFDMask(SVOp)) {
6609 // The actual implementation will match the mask in the if above and then
6610 // during isel it can match several different instructions, not only pshufd
6611 // as its name says, sad but true, emulate the behavior for now...
6612 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6613 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6615 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6617 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6618 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6620 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6624 // Check if this can be converted into a logical shift.
6625 bool isLeft = false;
6628 bool isShift = getSubtarget()->hasXMMInt() &&
6629 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6630 if (isShift && ShVal.hasOneUse()) {
6631 // If the shifted value has multiple uses, it may be cheaper to use
6632 // v_set0 + movlhps or movhlps, etc.
6633 EVT EltVT = VT.getVectorElementType();
6634 ShAmt *= EltVT.getSizeInBits();
6635 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6638 if (X86::isMOVLMask(SVOp)) {
6641 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6642 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6643 if (!X86::isMOVLPMask(SVOp)) {
6644 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6645 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6647 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6648 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6652 // FIXME: fold these into legal mask.
6653 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6654 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6656 if (X86::isMOVHLPSMask(SVOp))
6657 return getMOVHighToLow(Op, dl, DAG);
6659 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6660 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6662 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6663 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6665 if (X86::isMOVLPMask(SVOp))
6666 return getMOVLP(Op, dl, DAG, HasXMMInt);
6668 if (ShouldXformToMOVHLPS(SVOp) ||
6669 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6670 return CommuteVectorShuffle(SVOp, DAG);
6673 // No better options. Use a vshl / vsrl.
6674 EVT EltVT = VT.getVectorElementType();
6675 ShAmt *= EltVT.getSizeInBits();
6676 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6679 bool Commuted = false;
6680 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6681 // 1,1,1,1 -> v8i16 though.
6682 V1IsSplat = isSplatVector(V1.getNode());
6683 V2IsSplat = isSplatVector(V2.getNode());
6685 // Canonicalize the splat or undef, if present, to be on the RHS.
6686 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6687 Op = CommuteVectorShuffle(SVOp, DAG);
6688 SVOp = cast<ShuffleVectorSDNode>(Op);
6689 V1 = SVOp->getOperand(0);
6690 V2 = SVOp->getOperand(1);
6691 std::swap(V1IsSplat, V2IsSplat);
6692 std::swap(V1IsUndef, V2IsUndef);
6696 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6697 // Shuffling low element of v1 into undef, just return v1.
6700 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6701 // the instruction selector will not match, so get a canonical MOVL with
6702 // swapped operands to undo the commute.
6703 return getMOVL(DAG, dl, VT, V2, V1);
6706 if (X86::isUNPCKLMask(SVOp))
6707 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6709 if (X86::isUNPCKHMask(SVOp))
6710 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6713 // Normalize mask so all entries that point to V2 points to its first
6714 // element then try to match unpck{h|l} again. If match, return a
6715 // new vector_shuffle with the corrected mask.
6716 SDValue NewMask = NormalizeMask(SVOp, DAG);
6717 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6718 if (NSVOp != SVOp) {
6719 if (X86::isUNPCKLMask(NSVOp, true)) {
6721 } else if (X86::isUNPCKHMask(NSVOp, true)) {
6728 // Commute is back and try unpck* again.
6729 // FIXME: this seems wrong.
6730 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6731 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6733 if (X86::isUNPCKLMask(NewSVOp))
6734 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6736 if (X86::isUNPCKHMask(NewSVOp))
6737 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6740 // Normalize the node to match x86 shuffle ops if needed
6741 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6742 return CommuteVectorShuffle(SVOp, DAG);
6744 // The checks below are all present in isShuffleMaskLegal, but they are
6745 // inlined here right now to enable us to directly emit target specific
6746 // nodes, and remove one by one until they don't return Op anymore.
6747 SmallVector<int, 16> M;
6750 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6751 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6752 X86::getShufflePALIGNRImmediate(SVOp),
6755 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6756 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6757 if (VT == MVT::v2f64)
6758 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6759 if (VT == MVT::v2i64)
6760 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6763 if (isPSHUFHWMask(M, VT))
6764 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6765 X86::getShufflePSHUFHWImmediate(SVOp),
6768 if (isPSHUFLWMask(M, VT))
6769 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6770 X86::getShufflePSHUFLWImmediate(SVOp),
6773 if (isSHUFPMask(M, VT))
6774 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6775 X86::getShuffleSHUFImmediate(SVOp), DAG);
6777 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6778 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6779 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6780 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6782 //===--------------------------------------------------------------------===//
6783 // Generate target specific nodes for 128 or 256-bit shuffles only
6784 // supported in the AVX instruction set.
6787 // Handle VMOVDDUPY permutations
6788 if (isMOVDDUPYMask(SVOp, Subtarget))
6789 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6791 // Handle VPERMILPS* permutations
6792 if (isVPERMILPSMask(M, VT, Subtarget))
6793 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6794 getShuffleVPERMILPSImmediate(SVOp), DAG);
6796 // Handle VPERMILPD* permutations
6797 if (isVPERMILPDMask(M, VT, Subtarget))
6798 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6799 getShuffleVPERMILPDImmediate(SVOp), DAG);
6801 // Handle VPERM2F128 permutations
6802 if (isVPERM2F128Mask(M, VT, Subtarget))
6803 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6804 getShuffleVPERM2F128Immediate(SVOp), DAG);
6806 // Handle VSHUFPSY permutations
6807 if (isVSHUFPSYMask(M, VT, Subtarget))
6808 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6809 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6811 // Handle VSHUFPDY permutations
6812 if (isVSHUFPDYMask(M, VT, Subtarget))
6813 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6814 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6816 //===--------------------------------------------------------------------===//
6817 // Since no target specific shuffle was selected for this generic one,
6818 // lower it into other known shuffles. FIXME: this isn't true yet, but
6819 // this is the plan.
6822 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6823 if (VT == MVT::v8i16) {
6824 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6825 if (NewOp.getNode())
6829 if (VT == MVT::v16i8) {
6830 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6831 if (NewOp.getNode())
6835 // Handle all 128-bit wide vectors with 4 elements, and match them with
6836 // several different shuffle types.
6837 if (NumElems == 4 && VT.getSizeInBits() == 128)
6838 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6840 // Handle general 256-bit shuffles
6841 if (VT.is256BitVector())
6842 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6848 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6849 SelectionDAG &DAG) const {
6850 EVT VT = Op.getValueType();
6851 DebugLoc dl = Op.getDebugLoc();
6853 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6856 if (VT.getSizeInBits() == 8) {
6857 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6858 Op.getOperand(0), Op.getOperand(1));
6859 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6860 DAG.getValueType(VT));
6861 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6862 } else if (VT.getSizeInBits() == 16) {
6863 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6864 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6866 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6867 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6868 DAG.getNode(ISD::BITCAST, dl,
6872 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6873 Op.getOperand(0), Op.getOperand(1));
6874 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6875 DAG.getValueType(VT));
6876 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6877 } else if (VT == MVT::f32) {
6878 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6879 // the result back to FR32 register. It's only worth matching if the
6880 // result has a single use which is a store or a bitcast to i32. And in
6881 // the case of a store, it's not worth it if the index is a constant 0,
6882 // because a MOVSSmr can be used instead, which is smaller and faster.
6883 if (!Op.hasOneUse())
6885 SDNode *User = *Op.getNode()->use_begin();
6886 if ((User->getOpcode() != ISD::STORE ||
6887 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6888 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6889 (User->getOpcode() != ISD::BITCAST ||
6890 User->getValueType(0) != MVT::i32))
6892 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6893 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6896 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6897 } else if (VT == MVT::i32) {
6898 // ExtractPS works with constant index.
6899 if (isa<ConstantSDNode>(Op.getOperand(1)))
6907 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6908 SelectionDAG &DAG) const {
6909 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6912 SDValue Vec = Op.getOperand(0);
6913 EVT VecVT = Vec.getValueType();
6915 // If this is a 256-bit vector result, first extract the 128-bit vector and
6916 // then extract the element from the 128-bit vector.
6917 if (VecVT.getSizeInBits() == 256) {
6918 DebugLoc dl = Op.getNode()->getDebugLoc();
6919 unsigned NumElems = VecVT.getVectorNumElements();
6920 SDValue Idx = Op.getOperand(1);
6921 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6923 // Get the 128-bit vector.
6924 bool Upper = IdxVal >= NumElems/2;
6925 Vec = Extract128BitVector(Vec,
6926 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6928 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6929 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6932 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6934 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6935 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6940 EVT VT = Op.getValueType();
6941 DebugLoc dl = Op.getDebugLoc();
6942 // TODO: handle v16i8.
6943 if (VT.getSizeInBits() == 16) {
6944 SDValue Vec = Op.getOperand(0);
6945 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6947 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6948 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6949 DAG.getNode(ISD::BITCAST, dl,
6952 // Transform it so it match pextrw which produces a 32-bit result.
6953 EVT EltVT = MVT::i32;
6954 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6955 Op.getOperand(0), Op.getOperand(1));
6956 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6957 DAG.getValueType(VT));
6958 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6959 } else if (VT.getSizeInBits() == 32) {
6960 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6964 // SHUFPS the element to the lowest double word, then movss.
6965 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6966 EVT VVT = Op.getOperand(0).getValueType();
6967 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6968 DAG.getUNDEF(VVT), Mask);
6969 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6970 DAG.getIntPtrConstant(0));
6971 } else if (VT.getSizeInBits() == 64) {
6972 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6973 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6974 // to match extract_elt for f64.
6975 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6979 // UNPCKHPD the element to the lowest double word, then movsd.
6980 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6981 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6982 int Mask[2] = { 1, -1 };
6983 EVT VVT = Op.getOperand(0).getValueType();
6984 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6985 DAG.getUNDEF(VVT), Mask);
6986 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6987 DAG.getIntPtrConstant(0));
6994 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6995 SelectionDAG &DAG) const {
6996 EVT VT = Op.getValueType();
6997 EVT EltVT = VT.getVectorElementType();
6998 DebugLoc dl = Op.getDebugLoc();
7000 SDValue N0 = Op.getOperand(0);
7001 SDValue N1 = Op.getOperand(1);
7002 SDValue N2 = Op.getOperand(2);
7004 if (VT.getSizeInBits() == 256)
7007 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7008 isa<ConstantSDNode>(N2)) {
7010 if (VT == MVT::v8i16)
7011 Opc = X86ISD::PINSRW;
7012 else if (VT == MVT::v16i8)
7013 Opc = X86ISD::PINSRB;
7015 Opc = X86ISD::PINSRB;
7017 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7019 if (N1.getValueType() != MVT::i32)
7020 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7021 if (N2.getValueType() != MVT::i32)
7022 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7023 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7024 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7025 // Bits [7:6] of the constant are the source select. This will always be
7026 // zero here. The DAG Combiner may combine an extract_elt index into these
7027 // bits. For example (insert (extract, 3), 2) could be matched by putting
7028 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7029 // Bits [5:4] of the constant are the destination select. This is the
7030 // value of the incoming immediate.
7031 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7032 // combine either bitwise AND or insert of float 0.0 to set these bits.
7033 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7034 // Create this as a scalar to vector..
7035 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7036 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7037 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7038 // PINSR* works with constant index.
7045 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7046 EVT VT = Op.getValueType();
7047 EVT EltVT = VT.getVectorElementType();
7049 DebugLoc dl = Op.getDebugLoc();
7050 SDValue N0 = Op.getOperand(0);
7051 SDValue N1 = Op.getOperand(1);
7052 SDValue N2 = Op.getOperand(2);
7054 // If this is a 256-bit vector result, first extract the 128-bit vector,
7055 // insert the element into the extracted half and then place it back.
7056 if (VT.getSizeInBits() == 256) {
7057 if (!isa<ConstantSDNode>(N2))
7060 // Get the desired 128-bit vector half.
7061 unsigned NumElems = VT.getVectorNumElements();
7062 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7063 bool Upper = IdxVal >= NumElems/2;
7064 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7065 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7067 // Insert the element into the desired half.
7068 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7069 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7071 // Insert the changed part back to the 256-bit vector
7072 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7075 if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7076 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7078 if (EltVT == MVT::i8)
7081 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7082 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7083 // as its second argument.
7084 if (N1.getValueType() != MVT::i32)
7085 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7086 if (N2.getValueType() != MVT::i32)
7087 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7088 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7094 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7095 LLVMContext *Context = DAG.getContext();
7096 DebugLoc dl = Op.getDebugLoc();
7097 EVT OpVT = Op.getValueType();
7099 // If this is a 256-bit vector result, first insert into a 128-bit
7100 // vector and then insert into the 256-bit vector.
7101 if (OpVT.getSizeInBits() > 128) {
7102 // Insert into a 128-bit vector.
7103 EVT VT128 = EVT::getVectorVT(*Context,
7104 OpVT.getVectorElementType(),
7105 OpVT.getVectorNumElements() / 2);
7107 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7109 // Insert the 128-bit vector.
7110 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7111 DAG.getConstant(0, MVT::i32),
7115 if (Op.getValueType() == MVT::v1i64 &&
7116 Op.getOperand(0).getValueType() == MVT::i64)
7117 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7119 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7120 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7121 "Expected an SSE type!");
7122 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7123 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7126 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7127 // a simple subregister reference or explicit instructions to grab
7128 // upper bits of a vector.
7130 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7131 if (Subtarget->hasAVX()) {
7132 DebugLoc dl = Op.getNode()->getDebugLoc();
7133 SDValue Vec = Op.getNode()->getOperand(0);
7134 SDValue Idx = Op.getNode()->getOperand(1);
7136 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7137 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7138 return Extract128BitVector(Vec, Idx, DAG, dl);
7144 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7145 // simple superregister reference or explicit instructions to insert
7146 // the upper bits of a vector.
7148 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7149 if (Subtarget->hasAVX()) {
7150 DebugLoc dl = Op.getNode()->getDebugLoc();
7151 SDValue Vec = Op.getNode()->getOperand(0);
7152 SDValue SubVec = Op.getNode()->getOperand(1);
7153 SDValue Idx = Op.getNode()->getOperand(2);
7155 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7156 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7157 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7163 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7164 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7165 // one of the above mentioned nodes. It has to be wrapped because otherwise
7166 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7167 // be used to form addressing mode. These wrapped nodes will be selected
7170 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7171 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7173 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7175 unsigned char OpFlag = 0;
7176 unsigned WrapperKind = X86ISD::Wrapper;
7177 CodeModel::Model M = getTargetMachine().getCodeModel();
7179 if (Subtarget->isPICStyleRIPRel() &&
7180 (M == CodeModel::Small || M == CodeModel::Kernel))
7181 WrapperKind = X86ISD::WrapperRIP;
7182 else if (Subtarget->isPICStyleGOT())
7183 OpFlag = X86II::MO_GOTOFF;
7184 else if (Subtarget->isPICStyleStubPIC())
7185 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7187 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7189 CP->getOffset(), OpFlag);
7190 DebugLoc DL = CP->getDebugLoc();
7191 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7192 // With PIC, the address is actually $g + Offset.
7194 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7195 DAG.getNode(X86ISD::GlobalBaseReg,
7196 DebugLoc(), getPointerTy()),
7203 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7204 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7206 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7208 unsigned char OpFlag = 0;
7209 unsigned WrapperKind = X86ISD::Wrapper;
7210 CodeModel::Model M = getTargetMachine().getCodeModel();
7212 if (Subtarget->isPICStyleRIPRel() &&
7213 (M == CodeModel::Small || M == CodeModel::Kernel))
7214 WrapperKind = X86ISD::WrapperRIP;
7215 else if (Subtarget->isPICStyleGOT())
7216 OpFlag = X86II::MO_GOTOFF;
7217 else if (Subtarget->isPICStyleStubPIC())
7218 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7220 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7222 DebugLoc DL = JT->getDebugLoc();
7223 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7225 // With PIC, the address is actually $g + Offset.
7227 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7228 DAG.getNode(X86ISD::GlobalBaseReg,
7229 DebugLoc(), getPointerTy()),
7236 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7237 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7239 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7241 unsigned char OpFlag = 0;
7242 unsigned WrapperKind = X86ISD::Wrapper;
7243 CodeModel::Model M = getTargetMachine().getCodeModel();
7245 if (Subtarget->isPICStyleRIPRel() &&
7246 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7247 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7248 OpFlag = X86II::MO_GOTPCREL;
7249 WrapperKind = X86ISD::WrapperRIP;
7250 } else if (Subtarget->isPICStyleGOT()) {
7251 OpFlag = X86II::MO_GOT;
7252 } else if (Subtarget->isPICStyleStubPIC()) {
7253 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7254 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7255 OpFlag = X86II::MO_DARWIN_NONLAZY;
7258 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7260 DebugLoc DL = Op.getDebugLoc();
7261 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7264 // With PIC, the address is actually $g + Offset.
7265 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7266 !Subtarget->is64Bit()) {
7267 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7268 DAG.getNode(X86ISD::GlobalBaseReg,
7269 DebugLoc(), getPointerTy()),
7273 // For symbols that require a load from a stub to get the address, emit the
7275 if (isGlobalStubReference(OpFlag))
7276 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7277 MachinePointerInfo::getGOT(), false, false, 0);
7283 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7284 // Create the TargetBlockAddressAddress node.
7285 unsigned char OpFlags =
7286 Subtarget->ClassifyBlockAddressReference();
7287 CodeModel::Model M = getTargetMachine().getCodeModel();
7288 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7289 DebugLoc dl = Op.getDebugLoc();
7290 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7291 /*isTarget=*/true, OpFlags);
7293 if (Subtarget->isPICStyleRIPRel() &&
7294 (M == CodeModel::Small || M == CodeModel::Kernel))
7295 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7297 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7299 // With PIC, the address is actually $g + Offset.
7300 if (isGlobalRelativeToPICBase(OpFlags)) {
7301 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7302 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7310 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7312 SelectionDAG &DAG) const {
7313 // Create the TargetGlobalAddress node, folding in the constant
7314 // offset if it is legal.
7315 unsigned char OpFlags =
7316 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7317 CodeModel::Model M = getTargetMachine().getCodeModel();
7319 if (OpFlags == X86II::MO_NO_FLAG &&
7320 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7321 // A direct static reference to a global.
7322 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7325 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7328 if (Subtarget->isPICStyleRIPRel() &&
7329 (M == CodeModel::Small || M == CodeModel::Kernel))
7330 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7332 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7334 // With PIC, the address is actually $g + Offset.
7335 if (isGlobalRelativeToPICBase(OpFlags)) {
7336 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7337 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7341 // For globals that require a load from a stub to get the address, emit the
7343 if (isGlobalStubReference(OpFlags))
7344 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7345 MachinePointerInfo::getGOT(), false, false, 0);
7347 // If there was a non-zero offset that we didn't fold, create an explicit
7350 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7351 DAG.getConstant(Offset, getPointerTy()));
7357 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7358 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7359 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7360 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7364 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7365 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7366 unsigned char OperandFlags) {
7367 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7368 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7369 DebugLoc dl = GA->getDebugLoc();
7370 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7371 GA->getValueType(0),
7375 SDValue Ops[] = { Chain, TGA, *InFlag };
7376 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7378 SDValue Ops[] = { Chain, TGA };
7379 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7382 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7383 MFI->setAdjustsStack(true);
7385 SDValue Flag = Chain.getValue(1);
7386 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7389 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7391 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7394 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7395 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7396 DAG.getNode(X86ISD::GlobalBaseReg,
7397 DebugLoc(), PtrVT), InFlag);
7398 InFlag = Chain.getValue(1);
7400 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7403 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7405 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7407 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7408 X86::RAX, X86II::MO_TLSGD);
7411 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7412 // "local exec" model.
7413 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7414 const EVT PtrVT, TLSModel::Model model,
7416 DebugLoc dl = GA->getDebugLoc();
7418 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7419 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7420 is64Bit ? 257 : 256));
7422 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7423 DAG.getIntPtrConstant(0),
7424 MachinePointerInfo(Ptr), false, false, 0);
7426 unsigned char OperandFlags = 0;
7427 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7429 unsigned WrapperKind = X86ISD::Wrapper;
7430 if (model == TLSModel::LocalExec) {
7431 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7432 } else if (is64Bit) {
7433 assert(model == TLSModel::InitialExec);
7434 OperandFlags = X86II::MO_GOTTPOFF;
7435 WrapperKind = X86ISD::WrapperRIP;
7437 assert(model == TLSModel::InitialExec);
7438 OperandFlags = X86II::MO_INDNTPOFF;
7441 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7443 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7444 GA->getValueType(0),
7445 GA->getOffset(), OperandFlags);
7446 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7448 if (model == TLSModel::InitialExec)
7449 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7450 MachinePointerInfo::getGOT(), false, false, 0);
7452 // The address of the thread local variable is the add of the thread
7453 // pointer with the offset of the variable.
7454 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7458 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7460 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7461 const GlobalValue *GV = GA->getGlobal();
7463 if (Subtarget->isTargetELF()) {
7464 // TODO: implement the "local dynamic" model
7465 // TODO: implement the "initial exec"model for pic executables
7467 // If GV is an alias then use the aliasee for determining
7468 // thread-localness.
7469 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7470 GV = GA->resolveAliasedGlobal(false);
7472 TLSModel::Model model
7473 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7476 case TLSModel::GeneralDynamic:
7477 case TLSModel::LocalDynamic: // not implemented
7478 if (Subtarget->is64Bit())
7479 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7480 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7482 case TLSModel::InitialExec:
7483 case TLSModel::LocalExec:
7484 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7485 Subtarget->is64Bit());
7487 } else if (Subtarget->isTargetDarwin()) {
7488 // Darwin only has one model of TLS. Lower to that.
7489 unsigned char OpFlag = 0;
7490 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7491 X86ISD::WrapperRIP : X86ISD::Wrapper;
7493 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7495 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7496 !Subtarget->is64Bit();
7498 OpFlag = X86II::MO_TLVP_PIC_BASE;
7500 OpFlag = X86II::MO_TLVP;
7501 DebugLoc DL = Op.getDebugLoc();
7502 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7503 GA->getValueType(0),
7504 GA->getOffset(), OpFlag);
7505 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7507 // With PIC32, the address is actually $g + Offset.
7509 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7510 DAG.getNode(X86ISD::GlobalBaseReg,
7511 DebugLoc(), getPointerTy()),
7514 // Lowering the machine isd will make sure everything is in the right
7516 SDValue Chain = DAG.getEntryNode();
7517 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7518 SDValue Args[] = { Chain, Offset };
7519 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7521 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7522 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7523 MFI->setAdjustsStack(true);
7525 // And our return value (tls address) is in the standard call return value
7527 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7528 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7532 "TLS not implemented for this target.");
7534 llvm_unreachable("Unreachable");
7539 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7540 /// take a 2 x i32 value to shift plus a shift amount.
7541 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7542 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7543 EVT VT = Op.getValueType();
7544 unsigned VTBits = VT.getSizeInBits();
7545 DebugLoc dl = Op.getDebugLoc();
7546 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7547 SDValue ShOpLo = Op.getOperand(0);
7548 SDValue ShOpHi = Op.getOperand(1);
7549 SDValue ShAmt = Op.getOperand(2);
7550 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7551 DAG.getConstant(VTBits - 1, MVT::i8))
7552 : DAG.getConstant(0, VT);
7555 if (Op.getOpcode() == ISD::SHL_PARTS) {
7556 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7557 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7559 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7560 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7563 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7564 DAG.getConstant(VTBits, MVT::i8));
7565 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7566 AndNode, DAG.getConstant(0, MVT::i8));
7569 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7570 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7571 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7573 if (Op.getOpcode() == ISD::SHL_PARTS) {
7574 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7575 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7577 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7578 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7581 SDValue Ops[2] = { Lo, Hi };
7582 return DAG.getMergeValues(Ops, 2, dl);
7585 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7586 SelectionDAG &DAG) const {
7587 EVT SrcVT = Op.getOperand(0).getValueType();
7589 if (SrcVT.isVector())
7592 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7593 "Unknown SINT_TO_FP to lower!");
7595 // These are really Legal; return the operand so the caller accepts it as
7597 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7599 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7600 Subtarget->is64Bit()) {
7604 DebugLoc dl = Op.getDebugLoc();
7605 unsigned Size = SrcVT.getSizeInBits()/8;
7606 MachineFunction &MF = DAG.getMachineFunction();
7607 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7608 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7609 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7611 MachinePointerInfo::getFixedStack(SSFI),
7613 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7616 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7618 SelectionDAG &DAG) const {
7620 DebugLoc DL = Op.getDebugLoc();
7622 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7624 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7626 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7628 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7630 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7631 MachineMemOperand *MMO;
7633 int SSFI = FI->getIndex();
7635 DAG.getMachineFunction()
7636 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7637 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7639 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7640 StackSlot = StackSlot.getOperand(1);
7642 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7643 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7645 Tys, Ops, array_lengthof(Ops),
7649 Chain = Result.getValue(1);
7650 SDValue InFlag = Result.getValue(2);
7652 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7653 // shouldn't be necessary except that RFP cannot be live across
7654 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7655 MachineFunction &MF = DAG.getMachineFunction();
7656 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7657 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7658 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7659 Tys = DAG.getVTList(MVT::Other);
7661 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7663 MachineMemOperand *MMO =
7664 DAG.getMachineFunction()
7665 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7666 MachineMemOperand::MOStore, SSFISize, SSFISize);
7668 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7669 Ops, array_lengthof(Ops),
7670 Op.getValueType(), MMO);
7671 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7672 MachinePointerInfo::getFixedStack(SSFI),
7679 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7680 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7681 SelectionDAG &DAG) const {
7682 // This algorithm is not obvious. Here it is in C code, more or less:
7684 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7685 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7686 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7688 // Copy ints to xmm registers.
7689 __m128i xh = _mm_cvtsi32_si128( hi );
7690 __m128i xl = _mm_cvtsi32_si128( lo );
7692 // Combine into low half of a single xmm register.
7693 __m128i x = _mm_unpacklo_epi32( xh, xl );
7697 // Merge in appropriate exponents to give the integer bits the right
7699 x = _mm_unpacklo_epi32( x, exp );
7701 // Subtract away the biases to deal with the IEEE-754 double precision
7703 d = _mm_sub_pd( (__m128d) x, bias );
7705 // All conversions up to here are exact. The correctly rounded result is
7706 // calculated using the current rounding mode using the following
7708 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7709 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7710 // store doesn't really need to be here (except
7711 // maybe to zero the other double)
7716 DebugLoc dl = Op.getDebugLoc();
7717 LLVMContext *Context = DAG.getContext();
7719 // Build some magic constants.
7720 std::vector<Constant*> CV0;
7721 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7722 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7723 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7724 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7725 Constant *C0 = ConstantVector::get(CV0);
7726 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7728 std::vector<Constant*> CV1;
7730 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7732 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7733 Constant *C1 = ConstantVector::get(CV1);
7734 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7736 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7737 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7739 DAG.getIntPtrConstant(1)));
7740 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7741 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7743 DAG.getIntPtrConstant(0)));
7744 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7745 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7746 MachinePointerInfo::getConstantPool(),
7748 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7749 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7750 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7751 MachinePointerInfo::getConstantPool(),
7753 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7755 // Add the halves; easiest way is to swap them into another reg first.
7756 int ShufMask[2] = { 1, -1 };
7757 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7758 DAG.getUNDEF(MVT::v2f64), ShufMask);
7759 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7760 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7761 DAG.getIntPtrConstant(0));
7764 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7765 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7766 SelectionDAG &DAG) const {
7767 DebugLoc dl = Op.getDebugLoc();
7768 // FP constant to bias correct the final result.
7769 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7772 // Load the 32-bit value into an XMM register.
7773 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7776 // Zero out the upper parts of the register.
7777 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7780 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7781 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7782 DAG.getIntPtrConstant(0));
7784 // Or the load with the bias.
7785 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7786 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7787 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7789 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7790 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7791 MVT::v2f64, Bias)));
7792 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7793 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7794 DAG.getIntPtrConstant(0));
7796 // Subtract the bias.
7797 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7799 // Handle final rounding.
7800 EVT DestVT = Op.getValueType();
7802 if (DestVT.bitsLT(MVT::f64)) {
7803 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7804 DAG.getIntPtrConstant(0));
7805 } else if (DestVT.bitsGT(MVT::f64)) {
7806 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7809 // Handle final rounding.
7813 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7814 SelectionDAG &DAG) const {
7815 SDValue N0 = Op.getOperand(0);
7816 DebugLoc dl = Op.getDebugLoc();
7818 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7819 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7820 // the optimization here.
7821 if (DAG.SignBitIsZero(N0))
7822 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7824 EVT SrcVT = N0.getValueType();
7825 EVT DstVT = Op.getValueType();
7826 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7827 return LowerUINT_TO_FP_i64(Op, DAG);
7828 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7829 return LowerUINT_TO_FP_i32(Op, DAG);
7831 // Make a 64-bit buffer, and use it to build an FILD.
7832 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7833 if (SrcVT == MVT::i32) {
7834 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7835 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7836 getPointerTy(), StackSlot, WordOff);
7837 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7838 StackSlot, MachinePointerInfo(),
7840 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7841 OffsetSlot, MachinePointerInfo(),
7843 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7847 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7848 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7849 StackSlot, MachinePointerInfo(),
7851 // For i64 source, we need to add the appropriate power of 2 if the input
7852 // was negative. This is the same as the optimization in
7853 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7854 // we must be careful to do the computation in x87 extended precision, not
7855 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7856 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7857 MachineMemOperand *MMO =
7858 DAG.getMachineFunction()
7859 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7860 MachineMemOperand::MOLoad, 8, 8);
7862 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7863 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7864 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7867 APInt FF(32, 0x5F800000ULL);
7869 // Check whether the sign bit is set.
7870 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7871 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7874 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7875 SDValue FudgePtr = DAG.getConstantPool(
7876 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7879 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7880 SDValue Zero = DAG.getIntPtrConstant(0);
7881 SDValue Four = DAG.getIntPtrConstant(4);
7882 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7884 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7886 // Load the value out, extending it from f32 to f80.
7887 // FIXME: Avoid the extend by constructing the right constant pool?
7888 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7889 FudgePtr, MachinePointerInfo::getConstantPool(),
7890 MVT::f32, false, false, 4);
7891 // Extend everything to 80 bits to force it to be done on x87.
7892 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7893 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7896 std::pair<SDValue,SDValue> X86TargetLowering::
7897 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7898 DebugLoc DL = Op.getDebugLoc();
7900 EVT DstTy = Op.getValueType();
7903 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7907 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7908 DstTy.getSimpleVT() >= MVT::i16 &&
7909 "Unknown FP_TO_SINT to lower!");
7911 // These are really Legal.
7912 if (DstTy == MVT::i32 &&
7913 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7914 return std::make_pair(SDValue(), SDValue());
7915 if (Subtarget->is64Bit() &&
7916 DstTy == MVT::i64 &&
7917 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7918 return std::make_pair(SDValue(), SDValue());
7920 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7922 MachineFunction &MF = DAG.getMachineFunction();
7923 unsigned MemSize = DstTy.getSizeInBits()/8;
7924 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7925 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7930 switch (DstTy.getSimpleVT().SimpleTy) {
7931 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7932 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7933 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7934 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7937 SDValue Chain = DAG.getEntryNode();
7938 SDValue Value = Op.getOperand(0);
7939 EVT TheVT = Op.getOperand(0).getValueType();
7940 if (isScalarFPTypeInSSEReg(TheVT)) {
7941 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7942 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7943 MachinePointerInfo::getFixedStack(SSFI),
7945 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7947 Chain, StackSlot, DAG.getValueType(TheVT)
7950 MachineMemOperand *MMO =
7951 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7952 MachineMemOperand::MOLoad, MemSize, MemSize);
7953 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7955 Chain = Value.getValue(1);
7956 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7957 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7960 MachineMemOperand *MMO =
7961 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7962 MachineMemOperand::MOStore, MemSize, MemSize);
7964 // Build the FP_TO_INT*_IN_MEM
7965 SDValue Ops[] = { Chain, Value, StackSlot };
7966 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7967 Ops, 3, DstTy, MMO);
7969 return std::make_pair(FIST, StackSlot);
7972 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7973 SelectionDAG &DAG) const {
7974 if (Op.getValueType().isVector())
7977 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7978 SDValue FIST = Vals.first, StackSlot = Vals.second;
7979 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7980 if (FIST.getNode() == 0) return Op;
7983 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7984 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7987 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7988 SelectionDAG &DAG) const {
7989 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7990 SDValue FIST = Vals.first, StackSlot = Vals.second;
7991 assert(FIST.getNode() && "Unexpected failure");
7994 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7995 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7998 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7999 SelectionDAG &DAG) const {
8000 LLVMContext *Context = DAG.getContext();
8001 DebugLoc dl = Op.getDebugLoc();
8002 EVT VT = Op.getValueType();
8005 EltVT = VT.getVectorElementType();
8006 std::vector<Constant*> CV;
8007 if (EltVT == MVT::f64) {
8008 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8012 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8018 Constant *C = ConstantVector::get(CV);
8019 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8020 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8021 MachinePointerInfo::getConstantPool(),
8023 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8026 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8027 LLVMContext *Context = DAG.getContext();
8028 DebugLoc dl = Op.getDebugLoc();
8029 EVT VT = Op.getValueType();
8032 EltVT = VT.getVectorElementType();
8033 std::vector<Constant*> CV;
8034 if (EltVT == MVT::f64) {
8035 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8039 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8045 Constant *C = ConstantVector::get(CV);
8046 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8047 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8048 MachinePointerInfo::getConstantPool(),
8050 if (VT.isVector()) {
8051 return DAG.getNode(ISD::BITCAST, dl, VT,
8052 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8053 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8055 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8057 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8061 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8062 LLVMContext *Context = DAG.getContext();
8063 SDValue Op0 = Op.getOperand(0);
8064 SDValue Op1 = Op.getOperand(1);
8065 DebugLoc dl = Op.getDebugLoc();
8066 EVT VT = Op.getValueType();
8067 EVT SrcVT = Op1.getValueType();
8069 // If second operand is smaller, extend it first.
8070 if (SrcVT.bitsLT(VT)) {
8071 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8074 // And if it is bigger, shrink it first.
8075 if (SrcVT.bitsGT(VT)) {
8076 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8080 // At this point the operands and the result should have the same
8081 // type, and that won't be f80 since that is not custom lowered.
8083 // First get the sign bit of second operand.
8084 std::vector<Constant*> CV;
8085 if (SrcVT == MVT::f64) {
8086 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8087 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8089 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8090 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8091 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8092 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8094 Constant *C = ConstantVector::get(CV);
8095 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8096 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8097 MachinePointerInfo::getConstantPool(),
8099 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8101 // Shift sign bit right or left if the two operands have different types.
8102 if (SrcVT.bitsGT(VT)) {
8103 // Op0 is MVT::f32, Op1 is MVT::f64.
8104 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8105 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8106 DAG.getConstant(32, MVT::i32));
8107 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8108 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8109 DAG.getIntPtrConstant(0));
8112 // Clear first operand sign bit.
8114 if (VT == MVT::f64) {
8115 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8116 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8118 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8119 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8120 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8121 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8123 C = ConstantVector::get(CV);
8124 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8125 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8126 MachinePointerInfo::getConstantPool(),
8128 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8130 // Or the value with the sign bit.
8131 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8134 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8135 SDValue N0 = Op.getOperand(0);
8136 DebugLoc dl = Op.getDebugLoc();
8137 EVT VT = Op.getValueType();
8139 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8140 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8141 DAG.getConstant(1, VT));
8142 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8145 /// Emit nodes that will be selected as "test Op0,Op0", or something
8147 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8148 SelectionDAG &DAG) const {
8149 DebugLoc dl = Op.getDebugLoc();
8151 // CF and OF aren't always set the way we want. Determine which
8152 // of these we need.
8153 bool NeedCF = false;
8154 bool NeedOF = false;
8157 case X86::COND_A: case X86::COND_AE:
8158 case X86::COND_B: case X86::COND_BE:
8161 case X86::COND_G: case X86::COND_GE:
8162 case X86::COND_L: case X86::COND_LE:
8163 case X86::COND_O: case X86::COND_NO:
8168 // See if we can use the EFLAGS value from the operand instead of
8169 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8170 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8171 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8172 // Emit a CMP with 0, which is the TEST pattern.
8173 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8174 DAG.getConstant(0, Op.getValueType()));
8176 unsigned Opcode = 0;
8177 unsigned NumOperands = 0;
8178 switch (Op.getNode()->getOpcode()) {
8180 // Due to an isel shortcoming, be conservative if this add is likely to be
8181 // selected as part of a load-modify-store instruction. When the root node
8182 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8183 // uses of other nodes in the match, such as the ADD in this case. This
8184 // leads to the ADD being left around and reselected, with the result being
8185 // two adds in the output. Alas, even if none our users are stores, that
8186 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8187 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8188 // climbing the DAG back to the root, and it doesn't seem to be worth the
8190 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8191 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8192 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8195 if (ConstantSDNode *C =
8196 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8197 // An add of one will be selected as an INC.
8198 if (C->getAPIntValue() == 1) {
8199 Opcode = X86ISD::INC;
8204 // An add of negative one (subtract of one) will be selected as a DEC.
8205 if (C->getAPIntValue().isAllOnesValue()) {
8206 Opcode = X86ISD::DEC;
8212 // Otherwise use a regular EFLAGS-setting add.
8213 Opcode = X86ISD::ADD;
8217 // If the primary and result isn't used, don't bother using X86ISD::AND,
8218 // because a TEST instruction will be better.
8219 bool NonFlagUse = false;
8220 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8221 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8223 unsigned UOpNo = UI.getOperandNo();
8224 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8225 // Look pass truncate.
8226 UOpNo = User->use_begin().getOperandNo();
8227 User = *User->use_begin();
8230 if (User->getOpcode() != ISD::BRCOND &&
8231 User->getOpcode() != ISD::SETCC &&
8232 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8245 // Due to the ISEL shortcoming noted above, be conservative if this op is
8246 // likely to be selected as part of a load-modify-store instruction.
8247 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8248 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8249 if (UI->getOpcode() == ISD::STORE)
8252 // Otherwise use a regular EFLAGS-setting instruction.
8253 switch (Op.getNode()->getOpcode()) {
8254 default: llvm_unreachable("unexpected operator!");
8255 case ISD::SUB: Opcode = X86ISD::SUB; break;
8256 case ISD::OR: Opcode = X86ISD::OR; break;
8257 case ISD::XOR: Opcode = X86ISD::XOR; break;
8258 case ISD::AND: Opcode = X86ISD::AND; break;
8270 return SDValue(Op.getNode(), 1);
8277 // Emit a CMP with 0, which is the TEST pattern.
8278 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8279 DAG.getConstant(0, Op.getValueType()));
8281 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8282 SmallVector<SDValue, 4> Ops;
8283 for (unsigned i = 0; i != NumOperands; ++i)
8284 Ops.push_back(Op.getOperand(i));
8286 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8287 DAG.ReplaceAllUsesWith(Op, New);
8288 return SDValue(New.getNode(), 1);
8291 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8293 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8294 SelectionDAG &DAG) const {
8295 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8296 if (C->getAPIntValue() == 0)
8297 return EmitTest(Op0, X86CC, DAG);
8299 DebugLoc dl = Op0.getDebugLoc();
8300 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8303 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8304 /// if it's possible.
8305 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8306 DebugLoc dl, SelectionDAG &DAG) const {
8307 SDValue Op0 = And.getOperand(0);
8308 SDValue Op1 = And.getOperand(1);
8309 if (Op0.getOpcode() == ISD::TRUNCATE)
8310 Op0 = Op0.getOperand(0);
8311 if (Op1.getOpcode() == ISD::TRUNCATE)
8312 Op1 = Op1.getOperand(0);
8315 if (Op1.getOpcode() == ISD::SHL)
8316 std::swap(Op0, Op1);
8317 if (Op0.getOpcode() == ISD::SHL) {
8318 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8319 if (And00C->getZExtValue() == 1) {
8320 // If we looked past a truncate, check that it's only truncating away
8322 unsigned BitWidth = Op0.getValueSizeInBits();
8323 unsigned AndBitWidth = And.getValueSizeInBits();
8324 if (BitWidth > AndBitWidth) {
8325 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8326 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8327 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8331 RHS = Op0.getOperand(1);
8333 } else if (Op1.getOpcode() == ISD::Constant) {
8334 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8335 SDValue AndLHS = Op0;
8336 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8337 LHS = AndLHS.getOperand(0);
8338 RHS = AndLHS.getOperand(1);
8342 if (LHS.getNode()) {
8343 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8344 // instruction. Since the shift amount is in-range-or-undefined, we know
8345 // that doing a bittest on the i32 value is ok. We extend to i32 because
8346 // the encoding for the i16 version is larger than the i32 version.
8347 // Also promote i16 to i32 for performance / code size reason.
8348 if (LHS.getValueType() == MVT::i8 ||
8349 LHS.getValueType() == MVT::i16)
8350 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8352 // If the operand types disagree, extend the shift amount to match. Since
8353 // BT ignores high bits (like shifts) we can use anyextend.
8354 if (LHS.getValueType() != RHS.getValueType())
8355 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8357 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8358 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8359 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8360 DAG.getConstant(Cond, MVT::i8), BT);
8366 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8368 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8370 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8371 SDValue Op0 = Op.getOperand(0);
8372 SDValue Op1 = Op.getOperand(1);
8373 DebugLoc dl = Op.getDebugLoc();
8374 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8376 // Optimize to BT if possible.
8377 // Lower (X & (1 << N)) == 0 to BT(X, N).
8378 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8379 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8380 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8381 Op1.getOpcode() == ISD::Constant &&
8382 cast<ConstantSDNode>(Op1)->isNullValue() &&
8383 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8384 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8385 if (NewSetCC.getNode())
8389 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8391 if (Op1.getOpcode() == ISD::Constant &&
8392 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8393 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8394 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8396 // If the input is a setcc, then reuse the input setcc or use a new one with
8397 // the inverted condition.
8398 if (Op0.getOpcode() == X86ISD::SETCC) {
8399 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8400 bool Invert = (CC == ISD::SETNE) ^
8401 cast<ConstantSDNode>(Op1)->isNullValue();
8402 if (!Invert) return Op0;
8404 CCode = X86::GetOppositeBranchCondition(CCode);
8405 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8406 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8410 bool isFP = Op1.getValueType().isFloatingPoint();
8411 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8412 if (X86CC == X86::COND_INVALID)
8415 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8416 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8417 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8420 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8421 // ones, and then concatenate the result back.
8422 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8423 EVT VT = Op.getValueType();
8425 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8426 "Unsupported value type for operation");
8428 int NumElems = VT.getVectorNumElements();
8429 DebugLoc dl = Op.getDebugLoc();
8430 SDValue CC = Op.getOperand(2);
8431 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8432 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8434 // Extract the LHS vectors
8435 SDValue LHS = Op.getOperand(0);
8436 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8437 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8439 // Extract the RHS vectors
8440 SDValue RHS = Op.getOperand(1);
8441 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8442 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8444 // Issue the operation on the smaller types and concatenate the result back
8445 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8446 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8447 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8448 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8449 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8453 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8455 SDValue Op0 = Op.getOperand(0);
8456 SDValue Op1 = Op.getOperand(1);
8457 SDValue CC = Op.getOperand(2);
8458 EVT VT = Op.getValueType();
8459 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8460 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8461 DebugLoc dl = Op.getDebugLoc();
8465 EVT EltVT = Op0.getValueType().getVectorElementType();
8466 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8468 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8471 // SSE Condition code mapping:
8480 switch (SetCCOpcode) {
8483 case ISD::SETEQ: SSECC = 0; break;
8485 case ISD::SETGT: Swap = true; // Fallthrough
8487 case ISD::SETOLT: SSECC = 1; break;
8489 case ISD::SETGE: Swap = true; // Fallthrough
8491 case ISD::SETOLE: SSECC = 2; break;
8492 case ISD::SETUO: SSECC = 3; break;
8494 case ISD::SETNE: SSECC = 4; break;
8495 case ISD::SETULE: Swap = true;
8496 case ISD::SETUGE: SSECC = 5; break;
8497 case ISD::SETULT: Swap = true;
8498 case ISD::SETUGT: SSECC = 6; break;
8499 case ISD::SETO: SSECC = 7; break;
8502 std::swap(Op0, Op1);
8504 // In the two special cases we can't handle, emit two comparisons.
8506 if (SetCCOpcode == ISD::SETUEQ) {
8508 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8509 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8510 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8512 else if (SetCCOpcode == ISD::SETONE) {
8514 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8515 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8516 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8518 llvm_unreachable("Illegal FP comparison");
8520 // Handle all other FP comparisons here.
8521 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8524 // Break 256-bit integer vector compare into smaller ones.
8525 if (!isFP && VT.getSizeInBits() == 256)
8526 return Lower256IntVSETCC(Op, DAG);
8528 // We are handling one of the integer comparisons here. Since SSE only has
8529 // GT and EQ comparisons for integer, swapping operands and multiple
8530 // operations may be required for some comparisons.
8531 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8532 bool Swap = false, Invert = false, FlipSigns = false;
8534 switch (VT.getSimpleVT().SimpleTy) {
8536 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8537 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8538 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8539 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8542 switch (SetCCOpcode) {
8544 case ISD::SETNE: Invert = true;
8545 case ISD::SETEQ: Opc = EQOpc; break;
8546 case ISD::SETLT: Swap = true;
8547 case ISD::SETGT: Opc = GTOpc; break;
8548 case ISD::SETGE: Swap = true;
8549 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8550 case ISD::SETULT: Swap = true;
8551 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8552 case ISD::SETUGE: Swap = true;
8553 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8556 std::swap(Op0, Op1);
8558 // Check that the operation in question is available (most are plain SSE2,
8559 // but PCMPGTQ and PCMPEQQ have different requirements).
8560 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8562 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8565 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8566 // bits of the inputs before performing those operations.
8568 EVT EltVT = VT.getVectorElementType();
8569 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8571 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8572 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8574 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8575 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8578 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8580 // If the logical-not of the result is required, perform that now.
8582 Result = DAG.getNOT(dl, Result, VT);
8587 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8588 static bool isX86LogicalCmp(SDValue Op) {
8589 unsigned Opc = Op.getNode()->getOpcode();
8590 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8592 if (Op.getResNo() == 1 &&
8593 (Opc == X86ISD::ADD ||
8594 Opc == X86ISD::SUB ||
8595 Opc == X86ISD::ADC ||
8596 Opc == X86ISD::SBB ||
8597 Opc == X86ISD::SMUL ||
8598 Opc == X86ISD::UMUL ||
8599 Opc == X86ISD::INC ||
8600 Opc == X86ISD::DEC ||
8601 Opc == X86ISD::OR ||
8602 Opc == X86ISD::XOR ||
8603 Opc == X86ISD::AND))
8606 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8612 static bool isZero(SDValue V) {
8613 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8614 return C && C->isNullValue();
8617 static bool isAllOnes(SDValue V) {
8618 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8619 return C && C->isAllOnesValue();
8622 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8623 bool addTest = true;
8624 SDValue Cond = Op.getOperand(0);
8625 SDValue Op1 = Op.getOperand(1);
8626 SDValue Op2 = Op.getOperand(2);
8627 DebugLoc DL = Op.getDebugLoc();
8630 if (Cond.getOpcode() == ISD::SETCC) {
8631 SDValue NewCond = LowerSETCC(Cond, DAG);
8632 if (NewCond.getNode())
8636 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8637 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8638 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8639 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8640 if (Cond.getOpcode() == X86ISD::SETCC &&
8641 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8642 isZero(Cond.getOperand(1).getOperand(1))) {
8643 SDValue Cmp = Cond.getOperand(1);
8645 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8647 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8648 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8649 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8651 SDValue CmpOp0 = Cmp.getOperand(0);
8652 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8653 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8655 SDValue Res = // Res = 0 or -1.
8656 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8657 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8659 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8660 Res = DAG.getNOT(DL, Res, Res.getValueType());
8662 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8663 if (N2C == 0 || !N2C->isNullValue())
8664 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8669 // Look past (and (setcc_carry (cmp ...)), 1).
8670 if (Cond.getOpcode() == ISD::AND &&
8671 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8672 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8673 if (C && C->getAPIntValue() == 1)
8674 Cond = Cond.getOperand(0);
8677 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8678 // setting operand in place of the X86ISD::SETCC.
8679 if (Cond.getOpcode() == X86ISD::SETCC ||
8680 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8681 CC = Cond.getOperand(0);
8683 SDValue Cmp = Cond.getOperand(1);
8684 unsigned Opc = Cmp.getOpcode();
8685 EVT VT = Op.getValueType();
8687 bool IllegalFPCMov = false;
8688 if (VT.isFloatingPoint() && !VT.isVector() &&
8689 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8690 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8692 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8693 Opc == X86ISD::BT) { // FIXME
8700 // Look pass the truncate.
8701 if (Cond.getOpcode() == ISD::TRUNCATE)
8702 Cond = Cond.getOperand(0);
8704 // We know the result of AND is compared against zero. Try to match
8706 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8707 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8708 if (NewSetCC.getNode()) {
8709 CC = NewSetCC.getOperand(0);
8710 Cond = NewSetCC.getOperand(1);
8717 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8718 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8721 // a < b ? -1 : 0 -> RES = ~setcc_carry
8722 // a < b ? 0 : -1 -> RES = setcc_carry
8723 // a >= b ? -1 : 0 -> RES = setcc_carry
8724 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8725 if (Cond.getOpcode() == X86ISD::CMP) {
8726 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8728 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8729 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8730 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8731 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8732 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8733 return DAG.getNOT(DL, Res, Res.getValueType());
8738 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8739 // condition is true.
8740 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8741 SDValue Ops[] = { Op2, Op1, CC, Cond };
8742 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8745 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8746 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8747 // from the AND / OR.
8748 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8749 Opc = Op.getOpcode();
8750 if (Opc != ISD::OR && Opc != ISD::AND)
8752 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8753 Op.getOperand(0).hasOneUse() &&
8754 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8755 Op.getOperand(1).hasOneUse());
8758 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8759 // 1 and that the SETCC node has a single use.
8760 static bool isXor1OfSetCC(SDValue Op) {
8761 if (Op.getOpcode() != ISD::XOR)
8763 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8764 if (N1C && N1C->getAPIntValue() == 1) {
8765 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8766 Op.getOperand(0).hasOneUse();
8771 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8772 bool addTest = true;
8773 SDValue Chain = Op.getOperand(0);
8774 SDValue Cond = Op.getOperand(1);
8775 SDValue Dest = Op.getOperand(2);
8776 DebugLoc dl = Op.getDebugLoc();
8779 if (Cond.getOpcode() == ISD::SETCC) {
8780 SDValue NewCond = LowerSETCC(Cond, DAG);
8781 if (NewCond.getNode())
8785 // FIXME: LowerXALUO doesn't handle these!!
8786 else if (Cond.getOpcode() == X86ISD::ADD ||
8787 Cond.getOpcode() == X86ISD::SUB ||
8788 Cond.getOpcode() == X86ISD::SMUL ||
8789 Cond.getOpcode() == X86ISD::UMUL)
8790 Cond = LowerXALUO(Cond, DAG);
8793 // Look pass (and (setcc_carry (cmp ...)), 1).
8794 if (Cond.getOpcode() == ISD::AND &&
8795 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8796 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8797 if (C && C->getAPIntValue() == 1)
8798 Cond = Cond.getOperand(0);
8801 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8802 // setting operand in place of the X86ISD::SETCC.
8803 if (Cond.getOpcode() == X86ISD::SETCC ||
8804 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8805 CC = Cond.getOperand(0);
8807 SDValue Cmp = Cond.getOperand(1);
8808 unsigned Opc = Cmp.getOpcode();
8809 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8810 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8814 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8818 // These can only come from an arithmetic instruction with overflow,
8819 // e.g. SADDO, UADDO.
8820 Cond = Cond.getNode()->getOperand(1);
8827 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8828 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8829 if (CondOpc == ISD::OR) {
8830 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8831 // two branches instead of an explicit OR instruction with a
8833 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8834 isX86LogicalCmp(Cmp)) {
8835 CC = Cond.getOperand(0).getOperand(0);
8836 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8837 Chain, Dest, CC, Cmp);
8838 CC = Cond.getOperand(1).getOperand(0);
8842 } else { // ISD::AND
8843 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8844 // two branches instead of an explicit AND instruction with a
8845 // separate test. However, we only do this if this block doesn't
8846 // have a fall-through edge, because this requires an explicit
8847 // jmp when the condition is false.
8848 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8849 isX86LogicalCmp(Cmp) &&
8850 Op.getNode()->hasOneUse()) {
8851 X86::CondCode CCode =
8852 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8853 CCode = X86::GetOppositeBranchCondition(CCode);
8854 CC = DAG.getConstant(CCode, MVT::i8);
8855 SDNode *User = *Op.getNode()->use_begin();
8856 // Look for an unconditional branch following this conditional branch.
8857 // We need this because we need to reverse the successors in order
8858 // to implement FCMP_OEQ.
8859 if (User->getOpcode() == ISD::BR) {
8860 SDValue FalseBB = User->getOperand(1);
8862 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8863 assert(NewBR == User);
8867 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8868 Chain, Dest, CC, Cmp);
8869 X86::CondCode CCode =
8870 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8871 CCode = X86::GetOppositeBranchCondition(CCode);
8872 CC = DAG.getConstant(CCode, MVT::i8);
8878 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8879 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8880 // It should be transformed during dag combiner except when the condition
8881 // is set by a arithmetics with overflow node.
8882 X86::CondCode CCode =
8883 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8884 CCode = X86::GetOppositeBranchCondition(CCode);
8885 CC = DAG.getConstant(CCode, MVT::i8);
8886 Cond = Cond.getOperand(0).getOperand(1);
8892 // Look pass the truncate.
8893 if (Cond.getOpcode() == ISD::TRUNCATE)
8894 Cond = Cond.getOperand(0);
8896 // We know the result of AND is compared against zero. Try to match
8898 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8899 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8900 if (NewSetCC.getNode()) {
8901 CC = NewSetCC.getOperand(0);
8902 Cond = NewSetCC.getOperand(1);
8909 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8910 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8912 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8913 Chain, Dest, CC, Cond);
8917 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8918 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8919 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8920 // that the guard pages used by the OS virtual memory manager are allocated in
8921 // correct sequence.
8923 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8924 SelectionDAG &DAG) const {
8925 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8926 EnableSegmentedStacks) &&
8927 "This should be used only on Windows targets or when segmented stacks "
8929 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8930 DebugLoc dl = Op.getDebugLoc();
8933 SDValue Chain = Op.getOperand(0);
8934 SDValue Size = Op.getOperand(1);
8935 // FIXME: Ensure alignment here
8937 bool Is64Bit = Subtarget->is64Bit();
8938 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8940 if (EnableSegmentedStacks) {
8941 MachineFunction &MF = DAG.getMachineFunction();
8942 MachineRegisterInfo &MRI = MF.getRegInfo();
8945 // The 64 bit implementation of segmented stacks needs to clobber both r10
8946 // r11. This makes it impossible to use it along with nested parameters.
8947 const Function *F = MF.getFunction();
8949 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8951 if (I->hasNestAttr())
8952 report_fatal_error("Cannot use segmented stacks with functions that "
8953 "have nested arguments.");
8956 const TargetRegisterClass *AddrRegClass =
8957 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8958 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8959 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8960 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8961 DAG.getRegister(Vreg, SPTy));
8962 SDValue Ops1[2] = { Value, Chain };
8963 return DAG.getMergeValues(Ops1, 2, dl);
8966 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8968 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8969 Flag = Chain.getValue(1);
8970 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8972 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8973 Flag = Chain.getValue(1);
8975 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8977 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8978 return DAG.getMergeValues(Ops1, 2, dl);
8982 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8983 MachineFunction &MF = DAG.getMachineFunction();
8984 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8986 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8987 DebugLoc DL = Op.getDebugLoc();
8989 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8990 // vastart just stores the address of the VarArgsFrameIndex slot into the
8991 // memory location argument.
8992 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8994 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8995 MachinePointerInfo(SV), false, false, 0);
8999 // gp_offset (0 - 6 * 8)
9000 // fp_offset (48 - 48 + 8 * 16)
9001 // overflow_arg_area (point to parameters coming in memory).
9003 SmallVector<SDValue, 8> MemOps;
9004 SDValue FIN = Op.getOperand(1);
9006 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9007 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9009 FIN, MachinePointerInfo(SV), false, false, 0);
9010 MemOps.push_back(Store);
9013 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9014 FIN, DAG.getIntPtrConstant(4));
9015 Store = DAG.getStore(Op.getOperand(0), DL,
9016 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9018 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9019 MemOps.push_back(Store);
9021 // Store ptr to overflow_arg_area
9022 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9023 FIN, DAG.getIntPtrConstant(4));
9024 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9026 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9027 MachinePointerInfo(SV, 8),
9029 MemOps.push_back(Store);
9031 // Store ptr to reg_save_area.
9032 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9033 FIN, DAG.getIntPtrConstant(8));
9034 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9036 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9037 MachinePointerInfo(SV, 16), false, false, 0);
9038 MemOps.push_back(Store);
9039 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9040 &MemOps[0], MemOps.size());
9043 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9044 assert(Subtarget->is64Bit() &&
9045 "LowerVAARG only handles 64-bit va_arg!");
9046 assert((Subtarget->isTargetLinux() ||
9047 Subtarget->isTargetDarwin()) &&
9048 "Unhandled target in LowerVAARG");
9049 assert(Op.getNode()->getNumOperands() == 4);
9050 SDValue Chain = Op.getOperand(0);
9051 SDValue SrcPtr = Op.getOperand(1);
9052 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9053 unsigned Align = Op.getConstantOperandVal(3);
9054 DebugLoc dl = Op.getDebugLoc();
9056 EVT ArgVT = Op.getNode()->getValueType(0);
9057 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9058 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9061 // Decide which area this value should be read from.
9062 // TODO: Implement the AMD64 ABI in its entirety. This simple
9063 // selection mechanism works only for the basic types.
9064 if (ArgVT == MVT::f80) {
9065 llvm_unreachable("va_arg for f80 not yet implemented");
9066 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9067 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9068 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9069 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9071 llvm_unreachable("Unhandled argument type in LowerVAARG");
9075 // Sanity Check: Make sure using fp_offset makes sense.
9076 assert(!UseSoftFloat &&
9077 !(DAG.getMachineFunction()
9078 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9079 Subtarget->hasXMM());
9082 // Insert VAARG_64 node into the DAG
9083 // VAARG_64 returns two values: Variable Argument Address, Chain
9084 SmallVector<SDValue, 11> InstOps;
9085 InstOps.push_back(Chain);
9086 InstOps.push_back(SrcPtr);
9087 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9088 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9089 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9090 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9091 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9092 VTs, &InstOps[0], InstOps.size(),
9094 MachinePointerInfo(SV),
9099 Chain = VAARG.getValue(1);
9101 // Load the next argument and return it
9102 return DAG.getLoad(ArgVT, dl,
9105 MachinePointerInfo(),
9109 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9110 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9111 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9112 SDValue Chain = Op.getOperand(0);
9113 SDValue DstPtr = Op.getOperand(1);
9114 SDValue SrcPtr = Op.getOperand(2);
9115 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9116 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9117 DebugLoc DL = Op.getDebugLoc();
9119 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9120 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9122 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9126 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9127 DebugLoc dl = Op.getDebugLoc();
9128 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9130 default: return SDValue(); // Don't custom lower most intrinsics.
9131 // Comparison intrinsics.
9132 case Intrinsic::x86_sse_comieq_ss:
9133 case Intrinsic::x86_sse_comilt_ss:
9134 case Intrinsic::x86_sse_comile_ss:
9135 case Intrinsic::x86_sse_comigt_ss:
9136 case Intrinsic::x86_sse_comige_ss:
9137 case Intrinsic::x86_sse_comineq_ss:
9138 case Intrinsic::x86_sse_ucomieq_ss:
9139 case Intrinsic::x86_sse_ucomilt_ss:
9140 case Intrinsic::x86_sse_ucomile_ss:
9141 case Intrinsic::x86_sse_ucomigt_ss:
9142 case Intrinsic::x86_sse_ucomige_ss:
9143 case Intrinsic::x86_sse_ucomineq_ss:
9144 case Intrinsic::x86_sse2_comieq_sd:
9145 case Intrinsic::x86_sse2_comilt_sd:
9146 case Intrinsic::x86_sse2_comile_sd:
9147 case Intrinsic::x86_sse2_comigt_sd:
9148 case Intrinsic::x86_sse2_comige_sd:
9149 case Intrinsic::x86_sse2_comineq_sd:
9150 case Intrinsic::x86_sse2_ucomieq_sd:
9151 case Intrinsic::x86_sse2_ucomilt_sd:
9152 case Intrinsic::x86_sse2_ucomile_sd:
9153 case Intrinsic::x86_sse2_ucomigt_sd:
9154 case Intrinsic::x86_sse2_ucomige_sd:
9155 case Intrinsic::x86_sse2_ucomineq_sd: {
9157 ISD::CondCode CC = ISD::SETCC_INVALID;
9160 case Intrinsic::x86_sse_comieq_ss:
9161 case Intrinsic::x86_sse2_comieq_sd:
9165 case Intrinsic::x86_sse_comilt_ss:
9166 case Intrinsic::x86_sse2_comilt_sd:
9170 case Intrinsic::x86_sse_comile_ss:
9171 case Intrinsic::x86_sse2_comile_sd:
9175 case Intrinsic::x86_sse_comigt_ss:
9176 case Intrinsic::x86_sse2_comigt_sd:
9180 case Intrinsic::x86_sse_comige_ss:
9181 case Intrinsic::x86_sse2_comige_sd:
9185 case Intrinsic::x86_sse_comineq_ss:
9186 case Intrinsic::x86_sse2_comineq_sd:
9190 case Intrinsic::x86_sse_ucomieq_ss:
9191 case Intrinsic::x86_sse2_ucomieq_sd:
9192 Opc = X86ISD::UCOMI;
9195 case Intrinsic::x86_sse_ucomilt_ss:
9196 case Intrinsic::x86_sse2_ucomilt_sd:
9197 Opc = X86ISD::UCOMI;
9200 case Intrinsic::x86_sse_ucomile_ss:
9201 case Intrinsic::x86_sse2_ucomile_sd:
9202 Opc = X86ISD::UCOMI;
9205 case Intrinsic::x86_sse_ucomigt_ss:
9206 case Intrinsic::x86_sse2_ucomigt_sd:
9207 Opc = X86ISD::UCOMI;
9210 case Intrinsic::x86_sse_ucomige_ss:
9211 case Intrinsic::x86_sse2_ucomige_sd:
9212 Opc = X86ISD::UCOMI;
9215 case Intrinsic::x86_sse_ucomineq_ss:
9216 case Intrinsic::x86_sse2_ucomineq_sd:
9217 Opc = X86ISD::UCOMI;
9222 SDValue LHS = Op.getOperand(1);
9223 SDValue RHS = Op.getOperand(2);
9224 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9225 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9226 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9227 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9228 DAG.getConstant(X86CC, MVT::i8), Cond);
9229 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9231 // Arithmetic intrinsics.
9232 case Intrinsic::x86_sse3_hadd_ps:
9233 case Intrinsic::x86_sse3_hadd_pd:
9234 case Intrinsic::x86_avx_hadd_ps_256:
9235 case Intrinsic::x86_avx_hadd_pd_256:
9236 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9237 Op.getOperand(1), Op.getOperand(2));
9238 case Intrinsic::x86_sse3_hsub_ps:
9239 case Intrinsic::x86_sse3_hsub_pd:
9240 case Intrinsic::x86_avx_hsub_ps_256:
9241 case Intrinsic::x86_avx_hsub_pd_256:
9242 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9243 Op.getOperand(1), Op.getOperand(2));
9244 // ptest and testp intrinsics. The intrinsic these come from are designed to
9245 // return an integer value, not just an instruction so lower it to the ptest
9246 // or testp pattern and a setcc for the result.
9247 case Intrinsic::x86_sse41_ptestz:
9248 case Intrinsic::x86_sse41_ptestc:
9249 case Intrinsic::x86_sse41_ptestnzc:
9250 case Intrinsic::x86_avx_ptestz_256:
9251 case Intrinsic::x86_avx_ptestc_256:
9252 case Intrinsic::x86_avx_ptestnzc_256:
9253 case Intrinsic::x86_avx_vtestz_ps:
9254 case Intrinsic::x86_avx_vtestc_ps:
9255 case Intrinsic::x86_avx_vtestnzc_ps:
9256 case Intrinsic::x86_avx_vtestz_pd:
9257 case Intrinsic::x86_avx_vtestc_pd:
9258 case Intrinsic::x86_avx_vtestnzc_pd:
9259 case Intrinsic::x86_avx_vtestz_ps_256:
9260 case Intrinsic::x86_avx_vtestc_ps_256:
9261 case Intrinsic::x86_avx_vtestnzc_ps_256:
9262 case Intrinsic::x86_avx_vtestz_pd_256:
9263 case Intrinsic::x86_avx_vtestc_pd_256:
9264 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9265 bool IsTestPacked = false;
9268 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9269 case Intrinsic::x86_avx_vtestz_ps:
9270 case Intrinsic::x86_avx_vtestz_pd:
9271 case Intrinsic::x86_avx_vtestz_ps_256:
9272 case Intrinsic::x86_avx_vtestz_pd_256:
9273 IsTestPacked = true; // Fallthrough
9274 case Intrinsic::x86_sse41_ptestz:
9275 case Intrinsic::x86_avx_ptestz_256:
9277 X86CC = X86::COND_E;
9279 case Intrinsic::x86_avx_vtestc_ps:
9280 case Intrinsic::x86_avx_vtestc_pd:
9281 case Intrinsic::x86_avx_vtestc_ps_256:
9282 case Intrinsic::x86_avx_vtestc_pd_256:
9283 IsTestPacked = true; // Fallthrough
9284 case Intrinsic::x86_sse41_ptestc:
9285 case Intrinsic::x86_avx_ptestc_256:
9287 X86CC = X86::COND_B;
9289 case Intrinsic::x86_avx_vtestnzc_ps:
9290 case Intrinsic::x86_avx_vtestnzc_pd:
9291 case Intrinsic::x86_avx_vtestnzc_ps_256:
9292 case Intrinsic::x86_avx_vtestnzc_pd_256:
9293 IsTestPacked = true; // Fallthrough
9294 case Intrinsic::x86_sse41_ptestnzc:
9295 case Intrinsic::x86_avx_ptestnzc_256:
9297 X86CC = X86::COND_A;
9301 SDValue LHS = Op.getOperand(1);
9302 SDValue RHS = Op.getOperand(2);
9303 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9304 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9305 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9306 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9307 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9310 // Fix vector shift instructions where the last operand is a non-immediate
9312 case Intrinsic::x86_sse2_pslli_w:
9313 case Intrinsic::x86_sse2_pslli_d:
9314 case Intrinsic::x86_sse2_pslli_q:
9315 case Intrinsic::x86_sse2_psrli_w:
9316 case Intrinsic::x86_sse2_psrli_d:
9317 case Intrinsic::x86_sse2_psrli_q:
9318 case Intrinsic::x86_sse2_psrai_w:
9319 case Intrinsic::x86_sse2_psrai_d:
9320 case Intrinsic::x86_mmx_pslli_w:
9321 case Intrinsic::x86_mmx_pslli_d:
9322 case Intrinsic::x86_mmx_pslli_q:
9323 case Intrinsic::x86_mmx_psrli_w:
9324 case Intrinsic::x86_mmx_psrli_d:
9325 case Intrinsic::x86_mmx_psrli_q:
9326 case Intrinsic::x86_mmx_psrai_w:
9327 case Intrinsic::x86_mmx_psrai_d: {
9328 SDValue ShAmt = Op.getOperand(2);
9329 if (isa<ConstantSDNode>(ShAmt))
9332 unsigned NewIntNo = 0;
9333 EVT ShAmtVT = MVT::v4i32;
9335 case Intrinsic::x86_sse2_pslli_w:
9336 NewIntNo = Intrinsic::x86_sse2_psll_w;
9338 case Intrinsic::x86_sse2_pslli_d:
9339 NewIntNo = Intrinsic::x86_sse2_psll_d;
9341 case Intrinsic::x86_sse2_pslli_q:
9342 NewIntNo = Intrinsic::x86_sse2_psll_q;
9344 case Intrinsic::x86_sse2_psrli_w:
9345 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9347 case Intrinsic::x86_sse2_psrli_d:
9348 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9350 case Intrinsic::x86_sse2_psrli_q:
9351 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9353 case Intrinsic::x86_sse2_psrai_w:
9354 NewIntNo = Intrinsic::x86_sse2_psra_w;
9356 case Intrinsic::x86_sse2_psrai_d:
9357 NewIntNo = Intrinsic::x86_sse2_psra_d;
9360 ShAmtVT = MVT::v2i32;
9362 case Intrinsic::x86_mmx_pslli_w:
9363 NewIntNo = Intrinsic::x86_mmx_psll_w;
9365 case Intrinsic::x86_mmx_pslli_d:
9366 NewIntNo = Intrinsic::x86_mmx_psll_d;
9368 case Intrinsic::x86_mmx_pslli_q:
9369 NewIntNo = Intrinsic::x86_mmx_psll_q;
9371 case Intrinsic::x86_mmx_psrli_w:
9372 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9374 case Intrinsic::x86_mmx_psrli_d:
9375 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9377 case Intrinsic::x86_mmx_psrli_q:
9378 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9380 case Intrinsic::x86_mmx_psrai_w:
9381 NewIntNo = Intrinsic::x86_mmx_psra_w;
9383 case Intrinsic::x86_mmx_psrai_d:
9384 NewIntNo = Intrinsic::x86_mmx_psra_d;
9386 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9392 // The vector shift intrinsics with scalars uses 32b shift amounts but
9393 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9397 ShOps[1] = DAG.getConstant(0, MVT::i32);
9398 if (ShAmtVT == MVT::v4i32) {
9399 ShOps[2] = DAG.getUNDEF(MVT::i32);
9400 ShOps[3] = DAG.getUNDEF(MVT::i32);
9401 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9403 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9404 // FIXME this must be lowered to get rid of the invalid type.
9407 EVT VT = Op.getValueType();
9408 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9409 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9410 DAG.getConstant(NewIntNo, MVT::i32),
9411 Op.getOperand(1), ShAmt);
9416 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9417 SelectionDAG &DAG) const {
9418 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9419 MFI->setReturnAddressIsTaken(true);
9421 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9422 DebugLoc dl = Op.getDebugLoc();
9425 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9427 DAG.getConstant(TD->getPointerSize(),
9428 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9429 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9430 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9432 MachinePointerInfo(), false, false, 0);
9435 // Just load the return address.
9436 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9437 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9438 RetAddrFI, MachinePointerInfo(), false, false, 0);
9441 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9442 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9443 MFI->setFrameAddressIsTaken(true);
9445 EVT VT = Op.getValueType();
9446 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9447 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9448 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9449 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9451 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9452 MachinePointerInfo(),
9457 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9458 SelectionDAG &DAG) const {
9459 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9462 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9463 MachineFunction &MF = DAG.getMachineFunction();
9464 SDValue Chain = Op.getOperand(0);
9465 SDValue Offset = Op.getOperand(1);
9466 SDValue Handler = Op.getOperand(2);
9467 DebugLoc dl = Op.getDebugLoc();
9469 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9470 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9472 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9474 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9475 DAG.getIntPtrConstant(TD->getPointerSize()));
9476 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9477 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9479 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9480 MF.getRegInfo().addLiveOut(StoreAddrReg);
9482 return DAG.getNode(X86ISD::EH_RETURN, dl,
9484 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9487 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9488 SelectionDAG &DAG) const {
9489 return Op.getOperand(0);
9492 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9493 SelectionDAG &DAG) const {
9494 SDValue Root = Op.getOperand(0);
9495 SDValue Trmp = Op.getOperand(1); // trampoline
9496 SDValue FPtr = Op.getOperand(2); // nested function
9497 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9498 DebugLoc dl = Op.getDebugLoc();
9500 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9502 if (Subtarget->is64Bit()) {
9503 SDValue OutChains[6];
9505 // Large code-model.
9506 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9507 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9509 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9510 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9512 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9514 // Load the pointer to the nested function into R11.
9515 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9516 SDValue Addr = Trmp;
9517 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9518 Addr, MachinePointerInfo(TrmpAddr),
9521 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9522 DAG.getConstant(2, MVT::i64));
9523 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9524 MachinePointerInfo(TrmpAddr, 2),
9527 // Load the 'nest' parameter value into R10.
9528 // R10 is specified in X86CallingConv.td
9529 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9530 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9531 DAG.getConstant(10, MVT::i64));
9532 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9533 Addr, MachinePointerInfo(TrmpAddr, 10),
9536 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9537 DAG.getConstant(12, MVT::i64));
9538 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9539 MachinePointerInfo(TrmpAddr, 12),
9542 // Jump to the nested function.
9543 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9544 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9545 DAG.getConstant(20, MVT::i64));
9546 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9547 Addr, MachinePointerInfo(TrmpAddr, 20),
9550 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9551 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9552 DAG.getConstant(22, MVT::i64));
9553 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9554 MachinePointerInfo(TrmpAddr, 22),
9557 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9559 const Function *Func =
9560 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9561 CallingConv::ID CC = Func->getCallingConv();
9566 llvm_unreachable("Unsupported calling convention");
9567 case CallingConv::C:
9568 case CallingConv::X86_StdCall: {
9569 // Pass 'nest' parameter in ECX.
9570 // Must be kept in sync with X86CallingConv.td
9573 // Check that ECX wasn't needed by an 'inreg' parameter.
9574 FunctionType *FTy = Func->getFunctionType();
9575 const AttrListPtr &Attrs = Func->getAttributes();
9577 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9578 unsigned InRegCount = 0;
9581 for (FunctionType::param_iterator I = FTy->param_begin(),
9582 E = FTy->param_end(); I != E; ++I, ++Idx)
9583 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9584 // FIXME: should only count parameters that are lowered to integers.
9585 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9587 if (InRegCount > 2) {
9588 report_fatal_error("Nest register in use - reduce number of inreg"
9594 case CallingConv::X86_FastCall:
9595 case CallingConv::X86_ThisCall:
9596 case CallingConv::Fast:
9597 // Pass 'nest' parameter in EAX.
9598 // Must be kept in sync with X86CallingConv.td
9603 SDValue OutChains[4];
9606 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9607 DAG.getConstant(10, MVT::i32));
9608 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9610 // This is storing the opcode for MOV32ri.
9611 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9612 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9613 OutChains[0] = DAG.getStore(Root, dl,
9614 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9615 Trmp, MachinePointerInfo(TrmpAddr),
9618 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9619 DAG.getConstant(1, MVT::i32));
9620 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9621 MachinePointerInfo(TrmpAddr, 1),
9624 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9625 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9626 DAG.getConstant(5, MVT::i32));
9627 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9628 MachinePointerInfo(TrmpAddr, 5),
9631 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9632 DAG.getConstant(6, MVT::i32));
9633 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9634 MachinePointerInfo(TrmpAddr, 6),
9637 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9641 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9642 SelectionDAG &DAG) const {
9644 The rounding mode is in bits 11:10 of FPSR, and has the following
9651 FLT_ROUNDS, on the other hand, expects the following:
9658 To perform the conversion, we do:
9659 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9662 MachineFunction &MF = DAG.getMachineFunction();
9663 const TargetMachine &TM = MF.getTarget();
9664 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9665 unsigned StackAlignment = TFI.getStackAlignment();
9666 EVT VT = Op.getValueType();
9667 DebugLoc DL = Op.getDebugLoc();
9669 // Save FP Control Word to stack slot
9670 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9671 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9674 MachineMemOperand *MMO =
9675 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9676 MachineMemOperand::MOStore, 2, 2);
9678 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9679 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9680 DAG.getVTList(MVT::Other),
9681 Ops, 2, MVT::i16, MMO);
9683 // Load FP Control Word from stack slot
9684 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9685 MachinePointerInfo(), false, false, 0);
9687 // Transform as necessary
9689 DAG.getNode(ISD::SRL, DL, MVT::i16,
9690 DAG.getNode(ISD::AND, DL, MVT::i16,
9691 CWD, DAG.getConstant(0x800, MVT::i16)),
9692 DAG.getConstant(11, MVT::i8));
9694 DAG.getNode(ISD::SRL, DL, MVT::i16,
9695 DAG.getNode(ISD::AND, DL, MVT::i16,
9696 CWD, DAG.getConstant(0x400, MVT::i16)),
9697 DAG.getConstant(9, MVT::i8));
9700 DAG.getNode(ISD::AND, DL, MVT::i16,
9701 DAG.getNode(ISD::ADD, DL, MVT::i16,
9702 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9703 DAG.getConstant(1, MVT::i16)),
9704 DAG.getConstant(3, MVT::i16));
9707 return DAG.getNode((VT.getSizeInBits() < 16 ?
9708 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9711 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9712 EVT VT = Op.getValueType();
9714 unsigned NumBits = VT.getSizeInBits();
9715 DebugLoc dl = Op.getDebugLoc();
9717 Op = Op.getOperand(0);
9718 if (VT == MVT::i8) {
9719 // Zero extend to i32 since there is not an i8 bsr.
9721 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9724 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9725 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9726 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9728 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9731 DAG.getConstant(NumBits+NumBits-1, OpVT),
9732 DAG.getConstant(X86::COND_E, MVT::i8),
9735 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9737 // Finally xor with NumBits-1.
9738 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9741 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9745 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9746 EVT VT = Op.getValueType();
9748 unsigned NumBits = VT.getSizeInBits();
9749 DebugLoc dl = Op.getDebugLoc();
9751 Op = Op.getOperand(0);
9752 if (VT == MVT::i8) {
9754 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9757 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9758 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9759 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9761 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9764 DAG.getConstant(NumBits, OpVT),
9765 DAG.getConstant(X86::COND_E, MVT::i8),
9768 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9771 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9775 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9776 // ones, and then concatenate the result back.
9777 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9778 EVT VT = Op.getValueType();
9780 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9781 "Unsupported value type for operation");
9783 int NumElems = VT.getVectorNumElements();
9784 DebugLoc dl = Op.getDebugLoc();
9785 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9786 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9788 // Extract the LHS vectors
9789 SDValue LHS = Op.getOperand(0);
9790 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9791 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9793 // Extract the RHS vectors
9794 SDValue RHS = Op.getOperand(1);
9795 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9796 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9798 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9799 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9801 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9802 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9803 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9806 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9807 assert(Op.getValueType().getSizeInBits() == 256 &&
9808 Op.getValueType().isInteger() &&
9809 "Only handle AVX 256-bit vector integer operation");
9810 return Lower256IntArith(Op, DAG);
9813 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9814 assert(Op.getValueType().getSizeInBits() == 256 &&
9815 Op.getValueType().isInteger() &&
9816 "Only handle AVX 256-bit vector integer operation");
9817 return Lower256IntArith(Op, DAG);
9820 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9821 EVT VT = Op.getValueType();
9823 // Decompose 256-bit ops into smaller 128-bit ops.
9824 if (VT.getSizeInBits() == 256)
9825 return Lower256IntArith(Op, DAG);
9827 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9828 DebugLoc dl = Op.getDebugLoc();
9830 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9831 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9832 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9833 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9834 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9836 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9837 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9838 // return AloBlo + AloBhi + AhiBlo;
9840 SDValue A = Op.getOperand(0);
9841 SDValue B = Op.getOperand(1);
9843 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9844 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9845 A, DAG.getConstant(32, MVT::i32));
9846 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9847 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9848 B, DAG.getConstant(32, MVT::i32));
9849 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9850 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9852 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9853 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9855 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9856 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9858 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9859 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9860 AloBhi, DAG.getConstant(32, MVT::i32));
9861 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9862 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9863 AhiBlo, DAG.getConstant(32, MVT::i32));
9864 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9865 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9869 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9871 EVT VT = Op.getValueType();
9872 DebugLoc dl = Op.getDebugLoc();
9873 SDValue R = Op.getOperand(0);
9874 SDValue Amt = Op.getOperand(1);
9875 LLVMContext *Context = DAG.getContext();
9877 if (!Subtarget->hasXMMInt())
9880 // Decompose 256-bit shifts into smaller 128-bit shifts.
9881 if (VT.getSizeInBits() == 256) {
9882 int NumElems = VT.getVectorNumElements();
9883 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9884 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9886 // Extract the two vectors
9887 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9888 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9891 // Recreate the shift amount vectors
9893 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9894 // Constant shift amount
9895 SmallVector<SDValue, 4> Amt1Csts;
9896 SmallVector<SDValue, 4> Amt2Csts;
9897 for (int i = 0; i < NumElems/2; ++i)
9898 Amt1Csts.push_back(Amt->getOperand(i));
9899 for (int i = NumElems/2; i < NumElems; ++i)
9900 Amt2Csts.push_back(Amt->getOperand(i));
9902 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9903 &Amt1Csts[0], NumElems/2);
9904 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9905 &Amt2Csts[0], NumElems/2);
9907 // Variable shift amount
9908 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9909 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9913 // Issue new vector shifts for the smaller types
9914 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9915 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9917 // Concatenate the result back
9918 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9921 // Optimize shl/srl/sra with constant shift amount.
9922 if (isSplatVector(Amt.getNode())) {
9923 SDValue SclrAmt = Amt->getOperand(0);
9924 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9925 uint64_t ShiftAmt = C->getZExtValue();
9927 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9928 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9929 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9930 R, DAG.getConstant(ShiftAmt, MVT::i32));
9932 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9933 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9934 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9935 R, DAG.getConstant(ShiftAmt, MVT::i32));
9937 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9938 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9939 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9940 R, DAG.getConstant(ShiftAmt, MVT::i32));
9942 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9943 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9944 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9945 R, DAG.getConstant(ShiftAmt, MVT::i32));
9947 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9948 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9949 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9950 R, DAG.getConstant(ShiftAmt, MVT::i32));
9952 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9953 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9954 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9955 R, DAG.getConstant(ShiftAmt, MVT::i32));
9957 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9958 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9959 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9960 R, DAG.getConstant(ShiftAmt, MVT::i32));
9962 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9963 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9964 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9965 R, DAG.getConstant(ShiftAmt, MVT::i32));
9969 // Lower SHL with variable shift amount.
9970 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9971 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9972 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9973 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9975 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9977 std::vector<Constant*> CV(4, CI);
9978 Constant *C = ConstantVector::get(CV);
9979 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9980 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9981 MachinePointerInfo::getConstantPool(),
9984 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9985 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9986 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9987 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9989 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9991 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9992 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9993 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9995 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9996 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9998 std::vector<Constant*> CVM1(16, CM1);
9999 std::vector<Constant*> CVM2(16, CM2);
10000 Constant *C = ConstantVector::get(CVM1);
10001 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10002 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10003 MachinePointerInfo::getConstantPool(),
10006 // r = pblendv(r, psllw(r & (char16)15, 4), a);
10007 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10008 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10009 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10010 DAG.getConstant(4, MVT::i32));
10011 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10013 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10015 C = ConstantVector::get(CVM2);
10016 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10017 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10018 MachinePointerInfo::getConstantPool(),
10021 // r = pblendv(r, psllw(r & (char16)63, 2), a);
10022 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10023 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10024 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10025 DAG.getConstant(2, MVT::i32));
10026 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10028 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10030 // return pblendv(r, r+r, a);
10031 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10032 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10038 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10039 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10040 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10041 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10042 // has only one use.
10043 SDNode *N = Op.getNode();
10044 SDValue LHS = N->getOperand(0);
10045 SDValue RHS = N->getOperand(1);
10046 unsigned BaseOp = 0;
10048 DebugLoc DL = Op.getDebugLoc();
10049 switch (Op.getOpcode()) {
10050 default: llvm_unreachable("Unknown ovf instruction!");
10052 // A subtract of one will be selected as a INC. Note that INC doesn't
10053 // set CF, so we can't do this for UADDO.
10054 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10056 BaseOp = X86ISD::INC;
10057 Cond = X86::COND_O;
10060 BaseOp = X86ISD::ADD;
10061 Cond = X86::COND_O;
10064 BaseOp = X86ISD::ADD;
10065 Cond = X86::COND_B;
10068 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10069 // set CF, so we can't do this for USUBO.
10070 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10072 BaseOp = X86ISD::DEC;
10073 Cond = X86::COND_O;
10076 BaseOp = X86ISD::SUB;
10077 Cond = X86::COND_O;
10080 BaseOp = X86ISD::SUB;
10081 Cond = X86::COND_B;
10084 BaseOp = X86ISD::SMUL;
10085 Cond = X86::COND_O;
10087 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10088 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10090 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10093 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10094 DAG.getConstant(X86::COND_O, MVT::i32),
10095 SDValue(Sum.getNode(), 2));
10097 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10101 // Also sets EFLAGS.
10102 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10103 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10106 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10107 DAG.getConstant(Cond, MVT::i32),
10108 SDValue(Sum.getNode(), 1));
10110 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10113 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10114 DebugLoc dl = Op.getDebugLoc();
10115 SDNode* Node = Op.getNode();
10116 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10117 EVT VT = Node->getValueType(0);
10118 if (Subtarget->hasXMMInt() && VT.isVector()) {
10119 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10120 ExtraVT.getScalarType().getSizeInBits();
10121 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10123 unsigned SHLIntrinsicsID = 0;
10124 unsigned SRAIntrinsicsID = 0;
10125 switch (VT.getSimpleVT().SimpleTy) {
10129 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
10130 SRAIntrinsicsID = 0;
10134 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10135 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10139 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10140 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10145 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10146 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10147 Node->getOperand(0), ShAmt);
10149 // In case of 1 bit sext, no need to shr
10150 if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10152 if (SRAIntrinsicsID) {
10153 Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10154 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10164 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10165 DebugLoc dl = Op.getDebugLoc();
10167 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10168 // There isn't any reason to disable it if the target processor supports it.
10169 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10170 SDValue Chain = Op.getOperand(0);
10171 SDValue Zero = DAG.getConstant(0, MVT::i32);
10173 DAG.getRegister(X86::ESP, MVT::i32), // Base
10174 DAG.getTargetConstant(1, MVT::i8), // Scale
10175 DAG.getRegister(0, MVT::i32), // Index
10176 DAG.getTargetConstant(0, MVT::i32), // Disp
10177 DAG.getRegister(0, MVT::i32), // Segment.
10182 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10183 array_lengthof(Ops));
10184 return SDValue(Res, 0);
10187 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10189 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10191 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10192 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10193 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10194 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10196 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10197 if (!Op1 && !Op2 && !Op3 && Op4)
10198 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10200 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10201 if (Op1 && !Op2 && !Op3 && !Op4)
10202 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10204 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10206 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10209 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10210 SelectionDAG &DAG) const {
10211 DebugLoc dl = Op.getDebugLoc();
10212 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10213 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10214 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10215 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10217 // The only fence that needs an instruction is a sequentially-consistent
10218 // cross-thread fence.
10219 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10220 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10221 // no-sse2). There isn't any reason to disable it if the target processor
10223 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10224 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10226 SDValue Chain = Op.getOperand(0);
10227 SDValue Zero = DAG.getConstant(0, MVT::i32);
10229 DAG.getRegister(X86::ESP, MVT::i32), // Base
10230 DAG.getTargetConstant(1, MVT::i8), // Scale
10231 DAG.getRegister(0, MVT::i32), // Index
10232 DAG.getTargetConstant(0, MVT::i32), // Disp
10233 DAG.getRegister(0, MVT::i32), // Segment.
10238 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10239 array_lengthof(Ops));
10240 return SDValue(Res, 0);
10243 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10244 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10248 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10249 EVT T = Op.getValueType();
10250 DebugLoc DL = Op.getDebugLoc();
10253 switch(T.getSimpleVT().SimpleTy) {
10255 assert(false && "Invalid value type!");
10256 case MVT::i8: Reg = X86::AL; size = 1; break;
10257 case MVT::i16: Reg = X86::AX; size = 2; break;
10258 case MVT::i32: Reg = X86::EAX; size = 4; break;
10260 assert(Subtarget->is64Bit() && "Node not type legal!");
10261 Reg = X86::RAX; size = 8;
10264 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10265 Op.getOperand(2), SDValue());
10266 SDValue Ops[] = { cpIn.getValue(0),
10269 DAG.getTargetConstant(size, MVT::i8),
10270 cpIn.getValue(1) };
10271 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10272 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10273 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10276 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10280 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10281 SelectionDAG &DAG) const {
10282 assert(Subtarget->is64Bit() && "Result not type legalized?");
10283 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10284 SDValue TheChain = Op.getOperand(0);
10285 DebugLoc dl = Op.getDebugLoc();
10286 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10287 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10288 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10290 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10291 DAG.getConstant(32, MVT::i8));
10293 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10296 return DAG.getMergeValues(Ops, 2, dl);
10299 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10300 SelectionDAG &DAG) const {
10301 EVT SrcVT = Op.getOperand(0).getValueType();
10302 EVT DstVT = Op.getValueType();
10303 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10304 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10305 assert((DstVT == MVT::i64 ||
10306 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10307 "Unexpected custom BITCAST");
10308 // i64 <=> MMX conversions are Legal.
10309 if (SrcVT==MVT::i64 && DstVT.isVector())
10311 if (DstVT==MVT::i64 && SrcVT.isVector())
10313 // MMX <=> MMX conversions are Legal.
10314 if (SrcVT.isVector() && DstVT.isVector())
10316 // All other conversions need to be expanded.
10320 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10321 SDNode *Node = Op.getNode();
10322 DebugLoc dl = Node->getDebugLoc();
10323 EVT T = Node->getValueType(0);
10324 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10325 DAG.getConstant(0, T), Node->getOperand(2));
10326 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10327 cast<AtomicSDNode>(Node)->getMemoryVT(),
10328 Node->getOperand(0),
10329 Node->getOperand(1), negOp,
10330 cast<AtomicSDNode>(Node)->getSrcValue(),
10331 cast<AtomicSDNode>(Node)->getAlignment(),
10332 cast<AtomicSDNode>(Node)->getOrdering(),
10333 cast<AtomicSDNode>(Node)->getSynchScope());
10336 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10337 SDNode *Node = Op.getNode();
10338 DebugLoc dl = Node->getDebugLoc();
10339 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10341 // Convert seq_cst store -> xchg
10342 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10343 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10344 // (The only way to get a 16-byte store is cmpxchg16b)
10345 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10346 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10347 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10348 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10349 cast<AtomicSDNode>(Node)->getMemoryVT(),
10350 Node->getOperand(0),
10351 Node->getOperand(1), Node->getOperand(2),
10352 cast<AtomicSDNode>(Node)->getMemOperand(),
10353 cast<AtomicSDNode>(Node)->getOrdering(),
10354 cast<AtomicSDNode>(Node)->getSynchScope());
10355 return Swap.getValue(1);
10357 // Other atomic stores have a simple pattern.
10361 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10362 EVT VT = Op.getNode()->getValueType(0);
10364 // Let legalize expand this if it isn't a legal type yet.
10365 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10368 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10371 bool ExtraOp = false;
10372 switch (Op.getOpcode()) {
10373 default: assert(0 && "Invalid code");
10374 case ISD::ADDC: Opc = X86ISD::ADD; break;
10375 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10376 case ISD::SUBC: Opc = X86ISD::SUB; break;
10377 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10381 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10383 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10384 Op.getOperand(1), Op.getOperand(2));
10387 /// LowerOperation - Provide custom lowering hooks for some operations.
10389 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10390 switch (Op.getOpcode()) {
10391 default: llvm_unreachable("Should not custom lower this!");
10392 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10393 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10394 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10395 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10396 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10397 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10398 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10399 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10400 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10401 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10402 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10403 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10404 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10405 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10406 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10407 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10408 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10409 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10410 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10411 case ISD::SHL_PARTS:
10412 case ISD::SRA_PARTS:
10413 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10414 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10415 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10416 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10417 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10418 case ISD::FABS: return LowerFABS(Op, DAG);
10419 case ISD::FNEG: return LowerFNEG(Op, DAG);
10420 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10421 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10422 case ISD::SETCC: return LowerSETCC(Op, DAG);
10423 case ISD::SELECT: return LowerSELECT(Op, DAG);
10424 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10425 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10426 case ISD::VASTART: return LowerVASTART(Op, DAG);
10427 case ISD::VAARG: return LowerVAARG(Op, DAG);
10428 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10429 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10430 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10431 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10432 case ISD::FRAME_TO_ARGS_OFFSET:
10433 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10434 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10435 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10436 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10437 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10438 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10439 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10440 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10441 case ISD::MUL: return LowerMUL(Op, DAG);
10444 case ISD::SHL: return LowerShift(Op, DAG);
10450 case ISD::UMULO: return LowerXALUO(Op, DAG);
10451 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10452 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10456 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10457 case ISD::ADD: return LowerADD(Op, DAG);
10458 case ISD::SUB: return LowerSUB(Op, DAG);
10462 static void ReplaceATOMIC_LOAD(SDNode *Node,
10463 SmallVectorImpl<SDValue> &Results,
10464 SelectionDAG &DAG) {
10465 DebugLoc dl = Node->getDebugLoc();
10466 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10468 // Convert wide load -> cmpxchg8b/cmpxchg16b
10469 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10470 // (The only way to get a 16-byte load is cmpxchg16b)
10471 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10472 SDValue Zero = DAG.getConstant(0, VT);
10473 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10474 Node->getOperand(0),
10475 Node->getOperand(1), Zero, Zero,
10476 cast<AtomicSDNode>(Node)->getMemOperand(),
10477 cast<AtomicSDNode>(Node)->getOrdering(),
10478 cast<AtomicSDNode>(Node)->getSynchScope());
10479 Results.push_back(Swap.getValue(0));
10480 Results.push_back(Swap.getValue(1));
10483 void X86TargetLowering::
10484 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10485 SelectionDAG &DAG, unsigned NewOp) const {
10486 EVT T = Node->getValueType(0);
10487 DebugLoc dl = Node->getDebugLoc();
10488 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10490 SDValue Chain = Node->getOperand(0);
10491 SDValue In1 = Node->getOperand(1);
10492 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10493 Node->getOperand(2), DAG.getIntPtrConstant(0));
10494 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10495 Node->getOperand(2), DAG.getIntPtrConstant(1));
10496 SDValue Ops[] = { Chain, In1, In2L, In2H };
10497 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10499 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10500 cast<MemSDNode>(Node)->getMemOperand());
10501 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10502 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10503 Results.push_back(Result.getValue(2));
10506 /// ReplaceNodeResults - Replace a node with an illegal result type
10507 /// with a new node built out of custom code.
10508 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10509 SmallVectorImpl<SDValue>&Results,
10510 SelectionDAG &DAG) const {
10511 DebugLoc dl = N->getDebugLoc();
10512 switch (N->getOpcode()) {
10514 assert(false && "Do not know how to custom type legalize this operation!");
10516 case ISD::SIGN_EXTEND_INREG:
10521 // We don't want to expand or promote these.
10523 case ISD::FP_TO_SINT: {
10524 std::pair<SDValue,SDValue> Vals =
10525 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10526 SDValue FIST = Vals.first, StackSlot = Vals.second;
10527 if (FIST.getNode() != 0) {
10528 EVT VT = N->getValueType(0);
10529 // Return a load from the stack slot.
10530 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10531 MachinePointerInfo(), false, false, 0));
10535 case ISD::READCYCLECOUNTER: {
10536 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10537 SDValue TheChain = N->getOperand(0);
10538 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10539 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10541 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10543 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10544 SDValue Ops[] = { eax, edx };
10545 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10546 Results.push_back(edx.getValue(1));
10549 case ISD::ATOMIC_CMP_SWAP: {
10550 EVT T = N->getValueType(0);
10551 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10552 bool Regs64bit = T == MVT::i128;
10553 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10554 SDValue cpInL, cpInH;
10555 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10556 DAG.getConstant(0, HalfT));
10557 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10558 DAG.getConstant(1, HalfT));
10559 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10560 Regs64bit ? X86::RAX : X86::EAX,
10562 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10563 Regs64bit ? X86::RDX : X86::EDX,
10564 cpInH, cpInL.getValue(1));
10565 SDValue swapInL, swapInH;
10566 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10567 DAG.getConstant(0, HalfT));
10568 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10569 DAG.getConstant(1, HalfT));
10570 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10571 Regs64bit ? X86::RBX : X86::EBX,
10572 swapInL, cpInH.getValue(1));
10573 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10574 Regs64bit ? X86::RCX : X86::ECX,
10575 swapInH, swapInL.getValue(1));
10576 SDValue Ops[] = { swapInH.getValue(0),
10578 swapInH.getValue(1) };
10579 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10580 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10581 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10582 X86ISD::LCMPXCHG8_DAG;
10583 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10585 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10586 Regs64bit ? X86::RAX : X86::EAX,
10587 HalfT, Result.getValue(1));
10588 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10589 Regs64bit ? X86::RDX : X86::EDX,
10590 HalfT, cpOutL.getValue(2));
10591 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10592 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10593 Results.push_back(cpOutH.getValue(1));
10596 case ISD::ATOMIC_LOAD_ADD:
10597 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10599 case ISD::ATOMIC_LOAD_AND:
10600 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10602 case ISD::ATOMIC_LOAD_NAND:
10603 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10605 case ISD::ATOMIC_LOAD_OR:
10606 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10608 case ISD::ATOMIC_LOAD_SUB:
10609 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10611 case ISD::ATOMIC_LOAD_XOR:
10612 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10614 case ISD::ATOMIC_SWAP:
10615 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10617 case ISD::ATOMIC_LOAD:
10618 ReplaceATOMIC_LOAD(N, Results, DAG);
10622 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10624 default: return NULL;
10625 case X86ISD::BSF: return "X86ISD::BSF";
10626 case X86ISD::BSR: return "X86ISD::BSR";
10627 case X86ISD::SHLD: return "X86ISD::SHLD";
10628 case X86ISD::SHRD: return "X86ISD::SHRD";
10629 case X86ISD::FAND: return "X86ISD::FAND";
10630 case X86ISD::FOR: return "X86ISD::FOR";
10631 case X86ISD::FXOR: return "X86ISD::FXOR";
10632 case X86ISD::FSRL: return "X86ISD::FSRL";
10633 case X86ISD::FILD: return "X86ISD::FILD";
10634 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10635 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10636 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10637 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10638 case X86ISD::FLD: return "X86ISD::FLD";
10639 case X86ISD::FST: return "X86ISD::FST";
10640 case X86ISD::CALL: return "X86ISD::CALL";
10641 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10642 case X86ISD::BT: return "X86ISD::BT";
10643 case X86ISD::CMP: return "X86ISD::CMP";
10644 case X86ISD::COMI: return "X86ISD::COMI";
10645 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10646 case X86ISD::SETCC: return "X86ISD::SETCC";
10647 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10648 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10649 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10650 case X86ISD::CMOV: return "X86ISD::CMOV";
10651 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10652 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10653 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10654 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10655 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10656 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10657 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10658 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10659 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10660 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10661 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10662 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10663 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10664 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10665 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
10666 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
10667 case X86ISD::PSIGND: return "X86ISD::PSIGND";
10668 case X86ISD::FMAX: return "X86ISD::FMAX";
10669 case X86ISD::FMIN: return "X86ISD::FMIN";
10670 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10671 case X86ISD::FRCP: return "X86ISD::FRCP";
10672 case X86ISD::FHADD: return "X86ISD::FHADD";
10673 case X86ISD::FHSUB: return "X86ISD::FHSUB";
10674 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10675 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10676 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10677 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10678 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10679 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10680 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10681 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10682 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10683 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10684 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10685 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10686 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10687 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10688 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10689 case X86ISD::VSHL: return "X86ISD::VSHL";
10690 case X86ISD::VSRL: return "X86ISD::VSRL";
10691 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10692 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10693 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10694 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10695 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10696 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10697 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10698 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10699 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10700 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10701 case X86ISD::ADD: return "X86ISD::ADD";
10702 case X86ISD::SUB: return "X86ISD::SUB";
10703 case X86ISD::ADC: return "X86ISD::ADC";
10704 case X86ISD::SBB: return "X86ISD::SBB";
10705 case X86ISD::SMUL: return "X86ISD::SMUL";
10706 case X86ISD::UMUL: return "X86ISD::UMUL";
10707 case X86ISD::INC: return "X86ISD::INC";
10708 case X86ISD::DEC: return "X86ISD::DEC";
10709 case X86ISD::OR: return "X86ISD::OR";
10710 case X86ISD::XOR: return "X86ISD::XOR";
10711 case X86ISD::AND: return "X86ISD::AND";
10712 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10713 case X86ISD::PTEST: return "X86ISD::PTEST";
10714 case X86ISD::TESTP: return "X86ISD::TESTP";
10715 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10716 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10717 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10718 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10719 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10720 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10721 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10722 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10723 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10724 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
10725 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
10726 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
10727 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
10728 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
10729 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
10730 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
10731 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
10732 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
10733 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
10734 case X86ISD::MOVSD: return "X86ISD::MOVSD";
10735 case X86ISD::MOVSS: return "X86ISD::MOVSS";
10736 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
10737 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
10738 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
10739 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
10740 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
10741 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
10742 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
10743 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
10744 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
10745 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
10746 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
10747 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
10748 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
10749 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
10750 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
10751 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY";
10752 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
10753 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY";
10754 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
10755 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10756 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
10757 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
10758 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
10759 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
10763 // isLegalAddressingMode - Return true if the addressing mode represented
10764 // by AM is legal for this target, for a load/store of the specified type.
10765 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10767 // X86 supports extremely general addressing modes.
10768 CodeModel::Model M = getTargetMachine().getCodeModel();
10769 Reloc::Model R = getTargetMachine().getRelocationModel();
10771 // X86 allows a sign-extended 32-bit immediate field as a displacement.
10772 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10777 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10779 // If a reference to this global requires an extra load, we can't fold it.
10780 if (isGlobalStubReference(GVFlags))
10783 // If BaseGV requires a register for the PIC base, we cannot also have a
10784 // BaseReg specified.
10785 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10788 // If lower 4G is not available, then we must use rip-relative addressing.
10789 if ((M != CodeModel::Small || R != Reloc::Static) &&
10790 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10794 switch (AM.Scale) {
10800 // These scales always work.
10805 // These scales are formed with basereg+scalereg. Only accept if there is
10810 default: // Other stuff never works.
10818 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10819 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10821 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10822 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10823 if (NumBits1 <= NumBits2)
10828 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10829 if (!VT1.isInteger() || !VT2.isInteger())
10831 unsigned NumBits1 = VT1.getSizeInBits();
10832 unsigned NumBits2 = VT2.getSizeInBits();
10833 if (NumBits1 <= NumBits2)
10838 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10839 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10840 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10843 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10844 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10845 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10848 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10849 // i16 instructions are longer (0x66 prefix) and potentially slower.
10850 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10853 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10854 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10855 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10856 /// are assumed to be legal.
10858 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10860 // Very little shuffling can be done for 64-bit vectors right now.
10861 if (VT.getSizeInBits() == 64)
10862 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
10864 // FIXME: pshufb, blends, shifts.
10865 return (VT.getVectorNumElements() == 2 ||
10866 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10867 isMOVLMask(M, VT) ||
10868 isSHUFPMask(M, VT) ||
10869 isPSHUFDMask(M, VT) ||
10870 isPSHUFHWMask(M, VT) ||
10871 isPSHUFLWMask(M, VT) ||
10872 isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
10873 isUNPCKLMask(M, VT) ||
10874 isUNPCKHMask(M, VT) ||
10875 isUNPCKL_v_undef_Mask(M, VT) ||
10876 isUNPCKH_v_undef_Mask(M, VT));
10880 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10882 unsigned NumElts = VT.getVectorNumElements();
10883 // FIXME: This collection of masks seems suspect.
10886 if (NumElts == 4 && VT.getSizeInBits() == 128) {
10887 return (isMOVLMask(Mask, VT) ||
10888 isCommutedMOVLMask(Mask, VT, true) ||
10889 isSHUFPMask(Mask, VT) ||
10890 isCommutedSHUFPMask(Mask, VT));
10895 //===----------------------------------------------------------------------===//
10896 // X86 Scheduler Hooks
10897 //===----------------------------------------------------------------------===//
10899 // private utility function
10900 MachineBasicBlock *
10901 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10902 MachineBasicBlock *MBB,
10909 TargetRegisterClass *RC,
10910 bool invSrc) const {
10911 // For the atomic bitwise operator, we generate
10914 // ld t1 = [bitinstr.addr]
10915 // op t2 = t1, [bitinstr.val]
10917 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
10919 // fallthrough -->nextMBB
10920 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10921 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10922 MachineFunction::iterator MBBIter = MBB;
10925 /// First build the CFG
10926 MachineFunction *F = MBB->getParent();
10927 MachineBasicBlock *thisMBB = MBB;
10928 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10929 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10930 F->insert(MBBIter, newMBB);
10931 F->insert(MBBIter, nextMBB);
10933 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10934 nextMBB->splice(nextMBB->begin(), thisMBB,
10935 llvm::next(MachineBasicBlock::iterator(bInstr)),
10937 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10939 // Update thisMBB to fall through to newMBB
10940 thisMBB->addSuccessor(newMBB);
10942 // newMBB jumps to itself and fall through to nextMBB
10943 newMBB->addSuccessor(nextMBB);
10944 newMBB->addSuccessor(newMBB);
10946 // Insert instructions into newMBB based on incoming instruction
10947 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10948 "unexpected number of operands");
10949 DebugLoc dl = bInstr->getDebugLoc();
10950 MachineOperand& destOper = bInstr->getOperand(0);
10951 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10952 int numArgs = bInstr->getNumOperands() - 1;
10953 for (int i=0; i < numArgs; ++i)
10954 argOpers[i] = &bInstr->getOperand(i+1);
10956 // x86 address has 4 operands: base, index, scale, and displacement
10957 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10958 int valArgIndx = lastAddrIndx + 1;
10960 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10961 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10962 for (int i=0; i <= lastAddrIndx; ++i)
10963 (*MIB).addOperand(*argOpers[i]);
10965 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10967 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10972 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10973 assert((argOpers[valArgIndx]->isReg() ||
10974 argOpers[valArgIndx]->isImm()) &&
10975 "invalid operand");
10976 if (argOpers[valArgIndx]->isReg())
10977 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10979 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10981 (*MIB).addOperand(*argOpers[valArgIndx]);
10983 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10986 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10987 for (int i=0; i <= lastAddrIndx; ++i)
10988 (*MIB).addOperand(*argOpers[i]);
10990 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10991 (*MIB).setMemRefs(bInstr->memoperands_begin(),
10992 bInstr->memoperands_end());
10994 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10995 MIB.addReg(EAXreg);
10998 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11000 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11004 // private utility function: 64 bit atomics on 32 bit host.
11005 MachineBasicBlock *
11006 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11007 MachineBasicBlock *MBB,
11012 bool invSrc) const {
11013 // For the atomic bitwise operator, we generate
11014 // thisMBB (instructions are in pairs, except cmpxchg8b)
11015 // ld t1,t2 = [bitinstr.addr]
11017 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11018 // op t5, t6 <- out1, out2, [bitinstr.val]
11019 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11020 // mov ECX, EBX <- t5, t6
11021 // mov EAX, EDX <- t1, t2
11022 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11023 // mov t3, t4 <- EAX, EDX
11025 // result in out1, out2
11026 // fallthrough -->nextMBB
11028 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11029 const unsigned LoadOpc = X86::MOV32rm;
11030 const unsigned NotOpc = X86::NOT32r;
11031 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11032 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11033 MachineFunction::iterator MBBIter = MBB;
11036 /// First build the CFG
11037 MachineFunction *F = MBB->getParent();
11038 MachineBasicBlock *thisMBB = MBB;
11039 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11040 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11041 F->insert(MBBIter, newMBB);
11042 F->insert(MBBIter, nextMBB);
11044 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11045 nextMBB->splice(nextMBB->begin(), thisMBB,
11046 llvm::next(MachineBasicBlock::iterator(bInstr)),
11048 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11050 // Update thisMBB to fall through to newMBB
11051 thisMBB->addSuccessor(newMBB);
11053 // newMBB jumps to itself and fall through to nextMBB
11054 newMBB->addSuccessor(nextMBB);
11055 newMBB->addSuccessor(newMBB);
11057 DebugLoc dl = bInstr->getDebugLoc();
11058 // Insert instructions into newMBB based on incoming instruction
11059 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11060 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11061 "unexpected number of operands");
11062 MachineOperand& dest1Oper = bInstr->getOperand(0);
11063 MachineOperand& dest2Oper = bInstr->getOperand(1);
11064 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11065 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11066 argOpers[i] = &bInstr->getOperand(i+2);
11068 // We use some of the operands multiple times, so conservatively just
11069 // clear any kill flags that might be present.
11070 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11071 argOpers[i]->setIsKill(false);
11074 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11075 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11077 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11078 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11079 for (int i=0; i <= lastAddrIndx; ++i)
11080 (*MIB).addOperand(*argOpers[i]);
11081 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11082 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11083 // add 4 to displacement.
11084 for (int i=0; i <= lastAddrIndx-2; ++i)
11085 (*MIB).addOperand(*argOpers[i]);
11086 MachineOperand newOp3 = *(argOpers[3]);
11087 if (newOp3.isImm())
11088 newOp3.setImm(newOp3.getImm()+4);
11090 newOp3.setOffset(newOp3.getOffset()+4);
11091 (*MIB).addOperand(newOp3);
11092 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11094 // t3/4 are defined later, at the bottom of the loop
11095 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11096 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11097 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11098 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11099 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11100 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11102 // The subsequent operations should be using the destination registers of
11103 //the PHI instructions.
11105 t1 = F->getRegInfo().createVirtualRegister(RC);
11106 t2 = F->getRegInfo().createVirtualRegister(RC);
11107 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11108 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11110 t1 = dest1Oper.getReg();
11111 t2 = dest2Oper.getReg();
11114 int valArgIndx = lastAddrIndx + 1;
11115 assert((argOpers[valArgIndx]->isReg() ||
11116 argOpers[valArgIndx]->isImm()) &&
11117 "invalid operand");
11118 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11119 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11120 if (argOpers[valArgIndx]->isReg())
11121 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11123 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11124 if (regOpcL != X86::MOV32rr)
11126 (*MIB).addOperand(*argOpers[valArgIndx]);
11127 assert(argOpers[valArgIndx + 1]->isReg() ==
11128 argOpers[valArgIndx]->isReg());
11129 assert(argOpers[valArgIndx + 1]->isImm() ==
11130 argOpers[valArgIndx]->isImm());
11131 if (argOpers[valArgIndx + 1]->isReg())
11132 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11134 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11135 if (regOpcH != X86::MOV32rr)
11137 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11139 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11141 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11144 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11146 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11149 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11150 for (int i=0; i <= lastAddrIndx; ++i)
11151 (*MIB).addOperand(*argOpers[i]);
11153 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11154 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11155 bInstr->memoperands_end());
11157 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11158 MIB.addReg(X86::EAX);
11159 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11160 MIB.addReg(X86::EDX);
11163 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11165 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11169 // private utility function
11170 MachineBasicBlock *
11171 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11172 MachineBasicBlock *MBB,
11173 unsigned cmovOpc) const {
11174 // For the atomic min/max operator, we generate
11177 // ld t1 = [min/max.addr]
11178 // mov t2 = [min/max.val]
11180 // cmov[cond] t2 = t1
11182 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11184 // fallthrough -->nextMBB
11186 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11187 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11188 MachineFunction::iterator MBBIter = MBB;
11191 /// First build the CFG
11192 MachineFunction *F = MBB->getParent();
11193 MachineBasicBlock *thisMBB = MBB;
11194 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11195 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11196 F->insert(MBBIter, newMBB);
11197 F->insert(MBBIter, nextMBB);
11199 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11200 nextMBB->splice(nextMBB->begin(), thisMBB,
11201 llvm::next(MachineBasicBlock::iterator(mInstr)),
11203 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11205 // Update thisMBB to fall through to newMBB
11206 thisMBB->addSuccessor(newMBB);
11208 // newMBB jumps to newMBB and fall through to nextMBB
11209 newMBB->addSuccessor(nextMBB);
11210 newMBB->addSuccessor(newMBB);
11212 DebugLoc dl = mInstr->getDebugLoc();
11213 // Insert instructions into newMBB based on incoming instruction
11214 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11215 "unexpected number of operands");
11216 MachineOperand& destOper = mInstr->getOperand(0);
11217 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11218 int numArgs = mInstr->getNumOperands() - 1;
11219 for (int i=0; i < numArgs; ++i)
11220 argOpers[i] = &mInstr->getOperand(i+1);
11222 // x86 address has 4 operands: base, index, scale, and displacement
11223 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11224 int valArgIndx = lastAddrIndx + 1;
11226 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11227 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11228 for (int i=0; i <= lastAddrIndx; ++i)
11229 (*MIB).addOperand(*argOpers[i]);
11231 // We only support register and immediate values
11232 assert((argOpers[valArgIndx]->isReg() ||
11233 argOpers[valArgIndx]->isImm()) &&
11234 "invalid operand");
11236 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11237 if (argOpers[valArgIndx]->isReg())
11238 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11240 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11241 (*MIB).addOperand(*argOpers[valArgIndx]);
11243 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11246 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11251 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11252 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11256 // Cmp and exchange if none has modified the memory location
11257 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11258 for (int i=0; i <= lastAddrIndx; ++i)
11259 (*MIB).addOperand(*argOpers[i]);
11261 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11262 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11263 mInstr->memoperands_end());
11265 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11266 MIB.addReg(X86::EAX);
11269 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11271 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11275 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11276 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11277 // in the .td file.
11278 MachineBasicBlock *
11279 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11280 unsigned numArgs, bool memArg) const {
11281 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11282 "Target must have SSE4.2 or AVX features enabled");
11284 DebugLoc dl = MI->getDebugLoc();
11285 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11287 if (!Subtarget->hasAVX()) {
11289 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11291 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11294 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11296 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11299 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11300 for (unsigned i = 0; i < numArgs; ++i) {
11301 MachineOperand &Op = MI->getOperand(i+1);
11302 if (!(Op.isReg() && Op.isImplicit()))
11303 MIB.addOperand(Op);
11305 BuildMI(*BB, MI, dl,
11306 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11307 MI->getOperand(0).getReg())
11308 .addReg(X86::XMM0);
11310 MI->eraseFromParent();
11314 MachineBasicBlock *
11315 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11316 DebugLoc dl = MI->getDebugLoc();
11317 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11319 // Address into RAX/EAX, other two args into ECX, EDX.
11320 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11321 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11322 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11323 for (int i = 0; i < X86::AddrNumOperands; ++i)
11324 MIB.addOperand(MI->getOperand(i));
11326 unsigned ValOps = X86::AddrNumOperands;
11327 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11328 .addReg(MI->getOperand(ValOps).getReg());
11329 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11330 .addReg(MI->getOperand(ValOps+1).getReg());
11332 // The instruction doesn't actually take any operands though.
11333 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11335 MI->eraseFromParent(); // The pseudo is gone now.
11339 MachineBasicBlock *
11340 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11341 DebugLoc dl = MI->getDebugLoc();
11342 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11344 // First arg in ECX, the second in EAX.
11345 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11346 .addReg(MI->getOperand(0).getReg());
11347 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11348 .addReg(MI->getOperand(1).getReg());
11350 // The instruction doesn't actually take any operands though.
11351 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11353 MI->eraseFromParent(); // The pseudo is gone now.
11357 MachineBasicBlock *
11358 X86TargetLowering::EmitVAARG64WithCustomInserter(
11360 MachineBasicBlock *MBB) const {
11361 // Emit va_arg instruction on X86-64.
11363 // Operands to this pseudo-instruction:
11364 // 0 ) Output : destination address (reg)
11365 // 1-5) Input : va_list address (addr, i64mem)
11366 // 6 ) ArgSize : Size (in bytes) of vararg type
11367 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11368 // 8 ) Align : Alignment of type
11369 // 9 ) EFLAGS (implicit-def)
11371 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11372 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11374 unsigned DestReg = MI->getOperand(0).getReg();
11375 MachineOperand &Base = MI->getOperand(1);
11376 MachineOperand &Scale = MI->getOperand(2);
11377 MachineOperand &Index = MI->getOperand(3);
11378 MachineOperand &Disp = MI->getOperand(4);
11379 MachineOperand &Segment = MI->getOperand(5);
11380 unsigned ArgSize = MI->getOperand(6).getImm();
11381 unsigned ArgMode = MI->getOperand(7).getImm();
11382 unsigned Align = MI->getOperand(8).getImm();
11384 // Memory Reference
11385 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11386 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11387 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11389 // Machine Information
11390 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11391 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11392 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11393 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11394 DebugLoc DL = MI->getDebugLoc();
11396 // struct va_list {
11399 // i64 overflow_area (address)
11400 // i64 reg_save_area (address)
11402 // sizeof(va_list) = 24
11403 // alignment(va_list) = 8
11405 unsigned TotalNumIntRegs = 6;
11406 unsigned TotalNumXMMRegs = 8;
11407 bool UseGPOffset = (ArgMode == 1);
11408 bool UseFPOffset = (ArgMode == 2);
11409 unsigned MaxOffset = TotalNumIntRegs * 8 +
11410 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11412 /* Align ArgSize to a multiple of 8 */
11413 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11414 bool NeedsAlign = (Align > 8);
11416 MachineBasicBlock *thisMBB = MBB;
11417 MachineBasicBlock *overflowMBB;
11418 MachineBasicBlock *offsetMBB;
11419 MachineBasicBlock *endMBB;
11421 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11422 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11423 unsigned OffsetReg = 0;
11425 if (!UseGPOffset && !UseFPOffset) {
11426 // If we only pull from the overflow region, we don't create a branch.
11427 // We don't need to alter control flow.
11428 OffsetDestReg = 0; // unused
11429 OverflowDestReg = DestReg;
11432 overflowMBB = thisMBB;
11435 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11436 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11437 // If not, pull from overflow_area. (branch to overflowMBB)
11442 // offsetMBB overflowMBB
11447 // Registers for the PHI in endMBB
11448 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11449 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11451 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11452 MachineFunction *MF = MBB->getParent();
11453 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11454 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11455 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11457 MachineFunction::iterator MBBIter = MBB;
11460 // Insert the new basic blocks
11461 MF->insert(MBBIter, offsetMBB);
11462 MF->insert(MBBIter, overflowMBB);
11463 MF->insert(MBBIter, endMBB);
11465 // Transfer the remainder of MBB and its successor edges to endMBB.
11466 endMBB->splice(endMBB->begin(), thisMBB,
11467 llvm::next(MachineBasicBlock::iterator(MI)),
11469 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11471 // Make offsetMBB and overflowMBB successors of thisMBB
11472 thisMBB->addSuccessor(offsetMBB);
11473 thisMBB->addSuccessor(overflowMBB);
11475 // endMBB is a successor of both offsetMBB and overflowMBB
11476 offsetMBB->addSuccessor(endMBB);
11477 overflowMBB->addSuccessor(endMBB);
11479 // Load the offset value into a register
11480 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11481 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11485 .addDisp(Disp, UseFPOffset ? 4 : 0)
11486 .addOperand(Segment)
11487 .setMemRefs(MMOBegin, MMOEnd);
11489 // Check if there is enough room left to pull this argument.
11490 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11492 .addImm(MaxOffset + 8 - ArgSizeA8);
11494 // Branch to "overflowMBB" if offset >= max
11495 // Fall through to "offsetMBB" otherwise
11496 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11497 .addMBB(overflowMBB);
11500 // In offsetMBB, emit code to use the reg_save_area.
11502 assert(OffsetReg != 0);
11504 // Read the reg_save_area address.
11505 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11506 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11511 .addOperand(Segment)
11512 .setMemRefs(MMOBegin, MMOEnd);
11514 // Zero-extend the offset
11515 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11516 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11519 .addImm(X86::sub_32bit);
11521 // Add the offset to the reg_save_area to get the final address.
11522 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11523 .addReg(OffsetReg64)
11524 .addReg(RegSaveReg);
11526 // Compute the offset for the next argument
11527 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11528 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11530 .addImm(UseFPOffset ? 16 : 8);
11532 // Store it back into the va_list.
11533 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11537 .addDisp(Disp, UseFPOffset ? 4 : 0)
11538 .addOperand(Segment)
11539 .addReg(NextOffsetReg)
11540 .setMemRefs(MMOBegin, MMOEnd);
11543 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11548 // Emit code to use overflow area
11551 // Load the overflow_area address into a register.
11552 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11553 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11558 .addOperand(Segment)
11559 .setMemRefs(MMOBegin, MMOEnd);
11561 // If we need to align it, do so. Otherwise, just copy the address
11562 // to OverflowDestReg.
11564 // Align the overflow address
11565 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11566 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11568 // aligned_addr = (addr + (align-1)) & ~(align-1)
11569 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11570 .addReg(OverflowAddrReg)
11573 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11575 .addImm(~(uint64_t)(Align-1));
11577 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11578 .addReg(OverflowAddrReg);
11581 // Compute the next overflow address after this argument.
11582 // (the overflow address should be kept 8-byte aligned)
11583 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11584 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11585 .addReg(OverflowDestReg)
11586 .addImm(ArgSizeA8);
11588 // Store the new overflow address.
11589 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11594 .addOperand(Segment)
11595 .addReg(NextAddrReg)
11596 .setMemRefs(MMOBegin, MMOEnd);
11598 // If we branched, emit the PHI to the front of endMBB.
11600 BuildMI(*endMBB, endMBB->begin(), DL,
11601 TII->get(X86::PHI), DestReg)
11602 .addReg(OffsetDestReg).addMBB(offsetMBB)
11603 .addReg(OverflowDestReg).addMBB(overflowMBB);
11606 // Erase the pseudo instruction
11607 MI->eraseFromParent();
11612 MachineBasicBlock *
11613 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11615 MachineBasicBlock *MBB) const {
11616 // Emit code to save XMM registers to the stack. The ABI says that the
11617 // number of registers to save is given in %al, so it's theoretically
11618 // possible to do an indirect jump trick to avoid saving all of them,
11619 // however this code takes a simpler approach and just executes all
11620 // of the stores if %al is non-zero. It's less code, and it's probably
11621 // easier on the hardware branch predictor, and stores aren't all that
11622 // expensive anyway.
11624 // Create the new basic blocks. One block contains all the XMM stores,
11625 // and one block is the final destination regardless of whether any
11626 // stores were performed.
11627 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11628 MachineFunction *F = MBB->getParent();
11629 MachineFunction::iterator MBBIter = MBB;
11631 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11632 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11633 F->insert(MBBIter, XMMSaveMBB);
11634 F->insert(MBBIter, EndMBB);
11636 // Transfer the remainder of MBB and its successor edges to EndMBB.
11637 EndMBB->splice(EndMBB->begin(), MBB,
11638 llvm::next(MachineBasicBlock::iterator(MI)),
11640 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11642 // The original block will now fall through to the XMM save block.
11643 MBB->addSuccessor(XMMSaveMBB);
11644 // The XMMSaveMBB will fall through to the end block.
11645 XMMSaveMBB->addSuccessor(EndMBB);
11647 // Now add the instructions.
11648 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11649 DebugLoc DL = MI->getDebugLoc();
11651 unsigned CountReg = MI->getOperand(0).getReg();
11652 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11653 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11655 if (!Subtarget->isTargetWin64()) {
11656 // If %al is 0, branch around the XMM save block.
11657 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11658 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11659 MBB->addSuccessor(EndMBB);
11662 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11663 // In the XMM save block, save all the XMM argument registers.
11664 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11665 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11666 MachineMemOperand *MMO =
11667 F->getMachineMemOperand(
11668 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11669 MachineMemOperand::MOStore,
11670 /*Size=*/16, /*Align=*/16);
11671 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11672 .addFrameIndex(RegSaveFrameIndex)
11673 .addImm(/*Scale=*/1)
11674 .addReg(/*IndexReg=*/0)
11675 .addImm(/*Disp=*/Offset)
11676 .addReg(/*Segment=*/0)
11677 .addReg(MI->getOperand(i).getReg())
11678 .addMemOperand(MMO);
11681 MI->eraseFromParent(); // The pseudo instruction is gone now.
11686 MachineBasicBlock *
11687 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11688 MachineBasicBlock *BB) const {
11689 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11690 DebugLoc DL = MI->getDebugLoc();
11692 // To "insert" a SELECT_CC instruction, we actually have to insert the
11693 // diamond control-flow pattern. The incoming instruction knows the
11694 // destination vreg to set, the condition code register to branch on, the
11695 // true/false values to select between, and a branch opcode to use.
11696 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11697 MachineFunction::iterator It = BB;
11703 // cmpTY ccX, r1, r2
11705 // fallthrough --> copy0MBB
11706 MachineBasicBlock *thisMBB = BB;
11707 MachineFunction *F = BB->getParent();
11708 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11709 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11710 F->insert(It, copy0MBB);
11711 F->insert(It, sinkMBB);
11713 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11714 // live into the sink and copy blocks.
11715 if (!MI->killsRegister(X86::EFLAGS)) {
11716 copy0MBB->addLiveIn(X86::EFLAGS);
11717 sinkMBB->addLiveIn(X86::EFLAGS);
11720 // Transfer the remainder of BB and its successor edges to sinkMBB.
11721 sinkMBB->splice(sinkMBB->begin(), BB,
11722 llvm::next(MachineBasicBlock::iterator(MI)),
11724 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11726 // Add the true and fallthrough blocks as its successors.
11727 BB->addSuccessor(copy0MBB);
11728 BB->addSuccessor(sinkMBB);
11730 // Create the conditional branch instruction.
11732 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11733 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11736 // %FalseValue = ...
11737 // # fallthrough to sinkMBB
11738 copy0MBB->addSuccessor(sinkMBB);
11741 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11743 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11744 TII->get(X86::PHI), MI->getOperand(0).getReg())
11745 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11746 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11748 MI->eraseFromParent(); // The pseudo instruction is gone now.
11752 MachineBasicBlock *
11753 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11754 bool Is64Bit) const {
11755 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11756 DebugLoc DL = MI->getDebugLoc();
11757 MachineFunction *MF = BB->getParent();
11758 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11760 assert(EnableSegmentedStacks);
11762 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11763 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11766 // ... [Till the alloca]
11767 // If stacklet is not large enough, jump to mallocMBB
11770 // Allocate by subtracting from RSP
11771 // Jump to continueMBB
11774 // Allocate by call to runtime
11778 // [rest of original BB]
11781 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11782 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11783 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11785 MachineRegisterInfo &MRI = MF->getRegInfo();
11786 const TargetRegisterClass *AddrRegClass =
11787 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11789 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11790 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11791 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11792 sizeVReg = MI->getOperand(1).getReg(),
11793 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11795 MachineFunction::iterator MBBIter = BB;
11798 MF->insert(MBBIter, bumpMBB);
11799 MF->insert(MBBIter, mallocMBB);
11800 MF->insert(MBBIter, continueMBB);
11802 continueMBB->splice(continueMBB->begin(), BB, llvm::next
11803 (MachineBasicBlock::iterator(MI)), BB->end());
11804 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11806 // Add code to the main basic block to check if the stack limit has been hit,
11807 // and if so, jump to mallocMBB otherwise to bumpMBB.
11808 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11809 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11810 .addReg(tmpSPVReg).addReg(sizeVReg);
11811 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11812 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11813 .addReg(tmpSPVReg);
11814 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11816 // bumpMBB simply decreases the stack pointer, since we know the current
11817 // stacklet has enough space.
11818 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11819 .addReg(tmpSPVReg);
11820 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11821 .addReg(tmpSPVReg);
11822 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11824 // Calls into a routine in libgcc to allocate more space from the heap.
11826 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11828 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11829 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11831 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11833 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11834 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11835 .addExternalSymbol("__morestack_allocate_stack_space");
11839 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11842 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11843 .addReg(Is64Bit ? X86::RAX : X86::EAX);
11844 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11846 // Set up the CFG correctly.
11847 BB->addSuccessor(bumpMBB);
11848 BB->addSuccessor(mallocMBB);
11849 mallocMBB->addSuccessor(continueMBB);
11850 bumpMBB->addSuccessor(continueMBB);
11852 // Take care of the PHI nodes.
11853 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11854 MI->getOperand(0).getReg())
11855 .addReg(mallocPtrVReg).addMBB(mallocMBB)
11856 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11858 // Delete the original pseudo instruction.
11859 MI->eraseFromParent();
11862 return continueMBB;
11865 MachineBasicBlock *
11866 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11867 MachineBasicBlock *BB) const {
11868 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11869 DebugLoc DL = MI->getDebugLoc();
11871 assert(!Subtarget->isTargetEnvMacho());
11873 // The lowering is pretty easy: we're just emitting the call to _alloca. The
11874 // non-trivial part is impdef of ESP.
11876 if (Subtarget->isTargetWin64()) {
11877 if (Subtarget->isTargetCygMing()) {
11878 // ___chkstk(Mingw64):
11879 // Clobbers R10, R11, RAX and EFLAGS.
11881 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11882 .addExternalSymbol("___chkstk")
11883 .addReg(X86::RAX, RegState::Implicit)
11884 .addReg(X86::RSP, RegState::Implicit)
11885 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11886 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11887 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11889 // __chkstk(MSVCRT): does not update stack pointer.
11890 // Clobbers R10, R11 and EFLAGS.
11891 // FIXME: RAX(allocated size) might be reused and not killed.
11892 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11893 .addExternalSymbol("__chkstk")
11894 .addReg(X86::RAX, RegState::Implicit)
11895 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11896 // RAX has the offset to subtracted from RSP.
11897 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11902 const char *StackProbeSymbol =
11903 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11905 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11906 .addExternalSymbol(StackProbeSymbol)
11907 .addReg(X86::EAX, RegState::Implicit)
11908 .addReg(X86::ESP, RegState::Implicit)
11909 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11910 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11911 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11914 MI->eraseFromParent(); // The pseudo instruction is gone now.
11918 MachineBasicBlock *
11919 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11920 MachineBasicBlock *BB) const {
11921 // This is pretty easy. We're taking the value that we received from
11922 // our load from the relocation, sticking it in either RDI (x86-64)
11923 // or EAX and doing an indirect call. The return value will then
11924 // be in the normal return register.
11925 const X86InstrInfo *TII
11926 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11927 DebugLoc DL = MI->getDebugLoc();
11928 MachineFunction *F = BB->getParent();
11930 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11931 assert(MI->getOperand(3).isGlobal() && "This should be a global");
11933 if (Subtarget->is64Bit()) {
11934 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11935 TII->get(X86::MOV64rm), X86::RDI)
11937 .addImm(0).addReg(0)
11938 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11939 MI->getOperand(3).getTargetFlags())
11941 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11942 addDirectMem(MIB, X86::RDI);
11943 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11944 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11945 TII->get(X86::MOV32rm), X86::EAX)
11947 .addImm(0).addReg(0)
11948 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11949 MI->getOperand(3).getTargetFlags())
11951 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11952 addDirectMem(MIB, X86::EAX);
11954 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11955 TII->get(X86::MOV32rm), X86::EAX)
11956 .addReg(TII->getGlobalBaseReg(F))
11957 .addImm(0).addReg(0)
11958 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11959 MI->getOperand(3).getTargetFlags())
11961 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11962 addDirectMem(MIB, X86::EAX);
11965 MI->eraseFromParent(); // The pseudo instruction is gone now.
11969 MachineBasicBlock *
11970 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11971 MachineBasicBlock *BB) const {
11972 switch (MI->getOpcode()) {
11973 default: assert(0 && "Unexpected instr type to insert");
11974 case X86::TAILJMPd64:
11975 case X86::TAILJMPr64:
11976 case X86::TAILJMPm64:
11977 assert(0 && "TAILJMP64 would not be touched here.");
11978 case X86::TCRETURNdi64:
11979 case X86::TCRETURNri64:
11980 case X86::TCRETURNmi64:
11981 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11982 // On AMD64, additional defs should be added before register allocation.
11983 if (!Subtarget->isTargetWin64()) {
11984 MI->addRegisterDefined(X86::RSI);
11985 MI->addRegisterDefined(X86::RDI);
11986 MI->addRegisterDefined(X86::XMM6);
11987 MI->addRegisterDefined(X86::XMM7);
11988 MI->addRegisterDefined(X86::XMM8);
11989 MI->addRegisterDefined(X86::XMM9);
11990 MI->addRegisterDefined(X86::XMM10);
11991 MI->addRegisterDefined(X86::XMM11);
11992 MI->addRegisterDefined(X86::XMM12);
11993 MI->addRegisterDefined(X86::XMM13);
11994 MI->addRegisterDefined(X86::XMM14);
11995 MI->addRegisterDefined(X86::XMM15);
11998 case X86::WIN_ALLOCA:
11999 return EmitLoweredWinAlloca(MI, BB);
12000 case X86::SEG_ALLOCA_32:
12001 return EmitLoweredSegAlloca(MI, BB, false);
12002 case X86::SEG_ALLOCA_64:
12003 return EmitLoweredSegAlloca(MI, BB, true);
12004 case X86::TLSCall_32:
12005 case X86::TLSCall_64:
12006 return EmitLoweredTLSCall(MI, BB);
12007 case X86::CMOV_GR8:
12008 case X86::CMOV_FR32:
12009 case X86::CMOV_FR64:
12010 case X86::CMOV_V4F32:
12011 case X86::CMOV_V2F64:
12012 case X86::CMOV_V2I64:
12013 case X86::CMOV_V8F32:
12014 case X86::CMOV_V4F64:
12015 case X86::CMOV_V4I64:
12016 case X86::CMOV_GR16:
12017 case X86::CMOV_GR32:
12018 case X86::CMOV_RFP32:
12019 case X86::CMOV_RFP64:
12020 case X86::CMOV_RFP80:
12021 return EmitLoweredSelect(MI, BB);
12023 case X86::FP32_TO_INT16_IN_MEM:
12024 case X86::FP32_TO_INT32_IN_MEM:
12025 case X86::FP32_TO_INT64_IN_MEM:
12026 case X86::FP64_TO_INT16_IN_MEM:
12027 case X86::FP64_TO_INT32_IN_MEM:
12028 case X86::FP64_TO_INT64_IN_MEM:
12029 case X86::FP80_TO_INT16_IN_MEM:
12030 case X86::FP80_TO_INT32_IN_MEM:
12031 case X86::FP80_TO_INT64_IN_MEM: {
12032 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12033 DebugLoc DL = MI->getDebugLoc();
12035 // Change the floating point control register to use "round towards zero"
12036 // mode when truncating to an integer value.
12037 MachineFunction *F = BB->getParent();
12038 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12039 addFrameReference(BuildMI(*BB, MI, DL,
12040 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12042 // Load the old value of the high byte of the control word...
12044 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12045 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12048 // Set the high part to be round to zero...
12049 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12052 // Reload the modified control word now...
12053 addFrameReference(BuildMI(*BB, MI, DL,
12054 TII->get(X86::FLDCW16m)), CWFrameIdx);
12056 // Restore the memory image of control word to original value
12057 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12060 // Get the X86 opcode to use.
12062 switch (MI->getOpcode()) {
12063 default: llvm_unreachable("illegal opcode!");
12064 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12065 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12066 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12067 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12068 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12069 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12070 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12071 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12072 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12076 MachineOperand &Op = MI->getOperand(0);
12078 AM.BaseType = X86AddressMode::RegBase;
12079 AM.Base.Reg = Op.getReg();
12081 AM.BaseType = X86AddressMode::FrameIndexBase;
12082 AM.Base.FrameIndex = Op.getIndex();
12084 Op = MI->getOperand(1);
12086 AM.Scale = Op.getImm();
12087 Op = MI->getOperand(2);
12089 AM.IndexReg = Op.getImm();
12090 Op = MI->getOperand(3);
12091 if (Op.isGlobal()) {
12092 AM.GV = Op.getGlobal();
12094 AM.Disp = Op.getImm();
12096 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12097 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12099 // Reload the original control word now.
12100 addFrameReference(BuildMI(*BB, MI, DL,
12101 TII->get(X86::FLDCW16m)), CWFrameIdx);
12103 MI->eraseFromParent(); // The pseudo instruction is gone now.
12106 // String/text processing lowering.
12107 case X86::PCMPISTRM128REG:
12108 case X86::VPCMPISTRM128REG:
12109 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12110 case X86::PCMPISTRM128MEM:
12111 case X86::VPCMPISTRM128MEM:
12112 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12113 case X86::PCMPESTRM128REG:
12114 case X86::VPCMPESTRM128REG:
12115 return EmitPCMP(MI, BB, 5, false /* in mem */);
12116 case X86::PCMPESTRM128MEM:
12117 case X86::VPCMPESTRM128MEM:
12118 return EmitPCMP(MI, BB, 5, true /* in mem */);
12120 // Thread synchronization.
12122 return EmitMonitor(MI, BB);
12124 return EmitMwait(MI, BB);
12126 // Atomic Lowering.
12127 case X86::ATOMAND32:
12128 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12129 X86::AND32ri, X86::MOV32rm,
12131 X86::NOT32r, X86::EAX,
12132 X86::GR32RegisterClass);
12133 case X86::ATOMOR32:
12134 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12135 X86::OR32ri, X86::MOV32rm,
12137 X86::NOT32r, X86::EAX,
12138 X86::GR32RegisterClass);
12139 case X86::ATOMXOR32:
12140 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12141 X86::XOR32ri, X86::MOV32rm,
12143 X86::NOT32r, X86::EAX,
12144 X86::GR32RegisterClass);
12145 case X86::ATOMNAND32:
12146 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12147 X86::AND32ri, X86::MOV32rm,
12149 X86::NOT32r, X86::EAX,
12150 X86::GR32RegisterClass, true);
12151 case X86::ATOMMIN32:
12152 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12153 case X86::ATOMMAX32:
12154 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12155 case X86::ATOMUMIN32:
12156 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12157 case X86::ATOMUMAX32:
12158 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12160 case X86::ATOMAND16:
12161 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12162 X86::AND16ri, X86::MOV16rm,
12164 X86::NOT16r, X86::AX,
12165 X86::GR16RegisterClass);
12166 case X86::ATOMOR16:
12167 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12168 X86::OR16ri, X86::MOV16rm,
12170 X86::NOT16r, X86::AX,
12171 X86::GR16RegisterClass);
12172 case X86::ATOMXOR16:
12173 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12174 X86::XOR16ri, X86::MOV16rm,
12176 X86::NOT16r, X86::AX,
12177 X86::GR16RegisterClass);
12178 case X86::ATOMNAND16:
12179 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12180 X86::AND16ri, X86::MOV16rm,
12182 X86::NOT16r, X86::AX,
12183 X86::GR16RegisterClass, true);
12184 case X86::ATOMMIN16:
12185 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12186 case X86::ATOMMAX16:
12187 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12188 case X86::ATOMUMIN16:
12189 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12190 case X86::ATOMUMAX16:
12191 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12193 case X86::ATOMAND8:
12194 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12195 X86::AND8ri, X86::MOV8rm,
12197 X86::NOT8r, X86::AL,
12198 X86::GR8RegisterClass);
12200 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12201 X86::OR8ri, X86::MOV8rm,
12203 X86::NOT8r, X86::AL,
12204 X86::GR8RegisterClass);
12205 case X86::ATOMXOR8:
12206 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12207 X86::XOR8ri, X86::MOV8rm,
12209 X86::NOT8r, X86::AL,
12210 X86::GR8RegisterClass);
12211 case X86::ATOMNAND8:
12212 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12213 X86::AND8ri, X86::MOV8rm,
12215 X86::NOT8r, X86::AL,
12216 X86::GR8RegisterClass, true);
12217 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12218 // This group is for 64-bit host.
12219 case X86::ATOMAND64:
12220 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12221 X86::AND64ri32, X86::MOV64rm,
12223 X86::NOT64r, X86::RAX,
12224 X86::GR64RegisterClass);
12225 case X86::ATOMOR64:
12226 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12227 X86::OR64ri32, X86::MOV64rm,
12229 X86::NOT64r, X86::RAX,
12230 X86::GR64RegisterClass);
12231 case X86::ATOMXOR64:
12232 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12233 X86::XOR64ri32, X86::MOV64rm,
12235 X86::NOT64r, X86::RAX,
12236 X86::GR64RegisterClass);
12237 case X86::ATOMNAND64:
12238 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12239 X86::AND64ri32, X86::MOV64rm,
12241 X86::NOT64r, X86::RAX,
12242 X86::GR64RegisterClass, true);
12243 case X86::ATOMMIN64:
12244 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12245 case X86::ATOMMAX64:
12246 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12247 case X86::ATOMUMIN64:
12248 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12249 case X86::ATOMUMAX64:
12250 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12252 // This group does 64-bit operations on a 32-bit host.
12253 case X86::ATOMAND6432:
12254 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12255 X86::AND32rr, X86::AND32rr,
12256 X86::AND32ri, X86::AND32ri,
12258 case X86::ATOMOR6432:
12259 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12260 X86::OR32rr, X86::OR32rr,
12261 X86::OR32ri, X86::OR32ri,
12263 case X86::ATOMXOR6432:
12264 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12265 X86::XOR32rr, X86::XOR32rr,
12266 X86::XOR32ri, X86::XOR32ri,
12268 case X86::ATOMNAND6432:
12269 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12270 X86::AND32rr, X86::AND32rr,
12271 X86::AND32ri, X86::AND32ri,
12273 case X86::ATOMADD6432:
12274 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12275 X86::ADD32rr, X86::ADC32rr,
12276 X86::ADD32ri, X86::ADC32ri,
12278 case X86::ATOMSUB6432:
12279 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12280 X86::SUB32rr, X86::SBB32rr,
12281 X86::SUB32ri, X86::SBB32ri,
12283 case X86::ATOMSWAP6432:
12284 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12285 X86::MOV32rr, X86::MOV32rr,
12286 X86::MOV32ri, X86::MOV32ri,
12288 case X86::VASTART_SAVE_XMM_REGS:
12289 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12291 case X86::VAARG_64:
12292 return EmitVAARG64WithCustomInserter(MI, BB);
12296 //===----------------------------------------------------------------------===//
12297 // X86 Optimization Hooks
12298 //===----------------------------------------------------------------------===//
12300 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12304 const SelectionDAG &DAG,
12305 unsigned Depth) const {
12306 unsigned Opc = Op.getOpcode();
12307 assert((Opc >= ISD::BUILTIN_OP_END ||
12308 Opc == ISD::INTRINSIC_WO_CHAIN ||
12309 Opc == ISD::INTRINSIC_W_CHAIN ||
12310 Opc == ISD::INTRINSIC_VOID) &&
12311 "Should use MaskedValueIsZero if you don't know whether Op"
12312 " is a target node!");
12314 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12328 // These nodes' second result is a boolean.
12329 if (Op.getResNo() == 0)
12332 case X86ISD::SETCC:
12333 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12334 Mask.getBitWidth() - 1);
12336 case ISD::INTRINSIC_WO_CHAIN: {
12337 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12338 unsigned NumLoBits = 0;
12341 case Intrinsic::x86_sse_movmsk_ps:
12342 case Intrinsic::x86_avx_movmsk_ps_256:
12343 case Intrinsic::x86_sse2_movmsk_pd:
12344 case Intrinsic::x86_avx_movmsk_pd_256:
12345 case Intrinsic::x86_mmx_pmovmskb:
12346 case Intrinsic::x86_sse2_pmovmskb_128: {
12347 // High bits of movmskp{s|d}, pmovmskb are known zero.
12349 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12350 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12351 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12352 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12353 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12354 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12356 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12357 Mask.getBitWidth() - NumLoBits);
12366 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12367 unsigned Depth) const {
12368 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12369 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12370 return Op.getValueType().getScalarType().getSizeInBits();
12376 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12377 /// node is a GlobalAddress + offset.
12378 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12379 const GlobalValue* &GA,
12380 int64_t &Offset) const {
12381 if (N->getOpcode() == X86ISD::Wrapper) {
12382 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12383 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12384 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12388 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12391 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12392 /// same as extracting the high 128-bit part of 256-bit vector and then
12393 /// inserting the result into the low part of a new 256-bit vector
12394 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12395 EVT VT = SVOp->getValueType(0);
12396 int NumElems = VT.getVectorNumElements();
12398 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12399 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12400 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12401 SVOp->getMaskElt(j) >= 0)
12407 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12408 /// same as extracting the low 128-bit part of 256-bit vector and then
12409 /// inserting the result into the high part of a new 256-bit vector
12410 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12411 EVT VT = SVOp->getValueType(0);
12412 int NumElems = VT.getVectorNumElements();
12414 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12415 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12416 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12417 SVOp->getMaskElt(j) >= 0)
12423 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12424 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12425 TargetLowering::DAGCombinerInfo &DCI) {
12426 DebugLoc dl = N->getDebugLoc();
12427 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12428 SDValue V1 = SVOp->getOperand(0);
12429 SDValue V2 = SVOp->getOperand(1);
12430 EVT VT = SVOp->getValueType(0);
12431 int NumElems = VT.getVectorNumElements();
12433 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12434 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12438 // V UNDEF BUILD_VECTOR UNDEF
12440 // CONCAT_VECTOR CONCAT_VECTOR
12443 // RESULT: V + zero extended
12445 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12446 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12447 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12450 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12453 // To match the shuffle mask, the first half of the mask should
12454 // be exactly the first vector, and all the rest a splat with the
12455 // first element of the second one.
12456 for (int i = 0; i < NumElems/2; ++i)
12457 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12458 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12461 // Emit a zeroed vector and insert the desired subvector on its
12463 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12464 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12465 DAG.getConstant(0, MVT::i32), DAG, dl);
12466 return DCI.CombineTo(N, InsV);
12469 //===--------------------------------------------------------------------===//
12470 // Combine some shuffles into subvector extracts and inserts:
12473 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12474 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12475 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12477 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12478 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12479 return DCI.CombineTo(N, InsV);
12482 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12483 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12484 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12485 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12486 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12487 return DCI.CombineTo(N, InsV);
12493 /// PerformShuffleCombine - Performs several different shuffle combines.
12494 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12495 TargetLowering::DAGCombinerInfo &DCI,
12496 const X86Subtarget *Subtarget) {
12497 DebugLoc dl = N->getDebugLoc();
12498 EVT VT = N->getValueType(0);
12500 // Don't create instructions with illegal types after legalize types has run.
12501 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12502 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12505 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12506 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12507 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12508 return PerformShuffleCombine256(N, DAG, DCI);
12510 // Only handle 128 wide vector from here on.
12511 if (VT.getSizeInBits() != 128)
12514 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12515 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12516 // consecutive, non-overlapping, and in the right order.
12517 SmallVector<SDValue, 16> Elts;
12518 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12519 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12521 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12524 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12525 /// generation and convert it from being a bunch of shuffles and extracts
12526 /// to a simple store and scalar loads to extract the elements.
12527 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12528 const TargetLowering &TLI) {
12529 SDValue InputVector = N->getOperand(0);
12531 // Only operate on vectors of 4 elements, where the alternative shuffling
12532 // gets to be more expensive.
12533 if (InputVector.getValueType() != MVT::v4i32)
12536 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12537 // single use which is a sign-extend or zero-extend, and all elements are
12539 SmallVector<SDNode *, 4> Uses;
12540 unsigned ExtractedElements = 0;
12541 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12542 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12543 if (UI.getUse().getResNo() != InputVector.getResNo())
12546 SDNode *Extract = *UI;
12547 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12550 if (Extract->getValueType(0) != MVT::i32)
12552 if (!Extract->hasOneUse())
12554 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12555 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12557 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12560 // Record which element was extracted.
12561 ExtractedElements |=
12562 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12564 Uses.push_back(Extract);
12567 // If not all the elements were used, this may not be worthwhile.
12568 if (ExtractedElements != 15)
12571 // Ok, we've now decided to do the transformation.
12572 DebugLoc dl = InputVector.getDebugLoc();
12574 // Store the value to a temporary stack slot.
12575 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12576 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12577 MachinePointerInfo(), false, false, 0);
12579 // Replace each use (extract) with a load of the appropriate element.
12580 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12581 UE = Uses.end(); UI != UE; ++UI) {
12582 SDNode *Extract = *UI;
12584 // cOMpute the element's address.
12585 SDValue Idx = Extract->getOperand(1);
12587 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12588 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12589 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12591 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12592 StackPtr, OffsetVal);
12594 // Load the scalar.
12595 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12596 ScalarAddr, MachinePointerInfo(),
12599 // Replace the exact with the load.
12600 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12603 // The replacement was made in place; don't return anything.
12607 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12609 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12610 const X86Subtarget *Subtarget) {
12611 DebugLoc DL = N->getDebugLoc();
12612 SDValue Cond = N->getOperand(0);
12613 // Get the LHS/RHS of the select.
12614 SDValue LHS = N->getOperand(1);
12615 SDValue RHS = N->getOperand(2);
12616 EVT VT = LHS.getValueType();
12618 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12619 // instructions match the semantics of the common C idiom x<y?x:y but not
12620 // x<=y?x:y, because of how they handle negative zero (which can be
12621 // ignored in unsafe-math mode).
12622 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12623 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12624 (Subtarget->hasXMMInt() ||
12625 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12626 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12628 unsigned Opcode = 0;
12629 // Check for x CC y ? x : y.
12630 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12631 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12635 // Converting this to a min would handle NaNs incorrectly, and swapping
12636 // the operands would cause it to handle comparisons between positive
12637 // and negative zero incorrectly.
12638 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12639 if (!UnsafeFPMath &&
12640 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12642 std::swap(LHS, RHS);
12644 Opcode = X86ISD::FMIN;
12647 // Converting this to a min would handle comparisons between positive
12648 // and negative zero incorrectly.
12649 if (!UnsafeFPMath &&
12650 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12652 Opcode = X86ISD::FMIN;
12655 // Converting this to a min would handle both negative zeros and NaNs
12656 // incorrectly, but we can swap the operands to fix both.
12657 std::swap(LHS, RHS);
12661 Opcode = X86ISD::FMIN;
12665 // Converting this to a max would handle comparisons between positive
12666 // and negative zero incorrectly.
12667 if (!UnsafeFPMath &&
12668 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12670 Opcode = X86ISD::FMAX;
12673 // Converting this to a max would handle NaNs incorrectly, and swapping
12674 // the operands would cause it to handle comparisons between positive
12675 // and negative zero incorrectly.
12676 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12677 if (!UnsafeFPMath &&
12678 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12680 std::swap(LHS, RHS);
12682 Opcode = X86ISD::FMAX;
12685 // Converting this to a max would handle both negative zeros and NaNs
12686 // incorrectly, but we can swap the operands to fix both.
12687 std::swap(LHS, RHS);
12691 Opcode = X86ISD::FMAX;
12694 // Check for x CC y ? y : x -- a min/max with reversed arms.
12695 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12696 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12700 // Converting this to a min would handle comparisons between positive
12701 // and negative zero incorrectly, and swapping the operands would
12702 // cause it to handle NaNs incorrectly.
12703 if (!UnsafeFPMath &&
12704 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12705 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12707 std::swap(LHS, RHS);
12709 Opcode = X86ISD::FMIN;
12712 // Converting this to a min would handle NaNs incorrectly.
12713 if (!UnsafeFPMath &&
12714 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12716 Opcode = X86ISD::FMIN;
12719 // Converting this to a min would handle both negative zeros and NaNs
12720 // incorrectly, but we can swap the operands to fix both.
12721 std::swap(LHS, RHS);
12725 Opcode = X86ISD::FMIN;
12729 // Converting this to a max would handle NaNs incorrectly.
12730 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12732 Opcode = X86ISD::FMAX;
12735 // Converting this to a max would handle comparisons between positive
12736 // and negative zero incorrectly, and swapping the operands would
12737 // cause it to handle NaNs incorrectly.
12738 if (!UnsafeFPMath &&
12739 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12740 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12742 std::swap(LHS, RHS);
12744 Opcode = X86ISD::FMAX;
12747 // Converting this to a max would handle both negative zeros and NaNs
12748 // incorrectly, but we can swap the operands to fix both.
12749 std::swap(LHS, RHS);
12753 Opcode = X86ISD::FMAX;
12759 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12762 // If this is a select between two integer constants, try to do some
12764 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12765 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12766 // Don't do this for crazy integer types.
12767 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12768 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12769 // so that TrueC (the true value) is larger than FalseC.
12770 bool NeedsCondInvert = false;
12772 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12773 // Efficiently invertible.
12774 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
12775 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
12776 isa<ConstantSDNode>(Cond.getOperand(1))))) {
12777 NeedsCondInvert = true;
12778 std::swap(TrueC, FalseC);
12781 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
12782 if (FalseC->getAPIntValue() == 0 &&
12783 TrueC->getAPIntValue().isPowerOf2()) {
12784 if (NeedsCondInvert) // Invert the condition if needed.
12785 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12786 DAG.getConstant(1, Cond.getValueType()));
12788 // Zero extend the condition if needed.
12789 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12791 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12792 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12793 DAG.getConstant(ShAmt, MVT::i8));
12796 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12797 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12798 if (NeedsCondInvert) // Invert the condition if needed.
12799 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12800 DAG.getConstant(1, Cond.getValueType()));
12802 // Zero extend the condition if needed.
12803 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12804 FalseC->getValueType(0), Cond);
12805 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12806 SDValue(FalseC, 0));
12809 // Optimize cases that will turn into an LEA instruction. This requires
12810 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12811 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12812 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12813 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12815 bool isFastMultiplier = false;
12817 switch ((unsigned char)Diff) {
12819 case 1: // result = add base, cond
12820 case 2: // result = lea base( , cond*2)
12821 case 3: // result = lea base(cond, cond*2)
12822 case 4: // result = lea base( , cond*4)
12823 case 5: // result = lea base(cond, cond*4)
12824 case 8: // result = lea base( , cond*8)
12825 case 9: // result = lea base(cond, cond*8)
12826 isFastMultiplier = true;
12831 if (isFastMultiplier) {
12832 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12833 if (NeedsCondInvert) // Invert the condition if needed.
12834 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12835 DAG.getConstant(1, Cond.getValueType()));
12837 // Zero extend the condition if needed.
12838 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12840 // Scale the condition by the difference.
12842 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12843 DAG.getConstant(Diff, Cond.getValueType()));
12845 // Add the base if non-zero.
12846 if (FalseC->getAPIntValue() != 0)
12847 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12848 SDValue(FalseC, 0));
12858 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12859 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12860 TargetLowering::DAGCombinerInfo &DCI) {
12861 DebugLoc DL = N->getDebugLoc();
12863 // If the flag operand isn't dead, don't touch this CMOV.
12864 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12867 SDValue FalseOp = N->getOperand(0);
12868 SDValue TrueOp = N->getOperand(1);
12869 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12870 SDValue Cond = N->getOperand(3);
12871 if (CC == X86::COND_E || CC == X86::COND_NE) {
12872 switch (Cond.getOpcode()) {
12876 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12877 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12878 return (CC == X86::COND_E) ? FalseOp : TrueOp;
12882 // If this is a select between two integer constants, try to do some
12883 // optimizations. Note that the operands are ordered the opposite of SELECT
12885 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12886 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12887 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12888 // larger than FalseC (the false value).
12889 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12890 CC = X86::GetOppositeBranchCondition(CC);
12891 std::swap(TrueC, FalseC);
12894 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
12895 // This is efficient for any integer data type (including i8/i16) and
12897 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12898 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12899 DAG.getConstant(CC, MVT::i8), Cond);
12901 // Zero extend the condition if needed.
12902 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12904 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12905 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12906 DAG.getConstant(ShAmt, MVT::i8));
12907 if (N->getNumValues() == 2) // Dead flag value?
12908 return DCI.CombineTo(N, Cond, SDValue());
12912 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
12913 // for any integer data type, including i8/i16.
12914 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12915 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12916 DAG.getConstant(CC, MVT::i8), Cond);
12918 // Zero extend the condition if needed.
12919 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12920 FalseC->getValueType(0), Cond);
12921 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12922 SDValue(FalseC, 0));
12924 if (N->getNumValues() == 2) // Dead flag value?
12925 return DCI.CombineTo(N, Cond, SDValue());
12929 // Optimize cases that will turn into an LEA instruction. This requires
12930 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12931 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12932 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12933 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12935 bool isFastMultiplier = false;
12937 switch ((unsigned char)Diff) {
12939 case 1: // result = add base, cond
12940 case 2: // result = lea base( , cond*2)
12941 case 3: // result = lea base(cond, cond*2)
12942 case 4: // result = lea base( , cond*4)
12943 case 5: // result = lea base(cond, cond*4)
12944 case 8: // result = lea base( , cond*8)
12945 case 9: // result = lea base(cond, cond*8)
12946 isFastMultiplier = true;
12951 if (isFastMultiplier) {
12952 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12953 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12954 DAG.getConstant(CC, MVT::i8), Cond);
12955 // Zero extend the condition if needed.
12956 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12958 // Scale the condition by the difference.
12960 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12961 DAG.getConstant(Diff, Cond.getValueType()));
12963 // Add the base if non-zero.
12964 if (FalseC->getAPIntValue() != 0)
12965 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12966 SDValue(FalseC, 0));
12967 if (N->getNumValues() == 2) // Dead flag value?
12968 return DCI.CombineTo(N, Cond, SDValue());
12978 /// PerformMulCombine - Optimize a single multiply with constant into two
12979 /// in order to implement it with two cheaper instructions, e.g.
12980 /// LEA + SHL, LEA + LEA.
12981 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12982 TargetLowering::DAGCombinerInfo &DCI) {
12983 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12986 EVT VT = N->getValueType(0);
12987 if (VT != MVT::i64)
12990 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12993 uint64_t MulAmt = C->getZExtValue();
12994 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12997 uint64_t MulAmt1 = 0;
12998 uint64_t MulAmt2 = 0;
12999 if ((MulAmt % 9) == 0) {
13001 MulAmt2 = MulAmt / 9;
13002 } else if ((MulAmt % 5) == 0) {
13004 MulAmt2 = MulAmt / 5;
13005 } else if ((MulAmt % 3) == 0) {
13007 MulAmt2 = MulAmt / 3;
13010 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13011 DebugLoc DL = N->getDebugLoc();
13013 if (isPowerOf2_64(MulAmt2) &&
13014 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13015 // If second multiplifer is pow2, issue it first. We want the multiply by
13016 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13018 std::swap(MulAmt1, MulAmt2);
13021 if (isPowerOf2_64(MulAmt1))
13022 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13023 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13025 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13026 DAG.getConstant(MulAmt1, VT));
13028 if (isPowerOf2_64(MulAmt2))
13029 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13030 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13032 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13033 DAG.getConstant(MulAmt2, VT));
13035 // Do not add new nodes to DAG combiner worklist.
13036 DCI.CombineTo(N, NewMul, false);
13041 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13042 SDValue N0 = N->getOperand(0);
13043 SDValue N1 = N->getOperand(1);
13044 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13045 EVT VT = N0.getValueType();
13047 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13048 // since the result of setcc_c is all zero's or all ones.
13049 if (N1C && N0.getOpcode() == ISD::AND &&
13050 N0.getOperand(1).getOpcode() == ISD::Constant) {
13051 SDValue N00 = N0.getOperand(0);
13052 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13053 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13054 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13055 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13056 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13057 APInt ShAmt = N1C->getAPIntValue();
13058 Mask = Mask.shl(ShAmt);
13060 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13061 N00, DAG.getConstant(Mask, VT));
13068 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13070 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13071 const X86Subtarget *Subtarget) {
13072 EVT VT = N->getValueType(0);
13073 if (!VT.isVector() && VT.isInteger() &&
13074 N->getOpcode() == ISD::SHL)
13075 return PerformSHLCombine(N, DAG);
13077 // On X86 with SSE2 support, we can transform this to a vector shift if
13078 // all elements are shifted by the same amount. We can't do this in legalize
13079 // because the a constant vector is typically transformed to a constant pool
13080 // so we have no knowledge of the shift amount.
13081 if (!Subtarget->hasXMMInt())
13084 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13087 SDValue ShAmtOp = N->getOperand(1);
13088 EVT EltVT = VT.getVectorElementType();
13089 DebugLoc DL = N->getDebugLoc();
13090 SDValue BaseShAmt = SDValue();
13091 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13092 unsigned NumElts = VT.getVectorNumElements();
13094 for (; i != NumElts; ++i) {
13095 SDValue Arg = ShAmtOp.getOperand(i);
13096 if (Arg.getOpcode() == ISD::UNDEF) continue;
13100 for (; i != NumElts; ++i) {
13101 SDValue Arg = ShAmtOp.getOperand(i);
13102 if (Arg.getOpcode() == ISD::UNDEF) continue;
13103 if (Arg != BaseShAmt) {
13107 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13108 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13109 SDValue InVec = ShAmtOp.getOperand(0);
13110 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13111 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13113 for (; i != NumElts; ++i) {
13114 SDValue Arg = InVec.getOperand(i);
13115 if (Arg.getOpcode() == ISD::UNDEF) continue;
13119 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13121 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13122 if (C->getZExtValue() == SplatIdx)
13123 BaseShAmt = InVec.getOperand(1);
13126 if (BaseShAmt.getNode() == 0)
13127 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13128 DAG.getIntPtrConstant(0));
13132 // The shift amount is an i32.
13133 if (EltVT.bitsGT(MVT::i32))
13134 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13135 else if (EltVT.bitsLT(MVT::i32))
13136 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13138 // The shift amount is identical so we can do a vector shift.
13139 SDValue ValOp = N->getOperand(0);
13140 switch (N->getOpcode()) {
13142 llvm_unreachable("Unknown shift opcode!");
13145 if (VT == MVT::v2i64)
13146 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13147 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13149 if (VT == MVT::v4i32)
13150 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13151 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13153 if (VT == MVT::v8i16)
13154 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13155 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13159 if (VT == MVT::v4i32)
13160 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13161 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13163 if (VT == MVT::v8i16)
13164 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13165 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13169 if (VT == MVT::v2i64)
13170 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13171 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13173 if (VT == MVT::v4i32)
13174 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13175 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13177 if (VT == MVT::v8i16)
13178 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13179 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13187 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13188 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13189 // and friends. Likewise for OR -> CMPNEQSS.
13190 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13191 TargetLowering::DAGCombinerInfo &DCI,
13192 const X86Subtarget *Subtarget) {
13195 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13196 // we're requiring SSE2 for both.
13197 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13198 SDValue N0 = N->getOperand(0);
13199 SDValue N1 = N->getOperand(1);
13200 SDValue CMP0 = N0->getOperand(1);
13201 SDValue CMP1 = N1->getOperand(1);
13202 DebugLoc DL = N->getDebugLoc();
13204 // The SETCCs should both refer to the same CMP.
13205 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13208 SDValue CMP00 = CMP0->getOperand(0);
13209 SDValue CMP01 = CMP0->getOperand(1);
13210 EVT VT = CMP00.getValueType();
13212 if (VT == MVT::f32 || VT == MVT::f64) {
13213 bool ExpectingFlags = false;
13214 // Check for any users that want flags:
13215 for (SDNode::use_iterator UI = N->use_begin(),
13217 !ExpectingFlags && UI != UE; ++UI)
13218 switch (UI->getOpcode()) {
13223 ExpectingFlags = true;
13225 case ISD::CopyToReg:
13226 case ISD::SIGN_EXTEND:
13227 case ISD::ZERO_EXTEND:
13228 case ISD::ANY_EXTEND:
13232 if (!ExpectingFlags) {
13233 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13234 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13236 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13237 X86::CondCode tmp = cc0;
13242 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13243 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13244 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13245 X86ISD::NodeType NTOperator = is64BitFP ?
13246 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13247 // FIXME: need symbolic constants for these magic numbers.
13248 // See X86ATTInstPrinter.cpp:printSSECC().
13249 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13250 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13251 DAG.getConstant(x86cc, MVT::i8));
13252 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13254 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13255 DAG.getConstant(1, MVT::i32));
13256 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13257 return OneBitOfTruth;
13265 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13266 /// so it can be folded inside ANDNP.
13267 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13268 EVT VT = N->getValueType(0);
13270 // Match direct AllOnes for 128 and 256-bit vectors
13271 if (ISD::isBuildVectorAllOnes(N))
13274 // Look through a bit convert.
13275 if (N->getOpcode() == ISD::BITCAST)
13276 N = N->getOperand(0).getNode();
13278 // Sometimes the operand may come from a insert_subvector building a 256-bit
13280 if (VT.getSizeInBits() == 256 &&
13281 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13282 SDValue V1 = N->getOperand(0);
13283 SDValue V2 = N->getOperand(1);
13285 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13286 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13287 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13288 ISD::isBuildVectorAllOnes(V2.getNode()))
13295 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13296 TargetLowering::DAGCombinerInfo &DCI,
13297 const X86Subtarget *Subtarget) {
13298 if (DCI.isBeforeLegalizeOps())
13301 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13305 // Want to form ANDNP nodes:
13306 // 1) In the hopes of then easily combining them with OR and AND nodes
13307 // to form PBLEND/PSIGN.
13308 // 2) To match ANDN packed intrinsics
13309 EVT VT = N->getValueType(0);
13310 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13313 SDValue N0 = N->getOperand(0);
13314 SDValue N1 = N->getOperand(1);
13315 DebugLoc DL = N->getDebugLoc();
13317 // Check LHS for vnot
13318 if (N0.getOpcode() == ISD::XOR &&
13319 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13320 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13321 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13323 // Check RHS for vnot
13324 if (N1.getOpcode() == ISD::XOR &&
13325 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13326 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13327 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13332 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13333 TargetLowering::DAGCombinerInfo &DCI,
13334 const X86Subtarget *Subtarget) {
13335 if (DCI.isBeforeLegalizeOps())
13338 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13342 EVT VT = N->getValueType(0);
13343 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13346 SDValue N0 = N->getOperand(0);
13347 SDValue N1 = N->getOperand(1);
13349 // look for psign/blend
13350 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13351 if (VT == MVT::v2i64) {
13352 // Canonicalize pandn to RHS
13353 if (N0.getOpcode() == X86ISD::ANDNP)
13355 // or (and (m, x), (pandn m, y))
13356 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13357 SDValue Mask = N1.getOperand(0);
13358 SDValue X = N1.getOperand(1);
13360 if (N0.getOperand(0) == Mask)
13361 Y = N0.getOperand(1);
13362 if (N0.getOperand(1) == Mask)
13363 Y = N0.getOperand(0);
13365 // Check to see if the mask appeared in both the AND and ANDNP and
13369 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13370 if (Mask.getOpcode() != ISD::BITCAST ||
13371 X.getOpcode() != ISD::BITCAST ||
13372 Y.getOpcode() != ISD::BITCAST)
13375 // Look through mask bitcast.
13376 Mask = Mask.getOperand(0);
13377 EVT MaskVT = Mask.getValueType();
13379 // Validate that the Mask operand is a vector sra node. The sra node
13380 // will be an intrinsic.
13381 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13384 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13385 // there is no psrai.b
13386 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13387 case Intrinsic::x86_sse2_psrai_w:
13388 case Intrinsic::x86_sse2_psrai_d:
13390 default: return SDValue();
13393 // Check that the SRA is all signbits.
13394 SDValue SraC = Mask.getOperand(2);
13395 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13396 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13397 if ((SraAmt + 1) != EltBits)
13400 DebugLoc DL = N->getDebugLoc();
13402 // Now we know we at least have a plendvb with the mask val. See if
13403 // we can form a psignb/w/d.
13404 // psign = x.type == y.type == mask.type && y = sub(0, x);
13405 X = X.getOperand(0);
13406 Y = Y.getOperand(0);
13407 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13408 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13409 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13412 case 8: Opc = X86ISD::PSIGNB; break;
13413 case 16: Opc = X86ISD::PSIGNW; break;
13414 case 32: Opc = X86ISD::PSIGND; break;
13418 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13419 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13422 // PBLENDVB only available on SSE 4.1
13423 if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13426 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13427 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13428 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13429 Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13430 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13435 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13436 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13438 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13440 if (!N0.hasOneUse() || !N1.hasOneUse())
13443 SDValue ShAmt0 = N0.getOperand(1);
13444 if (ShAmt0.getValueType() != MVT::i8)
13446 SDValue ShAmt1 = N1.getOperand(1);
13447 if (ShAmt1.getValueType() != MVT::i8)
13449 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13450 ShAmt0 = ShAmt0.getOperand(0);
13451 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13452 ShAmt1 = ShAmt1.getOperand(0);
13454 DebugLoc DL = N->getDebugLoc();
13455 unsigned Opc = X86ISD::SHLD;
13456 SDValue Op0 = N0.getOperand(0);
13457 SDValue Op1 = N1.getOperand(0);
13458 if (ShAmt0.getOpcode() == ISD::SUB) {
13459 Opc = X86ISD::SHRD;
13460 std::swap(Op0, Op1);
13461 std::swap(ShAmt0, ShAmt1);
13464 unsigned Bits = VT.getSizeInBits();
13465 if (ShAmt1.getOpcode() == ISD::SUB) {
13466 SDValue Sum = ShAmt1.getOperand(0);
13467 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13468 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13469 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13470 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13471 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13472 return DAG.getNode(Opc, DL, VT,
13474 DAG.getNode(ISD::TRUNCATE, DL,
13477 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13478 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13480 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13481 return DAG.getNode(Opc, DL, VT,
13482 N0.getOperand(0), N1.getOperand(0),
13483 DAG.getNode(ISD::TRUNCATE, DL,
13490 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13491 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13492 const X86Subtarget *Subtarget) {
13493 LoadSDNode *Ld = cast<LoadSDNode>(N);
13494 EVT RegVT = Ld->getValueType(0);
13495 EVT MemVT = Ld->getMemoryVT();
13496 DebugLoc dl = Ld->getDebugLoc();
13497 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13499 ISD::LoadExtType Ext = Ld->getExtensionType();
13501 // If this is a vector EXT Load then attempt to optimize it using a
13502 // shuffle. We need SSE4 for the shuffles.
13503 // TODO: It is possible to support ZExt by zeroing the undef values
13504 // during the shuffle phase or after the shuffle.
13505 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13506 assert(MemVT != RegVT && "Cannot extend to the same type");
13507 assert(MemVT.isVector() && "Must load a vector from memory");
13509 unsigned NumElems = RegVT.getVectorNumElements();
13510 unsigned RegSz = RegVT.getSizeInBits();
13511 unsigned MemSz = MemVT.getSizeInBits();
13512 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13513 // All sizes must be a power of two
13514 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13516 // Attempt to load the original value using a single load op.
13517 // Find a scalar type which is equal to the loaded word size.
13518 MVT SclrLoadTy = MVT::i8;
13519 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13520 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13521 MVT Tp = (MVT::SimpleValueType)tp;
13522 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
13528 // Proceed if a load word is found.
13529 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13531 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13532 RegSz/SclrLoadTy.getSizeInBits());
13534 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13535 RegSz/MemVT.getScalarType().getSizeInBits());
13536 // Can't shuffle using an illegal type.
13537 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13539 // Perform a single load.
13540 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13542 Ld->getPointerInfo(), Ld->isVolatile(),
13543 Ld->isNonTemporal(), Ld->getAlignment());
13545 // Insert the word loaded into a vector.
13546 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13547 LoadUnitVecVT, ScalarLoad);
13549 // Bitcast the loaded value to a vector of the original element type, in
13550 // the size of the target vector type.
13551 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13552 unsigned SizeRatio = RegSz/MemSz;
13554 // Redistribute the loaded elements into the different locations.
13555 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13556 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13558 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13559 DAG.getUNDEF(SlicedVec.getValueType()),
13560 ShuffleVec.data());
13562 // Bitcast to the requested type.
13563 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13564 // Replace the original load with the new sequence
13565 // and return the new chain.
13566 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13567 return SDValue(ScalarLoad.getNode(), 1);
13573 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13574 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13575 const X86Subtarget *Subtarget) {
13576 StoreSDNode *St = cast<StoreSDNode>(N);
13577 EVT VT = St->getValue().getValueType();
13578 EVT StVT = St->getMemoryVT();
13579 DebugLoc dl = St->getDebugLoc();
13580 SDValue StoredVal = St->getOperand(1);
13581 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13583 // If we are saving a concatination of two XMM registers, perform two stores.
13584 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13585 // 128-bit ones. If in the future the cost becomes only one memory access the
13586 // first version would be better.
13587 if (VT.getSizeInBits() == 256 &&
13588 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13589 StoredVal.getNumOperands() == 2) {
13591 SDValue Value0 = StoredVal.getOperand(0);
13592 SDValue Value1 = StoredVal.getOperand(1);
13594 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13595 SDValue Ptr0 = St->getBasePtr();
13596 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13598 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13599 St->getPointerInfo(), St->isVolatile(),
13600 St->isNonTemporal(), St->getAlignment());
13601 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13602 St->getPointerInfo(), St->isVolatile(),
13603 St->isNonTemporal(), St->getAlignment());
13604 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13607 // Optimize trunc store (of multiple scalars) to shuffle and store.
13608 // First, pack all of the elements in one place. Next, store to memory
13609 // in fewer chunks.
13610 if (St->isTruncatingStore() && VT.isVector()) {
13611 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13612 unsigned NumElems = VT.getVectorNumElements();
13613 assert(StVT != VT && "Cannot truncate to the same type");
13614 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13615 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13617 // From, To sizes and ElemCount must be pow of two
13618 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13619 // We are going to use the original vector elt for storing.
13620 // Accumulated smaller vector elements must be a multiple of the store size.
13621 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13623 unsigned SizeRatio = FromSz / ToSz;
13625 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13627 // Create a type on which we perform the shuffle
13628 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13629 StVT.getScalarType(), NumElems*SizeRatio);
13631 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13633 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13634 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13635 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13637 // Can't shuffle using an illegal type
13638 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13640 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13641 DAG.getUNDEF(WideVec.getValueType()),
13642 ShuffleVec.data());
13643 // At this point all of the data is stored at the bottom of the
13644 // register. We now need to save it to mem.
13646 // Find the largest store unit
13647 MVT StoreType = MVT::i8;
13648 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13649 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13650 MVT Tp = (MVT::SimpleValueType)tp;
13651 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13655 // Bitcast the original vector into a vector of store-size units
13656 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13657 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13658 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13659 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13660 SmallVector<SDValue, 8> Chains;
13661 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13662 TLI.getPointerTy());
13663 SDValue Ptr = St->getBasePtr();
13665 // Perform one or more big stores into memory.
13666 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13667 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13668 StoreType, ShuffWide,
13669 DAG.getIntPtrConstant(i));
13670 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13671 St->getPointerInfo(), St->isVolatile(),
13672 St->isNonTemporal(), St->getAlignment());
13673 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13674 Chains.push_back(Ch);
13677 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13682 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
13683 // the FP state in cases where an emms may be missing.
13684 // A preferable solution to the general problem is to figure out the right
13685 // places to insert EMMS. This qualifies as a quick hack.
13687 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13688 if (VT.getSizeInBits() != 64)
13691 const Function *F = DAG.getMachineFunction().getFunction();
13692 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13693 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13694 && Subtarget->hasXMMInt();
13695 if ((VT.isVector() ||
13696 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13697 isa<LoadSDNode>(St->getValue()) &&
13698 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13699 St->getChain().hasOneUse() && !St->isVolatile()) {
13700 SDNode* LdVal = St->getValue().getNode();
13701 LoadSDNode *Ld = 0;
13702 int TokenFactorIndex = -1;
13703 SmallVector<SDValue, 8> Ops;
13704 SDNode* ChainVal = St->getChain().getNode();
13705 // Must be a store of a load. We currently handle two cases: the load
13706 // is a direct child, and it's under an intervening TokenFactor. It is
13707 // possible to dig deeper under nested TokenFactors.
13708 if (ChainVal == LdVal)
13709 Ld = cast<LoadSDNode>(St->getChain());
13710 else if (St->getValue().hasOneUse() &&
13711 ChainVal->getOpcode() == ISD::TokenFactor) {
13712 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13713 if (ChainVal->getOperand(i).getNode() == LdVal) {
13714 TokenFactorIndex = i;
13715 Ld = cast<LoadSDNode>(St->getValue());
13717 Ops.push_back(ChainVal->getOperand(i));
13721 if (!Ld || !ISD::isNormalLoad(Ld))
13724 // If this is not the MMX case, i.e. we are just turning i64 load/store
13725 // into f64 load/store, avoid the transformation if there are multiple
13726 // uses of the loaded value.
13727 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13730 DebugLoc LdDL = Ld->getDebugLoc();
13731 DebugLoc StDL = N->getDebugLoc();
13732 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13733 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13735 if (Subtarget->is64Bit() || F64IsLegal) {
13736 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13737 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13738 Ld->getPointerInfo(), Ld->isVolatile(),
13739 Ld->isNonTemporal(), Ld->getAlignment());
13740 SDValue NewChain = NewLd.getValue(1);
13741 if (TokenFactorIndex != -1) {
13742 Ops.push_back(NewChain);
13743 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13746 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13747 St->getPointerInfo(),
13748 St->isVolatile(), St->isNonTemporal(),
13749 St->getAlignment());
13752 // Otherwise, lower to two pairs of 32-bit loads / stores.
13753 SDValue LoAddr = Ld->getBasePtr();
13754 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13755 DAG.getConstant(4, MVT::i32));
13757 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13758 Ld->getPointerInfo(),
13759 Ld->isVolatile(), Ld->isNonTemporal(),
13760 Ld->getAlignment());
13761 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13762 Ld->getPointerInfo().getWithOffset(4),
13763 Ld->isVolatile(), Ld->isNonTemporal(),
13764 MinAlign(Ld->getAlignment(), 4));
13766 SDValue NewChain = LoLd.getValue(1);
13767 if (TokenFactorIndex != -1) {
13768 Ops.push_back(LoLd);
13769 Ops.push_back(HiLd);
13770 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13774 LoAddr = St->getBasePtr();
13775 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13776 DAG.getConstant(4, MVT::i32));
13778 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13779 St->getPointerInfo(),
13780 St->isVolatile(), St->isNonTemporal(),
13781 St->getAlignment());
13782 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13783 St->getPointerInfo().getWithOffset(4),
13785 St->isNonTemporal(),
13786 MinAlign(St->getAlignment(), 4));
13787 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13792 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
13793 /// and return the operands for the horizontal operation in LHS and RHS. A
13794 /// horizontal operation performs the binary operation on successive elements
13795 /// of its first operand, then on successive elements of its second operand,
13796 /// returning the resulting values in a vector. For example, if
13797 /// A = < float a0, float a1, float a2, float a3 >
13799 /// B = < float b0, float b1, float b2, float b3 >
13800 /// then the result of doing a horizontal operation on A and B is
13801 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
13802 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
13803 /// A horizontal-op B, for some already available A and B, and if so then LHS is
13804 /// set to A, RHS to B, and the routine returns 'true'.
13805 /// Note that the binary operation should have the property that if one of the
13806 /// operands is UNDEF then the result is UNDEF.
13807 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
13808 // Look for the following pattern: if
13809 // A = < float a0, float a1, float a2, float a3 >
13810 // B = < float b0, float b1, float b2, float b3 >
13812 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
13813 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
13814 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
13815 // which is A horizontal-op B.
13817 // At least one of the operands should be a vector shuffle.
13818 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13819 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
13822 EVT VT = LHS.getValueType();
13823 unsigned N = VT.getVectorNumElements();
13825 // View LHS in the form
13826 // LHS = VECTOR_SHUFFLE A, B, LMask
13827 // If LHS is not a shuffle then pretend it is the shuffle
13828 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
13829 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
13832 SmallVector<int, 8> LMask(N);
13833 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13834 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
13835 A = LHS.getOperand(0);
13836 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
13837 B = LHS.getOperand(1);
13838 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
13840 if (LHS.getOpcode() != ISD::UNDEF)
13842 for (unsigned i = 0; i != N; ++i)
13846 // Likewise, view RHS in the form
13847 // RHS = VECTOR_SHUFFLE C, D, RMask
13849 SmallVector<int, 8> RMask(N);
13850 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13851 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
13852 C = RHS.getOperand(0);
13853 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
13854 D = RHS.getOperand(1);
13855 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
13857 if (RHS.getOpcode() != ISD::UNDEF)
13859 for (unsigned i = 0; i != N; ++i)
13863 // Check that the shuffles are both shuffling the same vectors.
13864 if (!(A == C && B == D) && !(A == D && B == C))
13867 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
13868 if (!A.getNode() && !B.getNode())
13871 // If A and B occur in reverse order in RHS, then "swap" them (which means
13872 // rewriting the mask).
13874 for (unsigned i = 0; i != N; ++i) {
13875 unsigned Idx = RMask[i];
13878 else if (Idx < 2*N)
13882 // At this point LHS and RHS are equivalent to
13883 // LHS = VECTOR_SHUFFLE A, B, LMask
13884 // RHS = VECTOR_SHUFFLE A, B, RMask
13885 // Check that the masks correspond to performing a horizontal operation.
13886 for (unsigned i = 0; i != N; ++i) {
13887 unsigned LIdx = LMask[i], RIdx = RMask[i];
13889 // Ignore any UNDEF components.
13890 if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
13891 || (!B.getNode() && (LIdx >= N || RIdx >= N)))
13894 // Check that successive elements are being operated on. If not, this is
13895 // not a horizontal operation.
13896 if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
13897 !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
13901 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
13902 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
13906 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
13907 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
13908 const X86Subtarget *Subtarget) {
13909 EVT VT = N->getValueType(0);
13910 SDValue LHS = N->getOperand(0);
13911 SDValue RHS = N->getOperand(1);
13913 // Try to synthesize horizontal adds from adds of shuffles.
13914 if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13915 (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13916 isHorizontalBinOp(LHS, RHS, true))
13917 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
13921 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
13922 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
13923 const X86Subtarget *Subtarget) {
13924 EVT VT = N->getValueType(0);
13925 SDValue LHS = N->getOperand(0);
13926 SDValue RHS = N->getOperand(1);
13928 // Try to synthesize horizontal subs from subs of shuffles.
13929 if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13930 (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13931 isHorizontalBinOp(LHS, RHS, false))
13932 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
13936 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13937 /// X86ISD::FXOR nodes.
13938 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13939 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13940 // F[X]OR(0.0, x) -> x
13941 // F[X]OR(x, 0.0) -> x
13942 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13943 if (C->getValueAPF().isPosZero())
13944 return N->getOperand(1);
13945 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13946 if (C->getValueAPF().isPosZero())
13947 return N->getOperand(0);
13951 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13952 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13953 // FAND(0.0, x) -> 0.0
13954 // FAND(x, 0.0) -> 0.0
13955 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13956 if (C->getValueAPF().isPosZero())
13957 return N->getOperand(0);
13958 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13959 if (C->getValueAPF().isPosZero())
13960 return N->getOperand(1);
13964 static SDValue PerformBTCombine(SDNode *N,
13966 TargetLowering::DAGCombinerInfo &DCI) {
13967 // BT ignores high bits in the bit index operand.
13968 SDValue Op1 = N->getOperand(1);
13969 if (Op1.hasOneUse()) {
13970 unsigned BitWidth = Op1.getValueSizeInBits();
13971 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13972 APInt KnownZero, KnownOne;
13973 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13974 !DCI.isBeforeLegalizeOps());
13975 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13976 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13977 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13978 DCI.CommitTargetLoweringOpt(TLO);
13983 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13984 SDValue Op = N->getOperand(0);
13985 if (Op.getOpcode() == ISD::BITCAST)
13986 Op = Op.getOperand(0);
13987 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13988 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13989 VT.getVectorElementType().getSizeInBits() ==
13990 OpVT.getVectorElementType().getSizeInBits()) {
13991 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13996 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13997 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
13998 // (and (i32 x86isd::setcc_carry), 1)
13999 // This eliminates the zext. This transformation is necessary because
14000 // ISD::SETCC is always legalized to i8.
14001 DebugLoc dl = N->getDebugLoc();
14002 SDValue N0 = N->getOperand(0);
14003 EVT VT = N->getValueType(0);
14004 if (N0.getOpcode() == ISD::AND &&
14006 N0.getOperand(0).hasOneUse()) {
14007 SDValue N00 = N0.getOperand(0);
14008 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14010 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14011 if (!C || C->getZExtValue() != 1)
14013 return DAG.getNode(ISD::AND, dl, VT,
14014 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14015 N00.getOperand(0), N00.getOperand(1)),
14016 DAG.getConstant(1, VT));
14022 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14023 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14024 unsigned X86CC = N->getConstantOperandVal(0);
14025 SDValue EFLAG = N->getOperand(1);
14026 DebugLoc DL = N->getDebugLoc();
14028 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14029 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14031 if (X86CC == X86::COND_B)
14032 return DAG.getNode(ISD::AND, DL, MVT::i8,
14033 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14034 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14035 DAG.getConstant(1, MVT::i8));
14040 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14041 const X86TargetLowering *XTLI) {
14042 SDValue Op0 = N->getOperand(0);
14043 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14044 // a 32-bit target where SSE doesn't support i64->FP operations.
14045 if (Op0.getOpcode() == ISD::LOAD) {
14046 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14047 EVT VT = Ld->getValueType(0);
14048 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14049 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14050 !XTLI->getSubtarget()->is64Bit() &&
14051 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14052 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14053 Ld->getChain(), Op0, DAG);
14054 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14061 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14062 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14063 X86TargetLowering::DAGCombinerInfo &DCI) {
14064 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14065 // the result is either zero or one (depending on the input carry bit).
14066 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14067 if (X86::isZeroNode(N->getOperand(0)) &&
14068 X86::isZeroNode(N->getOperand(1)) &&
14069 // We don't have a good way to replace an EFLAGS use, so only do this when
14071 SDValue(N, 1).use_empty()) {
14072 DebugLoc DL = N->getDebugLoc();
14073 EVT VT = N->getValueType(0);
14074 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14075 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14076 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14077 DAG.getConstant(X86::COND_B,MVT::i8),
14079 DAG.getConstant(1, VT));
14080 return DCI.CombineTo(N, Res1, CarryOut);
14086 // fold (add Y, (sete X, 0)) -> adc 0, Y
14087 // (add Y, (setne X, 0)) -> sbb -1, Y
14088 // (sub (sete X, 0), Y) -> sbb 0, Y
14089 // (sub (setne X, 0), Y) -> adc -1, Y
14090 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14091 DebugLoc DL = N->getDebugLoc();
14093 // Look through ZExts.
14094 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14095 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14098 SDValue SetCC = Ext.getOperand(0);
14099 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14102 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14103 if (CC != X86::COND_E && CC != X86::COND_NE)
14106 SDValue Cmp = SetCC.getOperand(1);
14107 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14108 !X86::isZeroNode(Cmp.getOperand(1)) ||
14109 !Cmp.getOperand(0).getValueType().isInteger())
14112 SDValue CmpOp0 = Cmp.getOperand(0);
14113 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14114 DAG.getConstant(1, CmpOp0.getValueType()));
14116 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14117 if (CC == X86::COND_NE)
14118 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14119 DL, OtherVal.getValueType(), OtherVal,
14120 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14121 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14122 DL, OtherVal.getValueType(), OtherVal,
14123 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14126 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14127 SDValue Op0 = N->getOperand(0);
14128 SDValue Op1 = N->getOperand(1);
14130 // X86 can't encode an immediate LHS of a sub. See if we can push the
14131 // negation into a preceding instruction.
14132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14133 // If the RHS of the sub is a XOR with one use and a constant, invert the
14134 // immediate. Then add one to the LHS of the sub so we can turn
14135 // X-Y -> X+~Y+1, saving one register.
14136 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14137 isa<ConstantSDNode>(Op1.getOperand(1))) {
14138 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14139 EVT VT = Op0.getValueType();
14140 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14142 DAG.getConstant(~XorC, VT));
14143 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14144 DAG.getConstant(C->getAPIntValue()+1, VT));
14148 return OptimizeConditionalInDecrement(N, DAG);
14151 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14152 DAGCombinerInfo &DCI) const {
14153 SelectionDAG &DAG = DCI.DAG;
14154 switch (N->getOpcode()) {
14156 case ISD::EXTRACT_VECTOR_ELT:
14157 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14159 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14160 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14161 case ISD::ADD: return OptimizeConditionalInDecrement(N, DAG);
14162 case ISD::SUB: return PerformSubCombine(N, DAG);
14163 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14164 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14167 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14168 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14169 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14170 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14171 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14172 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14173 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14174 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14176 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14177 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14178 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14179 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14180 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14181 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14182 case X86ISD::SHUFPS: // Handle all target specific shuffles
14183 case X86ISD::SHUFPD:
14184 case X86ISD::PALIGN:
14185 case X86ISD::PUNPCKHBW:
14186 case X86ISD::PUNPCKHWD:
14187 case X86ISD::PUNPCKHDQ:
14188 case X86ISD::PUNPCKHQDQ:
14189 case X86ISD::UNPCKHPS:
14190 case X86ISD::UNPCKHPD:
14191 case X86ISD::VUNPCKHPSY:
14192 case X86ISD::VUNPCKHPDY:
14193 case X86ISD::PUNPCKLBW:
14194 case X86ISD::PUNPCKLWD:
14195 case X86ISD::PUNPCKLDQ:
14196 case X86ISD::PUNPCKLQDQ:
14197 case X86ISD::UNPCKLPS:
14198 case X86ISD::UNPCKLPD:
14199 case X86ISD::VUNPCKLPSY:
14200 case X86ISD::VUNPCKLPDY:
14201 case X86ISD::MOVHLPS:
14202 case X86ISD::MOVLHPS:
14203 case X86ISD::PSHUFD:
14204 case X86ISD::PSHUFHW:
14205 case X86ISD::PSHUFLW:
14206 case X86ISD::MOVSS:
14207 case X86ISD::MOVSD:
14208 case X86ISD::VPERMILPS:
14209 case X86ISD::VPERMILPSY:
14210 case X86ISD::VPERMILPD:
14211 case X86ISD::VPERMILPDY:
14212 case X86ISD::VPERM2F128:
14213 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14219 /// isTypeDesirableForOp - Return true if the target has native support for
14220 /// the specified value type and it is 'desirable' to use the type for the
14221 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14222 /// instruction encodings are longer and some i16 instructions are slow.
14223 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14224 if (!isTypeLegal(VT))
14226 if (VT != MVT::i16)
14233 case ISD::SIGN_EXTEND:
14234 case ISD::ZERO_EXTEND:
14235 case ISD::ANY_EXTEND:
14248 /// IsDesirableToPromoteOp - This method query the target whether it is
14249 /// beneficial for dag combiner to promote the specified node. If true, it
14250 /// should return the desired promotion type by reference.
14251 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14252 EVT VT = Op.getValueType();
14253 if (VT != MVT::i16)
14256 bool Promote = false;
14257 bool Commute = false;
14258 switch (Op.getOpcode()) {
14261 LoadSDNode *LD = cast<LoadSDNode>(Op);
14262 // If the non-extending load has a single use and it's not live out, then it
14263 // might be folded.
14264 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14265 Op.hasOneUse()*/) {
14266 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14267 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14268 // The only case where we'd want to promote LOAD (rather then it being
14269 // promoted as an operand is when it's only use is liveout.
14270 if (UI->getOpcode() != ISD::CopyToReg)
14277 case ISD::SIGN_EXTEND:
14278 case ISD::ZERO_EXTEND:
14279 case ISD::ANY_EXTEND:
14284 SDValue N0 = Op.getOperand(0);
14285 // Look out for (store (shl (load), x)).
14286 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14299 SDValue N0 = Op.getOperand(0);
14300 SDValue N1 = Op.getOperand(1);
14301 if (!Commute && MayFoldLoad(N1))
14303 // Avoid disabling potential load folding opportunities.
14304 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14306 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14316 //===----------------------------------------------------------------------===//
14317 // X86 Inline Assembly Support
14318 //===----------------------------------------------------------------------===//
14320 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14321 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14323 std::string AsmStr = IA->getAsmString();
14325 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14326 SmallVector<StringRef, 4> AsmPieces;
14327 SplitString(AsmStr, AsmPieces, ";\n");
14329 switch (AsmPieces.size()) {
14330 default: return false;
14332 AsmStr = AsmPieces[0];
14334 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
14336 // FIXME: this should verify that we are targeting a 486 or better. If not,
14337 // we will turn this bswap into something that will be lowered to logical ops
14338 // instead of emitting the bswap asm. For now, we don't support 486 or lower
14339 // so don't worry about this.
14341 if (AsmPieces.size() == 2 &&
14342 (AsmPieces[0] == "bswap" ||
14343 AsmPieces[0] == "bswapq" ||
14344 AsmPieces[0] == "bswapl") &&
14345 (AsmPieces[1] == "$0" ||
14346 AsmPieces[1] == "${0:q}")) {
14347 // No need to check constraints, nothing other than the equivalent of
14348 // "=r,0" would be valid here.
14349 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14350 if (!Ty || Ty->getBitWidth() % 16 != 0)
14352 return IntrinsicLowering::LowerToByteSwap(CI);
14354 // rorw $$8, ${0:w} --> llvm.bswap.i16
14355 if (CI->getType()->isIntegerTy(16) &&
14356 AsmPieces.size() == 3 &&
14357 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14358 AsmPieces[1] == "$$8," &&
14359 AsmPieces[2] == "${0:w}" &&
14360 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14362 const std::string &ConstraintsStr = IA->getConstraintString();
14363 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14364 std::sort(AsmPieces.begin(), AsmPieces.end());
14365 if (AsmPieces.size() == 4 &&
14366 AsmPieces[0] == "~{cc}" &&
14367 AsmPieces[1] == "~{dirflag}" &&
14368 AsmPieces[2] == "~{flags}" &&
14369 AsmPieces[3] == "~{fpsr}") {
14370 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14371 if (!Ty || Ty->getBitWidth() % 16 != 0)
14373 return IntrinsicLowering::LowerToByteSwap(CI);
14378 if (CI->getType()->isIntegerTy(32) &&
14379 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14380 SmallVector<StringRef, 4> Words;
14381 SplitString(AsmPieces[0], Words, " \t,");
14382 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14383 Words[2] == "${0:w}") {
14385 SplitString(AsmPieces[1], Words, " \t,");
14386 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14387 Words[2] == "$0") {
14389 SplitString(AsmPieces[2], Words, " \t,");
14390 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14391 Words[2] == "${0:w}") {
14393 const std::string &ConstraintsStr = IA->getConstraintString();
14394 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14395 std::sort(AsmPieces.begin(), AsmPieces.end());
14396 if (AsmPieces.size() == 4 &&
14397 AsmPieces[0] == "~{cc}" &&
14398 AsmPieces[1] == "~{dirflag}" &&
14399 AsmPieces[2] == "~{flags}" &&
14400 AsmPieces[3] == "~{fpsr}") {
14401 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14402 if (!Ty || Ty->getBitWidth() % 16 != 0)
14404 return IntrinsicLowering::LowerToByteSwap(CI);
14411 if (CI->getType()->isIntegerTy(64)) {
14412 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14413 if (Constraints.size() >= 2 &&
14414 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14415 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14416 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14417 SmallVector<StringRef, 4> Words;
14418 SplitString(AsmPieces[0], Words, " \t");
14419 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14421 SplitString(AsmPieces[1], Words, " \t");
14422 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14424 SplitString(AsmPieces[2], Words, " \t,");
14425 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14426 Words[2] == "%edx") {
14427 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14428 if (!Ty || Ty->getBitWidth() % 16 != 0)
14430 return IntrinsicLowering::LowerToByteSwap(CI);
14443 /// getConstraintType - Given a constraint letter, return the type of
14444 /// constraint it is for this target.
14445 X86TargetLowering::ConstraintType
14446 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14447 if (Constraint.size() == 1) {
14448 switch (Constraint[0]) {
14459 return C_RegisterClass;
14483 return TargetLowering::getConstraintType(Constraint);
14486 /// Examine constraint type and operand type and determine a weight value.
14487 /// This object must already have been set up with the operand type
14488 /// and the current alternative constraint selected.
14489 TargetLowering::ConstraintWeight
14490 X86TargetLowering::getSingleConstraintMatchWeight(
14491 AsmOperandInfo &info, const char *constraint) const {
14492 ConstraintWeight weight = CW_Invalid;
14493 Value *CallOperandVal = info.CallOperandVal;
14494 // If we don't have a value, we can't do a match,
14495 // but allow it at the lowest weight.
14496 if (CallOperandVal == NULL)
14498 Type *type = CallOperandVal->getType();
14499 // Look at the constraint type.
14500 switch (*constraint) {
14502 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14513 if (CallOperandVal->getType()->isIntegerTy())
14514 weight = CW_SpecificReg;
14519 if (type->isFloatingPointTy())
14520 weight = CW_SpecificReg;
14523 if (type->isX86_MMXTy() && Subtarget->hasMMX())
14524 weight = CW_SpecificReg;
14528 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14529 weight = CW_Register;
14532 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14533 if (C->getZExtValue() <= 31)
14534 weight = CW_Constant;
14538 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14539 if (C->getZExtValue() <= 63)
14540 weight = CW_Constant;
14544 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14545 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14546 weight = CW_Constant;
14550 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14551 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14552 weight = CW_Constant;
14556 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14557 if (C->getZExtValue() <= 3)
14558 weight = CW_Constant;
14562 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14563 if (C->getZExtValue() <= 0xff)
14564 weight = CW_Constant;
14569 if (dyn_cast<ConstantFP>(CallOperandVal)) {
14570 weight = CW_Constant;
14574 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14575 if ((C->getSExtValue() >= -0x80000000LL) &&
14576 (C->getSExtValue() <= 0x7fffffffLL))
14577 weight = CW_Constant;
14581 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14582 if (C->getZExtValue() <= 0xffffffff)
14583 weight = CW_Constant;
14590 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14591 /// with another that has more specific requirements based on the type of the
14592 /// corresponding operand.
14593 const char *X86TargetLowering::
14594 LowerXConstraint(EVT ConstraintVT) const {
14595 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14596 // 'f' like normal targets.
14597 if (ConstraintVT.isFloatingPoint()) {
14598 if (Subtarget->hasXMMInt())
14600 if (Subtarget->hasXMM())
14604 return TargetLowering::LowerXConstraint(ConstraintVT);
14607 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14608 /// vector. If it is invalid, don't add anything to Ops.
14609 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14610 std::string &Constraint,
14611 std::vector<SDValue>&Ops,
14612 SelectionDAG &DAG) const {
14613 SDValue Result(0, 0);
14615 // Only support length 1 constraints for now.
14616 if (Constraint.length() > 1) return;
14618 char ConstraintLetter = Constraint[0];
14619 switch (ConstraintLetter) {
14622 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14623 if (C->getZExtValue() <= 31) {
14624 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14630 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14631 if (C->getZExtValue() <= 63) {
14632 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14638 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14639 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14640 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14646 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14647 if (C->getZExtValue() <= 255) {
14648 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14654 // 32-bit signed value
14655 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14656 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14657 C->getSExtValue())) {
14658 // Widen to 64 bits here to get it sign extended.
14659 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14662 // FIXME gcc accepts some relocatable values here too, but only in certain
14663 // memory models; it's complicated.
14668 // 32-bit unsigned value
14669 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14670 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14671 C->getZExtValue())) {
14672 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14676 // FIXME gcc accepts some relocatable values here too, but only in certain
14677 // memory models; it's complicated.
14681 // Literal immediates are always ok.
14682 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14683 // Widen to 64 bits here to get it sign extended.
14684 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14688 // In any sort of PIC mode addresses need to be computed at runtime by
14689 // adding in a register or some sort of table lookup. These can't
14690 // be used as immediates.
14691 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14694 // If we are in non-pic codegen mode, we allow the address of a global (with
14695 // an optional displacement) to be used with 'i'.
14696 GlobalAddressSDNode *GA = 0;
14697 int64_t Offset = 0;
14699 // Match either (GA), (GA+C), (GA+C1+C2), etc.
14701 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14702 Offset += GA->getOffset();
14704 } else if (Op.getOpcode() == ISD::ADD) {
14705 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14706 Offset += C->getZExtValue();
14707 Op = Op.getOperand(0);
14710 } else if (Op.getOpcode() == ISD::SUB) {
14711 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14712 Offset += -C->getZExtValue();
14713 Op = Op.getOperand(0);
14718 // Otherwise, this isn't something we can handle, reject it.
14722 const GlobalValue *GV = GA->getGlobal();
14723 // If we require an extra load to get this address, as in PIC mode, we
14724 // can't accept it.
14725 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14726 getTargetMachine())))
14729 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14730 GA->getValueType(0), Offset);
14735 if (Result.getNode()) {
14736 Ops.push_back(Result);
14739 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14742 std::pair<unsigned, const TargetRegisterClass*>
14743 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14745 // First, see if this is a constraint that directly corresponds to an LLVM
14747 if (Constraint.size() == 1) {
14748 // GCC Constraint Letters
14749 switch (Constraint[0]) {
14751 // TODO: Slight differences here in allocation order and leaving
14752 // RIP in the class. Do they matter any more here than they do
14753 // in the normal allocation?
14754 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14755 if (Subtarget->is64Bit()) {
14756 if (VT == MVT::i32 || VT == MVT::f32)
14757 return std::make_pair(0U, X86::GR32RegisterClass);
14758 else if (VT == MVT::i16)
14759 return std::make_pair(0U, X86::GR16RegisterClass);
14760 else if (VT == MVT::i8 || VT == MVT::i1)
14761 return std::make_pair(0U, X86::GR8RegisterClass);
14762 else if (VT == MVT::i64 || VT == MVT::f64)
14763 return std::make_pair(0U, X86::GR64RegisterClass);
14766 // 32-bit fallthrough
14767 case 'Q': // Q_REGS
14768 if (VT == MVT::i32 || VT == MVT::f32)
14769 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14770 else if (VT == MVT::i16)
14771 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14772 else if (VT == MVT::i8 || VT == MVT::i1)
14773 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14774 else if (VT == MVT::i64)
14775 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14777 case 'r': // GENERAL_REGS
14778 case 'l': // INDEX_REGS
14779 if (VT == MVT::i8 || VT == MVT::i1)
14780 return std::make_pair(0U, X86::GR8RegisterClass);
14781 if (VT == MVT::i16)
14782 return std::make_pair(0U, X86::GR16RegisterClass);
14783 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14784 return std::make_pair(0U, X86::GR32RegisterClass);
14785 return std::make_pair(0U, X86::GR64RegisterClass);
14786 case 'R': // LEGACY_REGS
14787 if (VT == MVT::i8 || VT == MVT::i1)
14788 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14789 if (VT == MVT::i16)
14790 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14791 if (VT == MVT::i32 || !Subtarget->is64Bit())
14792 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14793 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14794 case 'f': // FP Stack registers.
14795 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14796 // value to the correct fpstack register class.
14797 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14798 return std::make_pair(0U, X86::RFP32RegisterClass);
14799 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14800 return std::make_pair(0U, X86::RFP64RegisterClass);
14801 return std::make_pair(0U, X86::RFP80RegisterClass);
14802 case 'y': // MMX_REGS if MMX allowed.
14803 if (!Subtarget->hasMMX()) break;
14804 return std::make_pair(0U, X86::VR64RegisterClass);
14805 case 'Y': // SSE_REGS if SSE2 allowed
14806 if (!Subtarget->hasXMMInt()) break;
14808 case 'x': // SSE_REGS if SSE1 allowed
14809 if (!Subtarget->hasXMM()) break;
14811 switch (VT.getSimpleVT().SimpleTy) {
14813 // Scalar SSE types.
14816 return std::make_pair(0U, X86::FR32RegisterClass);
14819 return std::make_pair(0U, X86::FR64RegisterClass);
14827 return std::make_pair(0U, X86::VR128RegisterClass);
14833 // Use the default implementation in TargetLowering to convert the register
14834 // constraint into a member of a register class.
14835 std::pair<unsigned, const TargetRegisterClass*> Res;
14836 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14838 // Not found as a standard register?
14839 if (Res.second == 0) {
14840 // Map st(0) -> st(7) -> ST0
14841 if (Constraint.size() == 7 && Constraint[0] == '{' &&
14842 tolower(Constraint[1]) == 's' &&
14843 tolower(Constraint[2]) == 't' &&
14844 Constraint[3] == '(' &&
14845 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14846 Constraint[5] == ')' &&
14847 Constraint[6] == '}') {
14849 Res.first = X86::ST0+Constraint[4]-'0';
14850 Res.second = X86::RFP80RegisterClass;
14854 // GCC allows "st(0)" to be called just plain "st".
14855 if (StringRef("{st}").equals_lower(Constraint)) {
14856 Res.first = X86::ST0;
14857 Res.second = X86::RFP80RegisterClass;
14862 if (StringRef("{flags}").equals_lower(Constraint)) {
14863 Res.first = X86::EFLAGS;
14864 Res.second = X86::CCRRegisterClass;
14868 // 'A' means EAX + EDX.
14869 if (Constraint == "A") {
14870 Res.first = X86::EAX;
14871 Res.second = X86::GR32_ADRegisterClass;
14877 // Otherwise, check to see if this is a register class of the wrong value
14878 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14879 // turn into {ax},{dx}.
14880 if (Res.second->hasType(VT))
14881 return Res; // Correct type already, nothing to do.
14883 // All of the single-register GCC register classes map their values onto
14884 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
14885 // really want an 8-bit or 32-bit register, map to the appropriate register
14886 // class and return the appropriate register.
14887 if (Res.second == X86::GR16RegisterClass) {
14888 if (VT == MVT::i8) {
14889 unsigned DestReg = 0;
14890 switch (Res.first) {
14892 case X86::AX: DestReg = X86::AL; break;
14893 case X86::DX: DestReg = X86::DL; break;
14894 case X86::CX: DestReg = X86::CL; break;
14895 case X86::BX: DestReg = X86::BL; break;
14898 Res.first = DestReg;
14899 Res.second = X86::GR8RegisterClass;
14901 } else if (VT == MVT::i32) {
14902 unsigned DestReg = 0;
14903 switch (Res.first) {
14905 case X86::AX: DestReg = X86::EAX; break;
14906 case X86::DX: DestReg = X86::EDX; break;
14907 case X86::CX: DestReg = X86::ECX; break;
14908 case X86::BX: DestReg = X86::EBX; break;
14909 case X86::SI: DestReg = X86::ESI; break;
14910 case X86::DI: DestReg = X86::EDI; break;
14911 case X86::BP: DestReg = X86::EBP; break;
14912 case X86::SP: DestReg = X86::ESP; break;
14915 Res.first = DestReg;
14916 Res.second = X86::GR32RegisterClass;
14918 } else if (VT == MVT::i64) {
14919 unsigned DestReg = 0;
14920 switch (Res.first) {
14922 case X86::AX: DestReg = X86::RAX; break;
14923 case X86::DX: DestReg = X86::RDX; break;
14924 case X86::CX: DestReg = X86::RCX; break;
14925 case X86::BX: DestReg = X86::RBX; break;
14926 case X86::SI: DestReg = X86::RSI; break;
14927 case X86::DI: DestReg = X86::RDI; break;
14928 case X86::BP: DestReg = X86::RBP; break;
14929 case X86::SP: DestReg = X86::RSP; break;
14932 Res.first = DestReg;
14933 Res.second = X86::GR64RegisterClass;
14936 } else if (Res.second == X86::FR32RegisterClass ||
14937 Res.second == X86::FR64RegisterClass ||
14938 Res.second == X86::VR128RegisterClass) {
14939 // Handle references to XMM physical registers that got mapped into the
14940 // wrong class. This can happen with constraints like {xmm0} where the
14941 // target independent register mapper will just pick the first match it can
14942 // find, ignoring the required type.
14943 if (VT == MVT::f32)
14944 Res.second = X86::FR32RegisterClass;
14945 else if (VT == MVT::f64)
14946 Res.second = X86::FR64RegisterClass;
14947 else if (X86::VR128RegisterClass->hasType(VT))
14948 Res.second = X86::VR128RegisterClass;